Пример #1
0
        private void autoShowUpgrade()
        {
            string ver = P2pLib.GetInstance().GetLatestVer();

            if (ver.IsNullOrEmpty())
            {
                return;
            }

            bool has_windows = false;

            string[] ver_split = ver.Split(',');
            for (int i = 0; i < ver_split.Length; ++i)
            {
                string[] item = ver_split[i].Split(';');
                if (item.Length < 3)
                {
                    continue;
                }

                if (item[0].Equals("windows"))
                {
                    if (String.Compare(item[1], P2pLib.kCurrentVersion) <= 0)
                    {
                        return;
                    }
                    else
                    {
                        if (String.Compare(item[1], upgrade_shown_version) != 0)
                        {
                            upgrade_shown_version = item[1];
                            has_windows           = true;
                        }
                    }
                }
            }

            if (!has_windows)
            {
                return;
            }

            if (upgrade_is_shown)
            {
                return;
            }

            upgrade_is_shown = true;
            if (upgradeForm != null)
            {
                upgradeForm.Activate();
            }
            else
            {
                upgradeForm = new VersionControl(ver);
                upgradeForm.Show();
                upgradeForm.Activate();
                upgradeForm.FormClosed += tmp_upgradeForm_FormClosed;
            }
        }
Пример #2
0
        private void cboPlanets_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (P2pLib.GetInstance().connectStarted || P2pLib.GetInstance().disConnectStarted)
            {
                return;
            }

            int country_idx = cboPlanets.SelectedIndex;

            if (P2pLib.GetInstance().choose_country_ == P2pLib.GetInstance().now_countries_[country_idx])
            {
                return;
            }

            P2pLib.GetInstance().connectSuccess   = false;
            P2pLib.GetInstance().connectStarted   = true;
            P2pLib.GetInstance().use_smart_route_ = true;

            SynchronizationContext syncContext = SynchronizationContext.Current;
            Thread tmp_thread = new Thread(() =>
            {
                P2pLib.GetInstance().choose_country_ = P2pLib.GetInstance().now_countries_[country_idx];
                Configuration.RandomNode();
                controller.ToggleEnable(true);
                controller.ToggleGlobal(true);
                P2pLib.GetInstance().connectSuccess = true;
                P2pLib.GetInstance().connectStarted = false;
                syncContext.Post(this.ConnectButton.ThreadRefresh, null);
            });

            tmp_thread.IsBackground = true;
            tmp_thread.Start();
        }
Пример #3
0
        public void CreateRemote()
        {
            Server server = _controller.GetAServer(IStrategyCallerType.TCP, (IPEndPoint)_connection.RemoteEndPoint,
                                                   _destEndPoint);

            if (server == null || server.server == "")
            {
                throw new ArgumentException("No server configured");
            }

            _encryptor = EncryptorFactory.GetEncryptor(P2pLib.GetInstance().enc_method_, P2pLib.GetInstance().seckey_);

            string ip   = "";
            ushort port = 0;
            int    res  = P2pLib.GetInstance().GetRemoteNode(ref ip, ref port);

            if (res == 0)
            {
                server.server      = ip;
                server.server_port = port;
            }

            this._server = server;

            /* prepare address buffer length for AEAD */
            Logging.Debug($"_addrBufLength={_addrBufLength}, remote server: {server.server}," +
                          $" remote port: {server.server_port}, connect times: {TCPRelay.connect_times_} " +
                          $"vpn server: {P2pLib.GetInstance().str_vpn_ip_} vpn port: {P2pLib.GetInstance().vpn_port_}");
            _encryptor.AddrBufLength = _addrBufLength;
        }
Пример #4
0
        private void button2_Click(object sender, EventArgs e)
        {
            // prikey paste
            IDataObject iData = Clipboard.GetDataObject();

            if (iData.GetDataPresent(DataFormats.Text))
            {
                string prikey = ((String)iData.GetData(DataFormats.Text)).Trim();
                if (prikey.Equals(P2pLib.GetInstance().prikey_))
                {
                    return;
                }

                if (prikey.Length != 64)
                {
                    MessageBox.Show(I18N.GetString("invalid private key."));
                    return;
                }

                if (!P2pLib.GetInstance().SavePrivateKey(prikey))
                {
                    MessageBox.Show(I18N.GetString("Set up to 3 private keys."));
                    return;
                }

                if (!P2pLib.GetInstance().ResetPrivateKey(prikey))
                {
                    MessageBox.Show(I18N.GetString("invalid private key."));
                    return;
                }

                MessageBox.Show(I18N.GetString("after success reset private key, must restart program."));
                Application.Exit();
            }
        }
Пример #5
0
        private void ConfigForm_Load_1(object sender, EventArgs e)
        {
            // Make a font for the item text.
            Font   font = new Font("Times New Roman", 14);
            Random ran  = new Random();
            int    n    = ran.Next(100, 1000);

            // Make image and text data.
            ImageAndText[] planets =
            {
                new ImageAndText(Resources.us,  "America" + '\n' + ran.Next(100,     1000) + " nodes", font),
                new ImageAndText(Resources.sg,  "Singapore" + '\n' + ran.Next(100,   1000) + " nodes", font),
                new ImageAndText(Resources.br,  "Brazil" + '\n' + ran.Next(100,      1000) + " nodes", font),
                new ImageAndText(Resources.de,  "Germany" + '\n' + ran.Next(100,     1000) + " nodes", font),
                new ImageAndText(Resources.nl,  "Netherlands" + '\n' + ran.Next(100, 1000) + " nodes", font),
                new ImageAndText(Resources.fr,  "France" + '\n' + ran.Next(100,      1000) + " nodes", font),
                new ImageAndText(Resources.kr,  "Korea" + '\n' + ran.Next(100,       1000) + " nodes", font),
                new ImageAndText(Resources.jp,  "Japan" + '\n' + ran.Next(100,       1000) + " nodes", font),
                new ImageAndText(Resources.ca,  "Canada" + '\n' + ran.Next(100,      1000) + " nodes", font),
                new ImageAndText(Resources.au,  "Australia" + '\n' + ran.Next(100,   1000) + " nodes", font),
                new ImageAndText(Resources.hk,  "Hong Kong" + '\n' + ran.Next(100,   1000) + " nodes", font),
                new ImageAndText(Resources.in1, "India" + '\n' + ran.Next(100,       1000) + " nodes", font),
                new ImageAndText(Resources.gb,  "England" + '\n' + ran.Next(100,     1000) + " nodes", font),
                new ImageAndText(Resources.cn,  "China" + '\n' + ran.Next(100,       1000) + " nodes", font),
            };

            cboPlanets.DisplayImagesAndText(planets);
            int select_idx = 0;

            for (int i = 0; i < P2pLib.GetInstance().now_countries_.Count; ++i)
            {
                if (P2pLib.GetInstance().now_countries_[i] == P2pLib.GetInstance().choose_country_)
                {
                    select_idx = i;
                    break;
                }
            }
            cboPlanets.SelectedIndex = select_idx;

            this.button2.Text = I18N.GetString("UPGRADE");
            this.button4.Text = I18N.GetString("SETTINGS");
            this.label7.Text  = I18N.GetString("Tenon p2p network protecting your privacy.");
            this.label6.Text  = I18N.GetString("Balance");
            this.label9.Text  = I18N.GetString("");
            this.label10.Text = I18N.GetString("waiting server...");
            this.label12.Text = I18N.GetString("Share to friends and earn the tenon coin.");

            _syncContext   = SynchronizationContext.Current;
            progressThread = new Thread(() =>
            {
                while (true)
                {
                    _syncContext.Post(ResetBalance, null);
                    Thread.Sleep(1000);
                }
            });
            progressThread.IsBackground = true;
            progressThread.Start();
        }
Пример #6
0
        private void Connect_Click(object sender, EventArgs e)
        {
            this.label8.Text = I18N.GetString("");
            if (P2pLib.GetInstance().server_status.Equals("bwo"))
            {
                showOutbandDialog();
                P2pLib.GetInstance().server_status = "ok";
                return;
            }
            SynchronizationContext syncContext = SynchronizationContext.Current;

            if (P2pLib.GetInstance().connectSuccess)
            {
                if (P2pLib.GetInstance().disConnectStarted)
                {
                    return;
                }
                P2pLib.GetInstance().disConnectStarted = true;

                Thread tmp_thread = new Thread(() =>
                {
                    controller.Stop();
                    controller.ToggleEnable(false);
                    P2pLib.GetInstance().connectSuccess = false;
                    P2pLib.GetInstance().connectStarted = false;
                    syncContext.Post(ConnectButton.ThreadRefresh, null);
                    P2pLib.GetInstance().disConnectStarted = false;
                });
                tmp_thread.IsBackground = true;
                tmp_thread.Start();
            }
            else
            {
                if (P2pLib.GetInstance().connectStarted)
                {
                    return;
                }

                P2pLib.GetInstance().connectStarted   = true;
                P2pLib.GetInstance().use_smart_route_ = true;
                int    country_idx = cboPlanets.SelectedIndex;
                Thread tmp_thread  = new Thread(() =>
                {
                    P2pLib.GetInstance().choose_country_ = P2pLib.GetInstance().now_countries_[country_idx];
                    Configuration.RandomNode();
                    controller.ToggleEnable(true);
                    controller.ToggleGlobal(true);
                    P2pLib.GetInstance().connectSuccess = true;
                    P2pLib.GetInstance().connectStarted = false;
                    syncContext.Post(this.ConnectButton.ThreadRefresh, null);
                });
                tmp_thread.IsBackground = true;
                tmp_thread.Start();
            }
        }
Пример #7
0
        public ProxyForm(ShadowsocksController controller)
        {
            this.Font = System.Drawing.SystemFonts.MessageBoxFont;
            InitializeComponent();

            this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon());

            this.controller = controller;

            string trans_str = P2pLib.GetInstance().Trans();

            if (!trans_str.IsNullOrEmpty())
            {
                string[] items = trans_str.Split(';');
                for (int i = 0; i < items.Length; ++i)
                {
                    string[] item = items[i].Split(',');
                    if (item.Length < 4)
                    {
                        continue;
                    }
                    int index = this.dataGridView1.Rows.Add();
                    this.dataGridView1.Rows[index].Cells[0].Value = item[0];
                    this.dataGridView1.Rows[index].Cells[1].Value = item[1];
                    this.dataGridView1.Rows[index].Cells[2].Value = (
                        item[2].Substring(0, 7).ToUpper() + "..." +
                        item[2].Substring(item[2].Length - 7, 7).ToUpper());
                    this.dataGridView1.Rows[index].Cells[3].Value = item[3];
                }
            }
            richTextBox2.Text = P2pLib.GetInstance().prikey_.ToUpper();
            richTextBox1.Text = P2pLib.GetInstance().account_id_.ToUpper();
            long balance = P2pLib.GetInstance().Balance();

            if (balance >= 0)
            {
                label4.Text = balance + " Tenon";
                label5.Text = Math.Round(balance * 0.002, 3) + "$";
            }
            else
            {
                label4.Text = "-- Tenon";
                label5.Text = "--$";
            }

            this.label2.Text       = I18N.GetString("Account");
            this.label3.Text       = I18N.GetString("Balance");
            this.label6.Text       = I18N.GetString("Transactions");
            this.label7.Text       = I18N.GetString("Global Mode");
            this.button1.Text      = I18N.GetString("copy");
            this.button3.Text      = I18N.GetString("copy");
            this.button2.Text      = I18N.GetString("paste");
            this.checkBox1.Checked = P2pLib.GetInstance().global_mode_;
        }
Пример #8
0
 private void Quit_Click(object sender, EventArgs e)
 {
     controller.Stop();
     controller.ToggleEnable(false);
     P2pLib.GetInstance().connectSuccess    = false;
     P2pLib.GetInstance().connectStarted    = false;
     P2pLib.GetInstance().disConnectStarted = false;
     Process.GetCurrentProcess().Kill();
     System.Environment.Exit(0);
     _notifyIcon.Visible = false;
     Application.Exit();
 }
Пример #9
0
        public Button_WOC()
        {
            DoubleBuffered = true;
            MouseEnter    += (sender, e) =>
            {
                _isHovering = true;
                Invalidate();
            };
            MouseLeave += (sender, e) =>
            {
                _isHovering = false;
                Invalidate();
            };

            _font1         = Font;
            _font2         = Font;
            _font3         = Font;
            _syncContext   = SynchronizationContext.Current;
            progressThread = new Thread(() =>
            {
                while (_enabled)
                {
                    if (P2pLib.GetInstance().connectStarted || P2pLib.GetInstance().disConnectStarted)
                    {
                        _progress += 2;
                        if (_progress >= 360)
                        {
                            _progress = 0;
                        }

                        _syncContext.Post(ThreadRefresh, null);
                    }
                    Thread.Sleep(10);
                }
            });
            progressThread.IsBackground = true;
            progressThread.Start();
        }
Пример #10
0
        private void SendToServer(int length, AsyncSession session)
        {
            _totalWrite += length;
            int bytesToSend;

            lock (_encryptionLock)
            {
                try
                {
                    _encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend);
                }
                catch (CryptoErrorException)
                {
                    Logging.Debug("encryption error");
                    Close();
                    return;
                }
            }

            if (!_has_sent)
            {
                List <byte> header_bytes = new List <byte>();
                int         append_size  = 0;
                if (P2pLib.GetInstance().use_smart_route_)
                {
                    string ex_route_ip   = "";
                    ushort ex_route_port = 0;
                    if (P2pLib.GetInstance().GetExRouteNode(ref ex_route_ip, ref ex_route_port) == 0)
                    {
                        RouteHeader tmp_rth = new RouteHeader();
                        tmp_rth.ip   = P2pLib.IpToInt(ex_route_ip);
                        tmp_rth.port = (ushort)(((ex_route_port & 0xff) << 8) |
                                                ((ex_route_port >> 8) & 0xff));
                        byte[] tmp_bt = RouteHeader.StuctToByte(tmp_rth);
                        header_bytes.AddRange(tmp_bt);
                        append_size += 6;
                    }
                    RouteHeader rth = new RouteHeader();
                    rth.ip   = P2pLib.GetInstance().vpn_ip_;
                    rth.port = (ushort)((
                                            (P2pLib.GetInstance().vpn_port_ & 0xff) << 8) |
                                        ((P2pLib.GetInstance().vpn_port_ >> 8) & 0xff));
                    byte[] bt = RouteHeader.StuctToByte(rth);
                    header_bytes.AddRange(bt);
                    append_size += 6;
                }

                string pubkey     = P2pLib.GetInstance().pubkey_;
                byte[] pubkey_arr = System.Text.Encoding.Default.GetBytes(pubkey);
                header_bytes.AddRange(pubkey_arr);

                string method = _server.method;
                header_bytes.Add((byte)method.Length);
                byte[] method_arr = System.Text.Encoding.Default.GetBytes(method);
                header_bytes.AddRange(method_arr);

                header_bytes.AddRange(_connetionSendBuffer);
                bytesToSend += pubkey.Length + 1 + method.Length + append_size;
                byte[] final_bytes = header_bytes.ToArray();
                Array.Copy(final_bytes, _connetionSendBuffer, bytesToSend);
                _has_sent = true;
            }

            _tcprelay.UpdateOutboundCounter(_server, bytesToSend);
            _startSendingTime = DateTime.Now;
            Logging.Debug($"SendToServer: {bytesToSend}");

            session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None,
                                     PipeRemoteSendCallback, new object[] { session, bytesToSend });
            IStrategy strategy = _controller.GetCurrentStrategy();

            strategy?.UpdateLastWrite(_server);
        }
Пример #11
0
        static void Main(string[] args)
        {
            // .NET Framework 4.7.2 on Win7 compatibility
            System.Net.ServicePointManager.SecurityProtocol |=
                System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

            // store args for further use
            Args = args;
            // Check OS since we are using dual-mode socket
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check .NET Framework version
            if (!Utils.IsSupportedRuntimeVersion())
            {
                MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to 4.6.2 or later."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                Process.Start(
                    "https://www.microsoft.com/download/details.aspx?id=53344");
                return;
            }

            Utils.ReleaseMemory(true);
            using (Mutex mutex = new Mutex(false, $"Global\\Shadowsocks_{Application.StartupPath.GetHashCode()}"))
            {
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                // handle UI exceptions
                Application.ThreadException += Application_ThreadException;
                // handle non-UI exceptions
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.ApplicationExit   += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                AutoStartup.RegisterForRestart(true);

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
                                    + Environment.NewLine
                                    + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                    I18N.GetString("Shadowsocks is already running."));
                    return;
                }
                Directory.SetCurrentDirectory(Application.StartupPath);
                Logging.OpenLogFile();

                int init_res = P2pLib.GetInstance().InitNetwork();
                if (init_res != 0)
                {
                    MessageBox.Show(I18N.GetString("init p2p network failed, please check out your network."));
                    return;
                }
#if DEBUG
                // truncate privoxy log file while debugging
                string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
                if (File.Exists(privoxyLogFilename))
                {
                    using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
                }
#else
                Logging.OpenLogFile();
#endif
                MainController = new ShadowsocksController();
                MenuController = new MenuViewController(MainController);
                HotKeys.Init(MainController);
                MainController.Start();
                Application.Run();
            }
        }
Пример #12
0
 private void button1_Click(object sender, EventArgs e)
 {
     // prikey copy
     Clipboard.SetDataObject(P2pLib.GetInstance().prikey_);
 }
Пример #13
0
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox tmpBox = sender as CheckBox;

            P2pLib.GetInstance().SetGlobalMode(tmpBox.Checked);
        }
Пример #14
0
        private void checkServerInfo(bool show_message)
        {
            string ver = P2pLib.GetInstance().GetLatestVer();

            if (ver.IsNullOrEmpty())
            {
                if (show_message)
                {
                    MessageBox.Show(I18N.GetString("Already the latest version."));
                }

                return;
            }

            bool has_windows = false;

            string[] ver_split = ver.Split(',');
            for (int i = 0; i < ver_split.Length; ++i)
            {
                string[] item = ver_split[i].Split(';');
                if (item.Length < 3)
                {
                    continue;
                }

                if (item[0].Equals("windows"))
                {
                    if (String.Compare(item[1], P2pLib.kCurrentVersion) <= 0)
                    {
                        if (show_message)
                        {
                            MessageBox.Show(I18N.GetString("Already the latest version."));
                            return;
                        }
                    }
                    else
                    {
                        has_windows = true;
                    }
                }

                if (item[0].Equals("share_ip"))
                {
                    if (!item[1].IsNullOrEmpty())
                    {
                        if (item[1].StartsWith("http"))
                        {
                            P2pLib.GetInstance().share_ip_ = item[1];
                        }
                        else
                        {
                            P2pLib.GetInstance().share_ip_ = "http://" + item[1];
                        }
                    }
                }

                if (item[0].Equals("buy_ip"))
                {
                    if (!item[1].IsNullOrEmpty())
                    {
                        if (item[1].StartsWith("http"))
                        {
                            P2pLib.GetInstance().buy_tenon_ip_ = item[1];
                        }
                        else
                        {
                            P2pLib.GetInstance().buy_tenon_ip_ = "http://" + item[1];
                        }
                    }
                }

                if (item[0].Equals("er"))
                {
                    P2pLib.GetInstance().SetExRouting(item[1]);
                }
            }

            if (!has_windows)
            {
                if (show_message)
                {
                    MessageBox.Show(I18N.GetString("Already the latest version."));
                }
                return;
            }

            if (upgrade_is_shown)
            {
                return;
            }

            if (!show_message)
            {
                return;
            }
            upgrade_is_shown = true;
            if (upgradeForm != null)
            {
                upgradeForm.Activate();
            }
            else
            {
                upgradeForm = new VersionControl(ver);
                upgradeForm.Show();
                upgradeForm.Activate();
                upgradeForm.FormClosed += tmp_upgradeForm_FormClosed;
            }
        }
Пример #15
0
 private void label12_Click(object sender, EventArgs e)
 {
     // share
     Clipboard.SetDataObject(P2pLib.GetInstance().share_ip_ + "?id=" + P2pLib.GetInstance().account_id_);
     MessageBox.Show(I18N.GetString("Copy sharing link succeeded."));
 }
Пример #16
0
        public static Configuration Load()
        {
            lock (locker) {
                if (loaded)
                {
                    return(config_loaded);
                }
                try
                {
                    //                 string configContent = File.ReadAllText(CONFIG_FILE);
                    config_loaded           = new Configuration(); //JsonConvert.DeserializeObject<Configuration>(configContent);
                    config_loaded.global    = true;
                    config_loaded.enabled   = true;
                    config_loaded.isDefault = true;

                    if (config_loaded.configs == null)
                    {
                        config_loaded.configs = new List <Server>();
                    }
                    //                 if (config.configs.Count == 0)
                    //                     config.configs.Add(GetDefaultServer());
                    if (config_loaded.localPort == 0)
                    {
                        config_loaded.localPort = 1080;
                    }
                    if (config_loaded.index == -1 && config_loaded.strategy == null)
                    {
                        config_loaded.index = 0;
                    }
                    if (config_loaded.logViewer == null)
                    {
                        config_loaded.logViewer = new LogViewerConfig();
                    }
                    if (config_loaded.proxy == null)
                    {
                        config_loaded.proxy = new ProxyConfig();
                    }
                    if (config_loaded.hotkey == null)
                    {
                        config_loaded.hotkey = new HotkeyConfig();
                    }
                    if (!System.Net.Sockets.Socket.OSSupportsIPv6)
                    {
                        config_loaded.isIPv6Enabled = false; // disable IPv6 if os not support
                    }
                    //TODO if remote host(server) do not support IPv6 (or DNS resolve AAAA TYPE record) disable IPv6?

                    string route_ip   = "";
                    ushort route_port = 0;
                    string def_route  = P2pLib.GetInstance().local_country_;
                    if (P2pLib.GetInstance().default_routing_map_.ContainsKey(P2pLib.GetInstance().local_country_))
                    {
                        def_route = P2pLib.GetInstance().default_routing_map_[P2pLib.GetInstance().local_country_];
                    }

                    int res = P2pLib.GetInstance().GetOneRouteNode(def_route, ref route_ip, ref route_port);
                    if (res != 0)
                    {
                        res = P2pLib.GetInstance().GetOneRouteNode(P2pLib.GetInstance().choose_country_, ref route_ip, ref route_port);
                        if (res != 0)
                        {
                            foreach (var country in P2pLib.GetInstance().now_countries_)
                            {
                                res = P2pLib.GetInstance().GetOneRouteNode(country, ref route_ip, ref route_port);
                                if (res == 0)
                                {
                                    break;
                                }
                            }
                        }

                        if (res != 0)
                        {
                            MessageBox.Show("waiting to get route nodes from p2p network. try again...");
                            return(config_loaded);
                        }
                    }

                    string vpn_ip     = "";
                    ushort vpn_port   = 0;
                    string svr_passwd = "";
                    res = P2pLib.GetInstance().GetOneVpnNode(P2pLib.GetInstance().choose_country_, ref vpn_ip, ref vpn_port, ref svr_passwd);
                    if (res != 0)
                    {
                        if (res != 0)
                        {
                            foreach (var country in P2pLib.GetInstance().now_countries_)
                            {
                                res = P2pLib.GetInstance().GetOneVpnNode(country, ref vpn_ip, ref vpn_port, ref svr_passwd);
                                if (res == 0)
                                {
                                    break;
                                }
                            }
                        }

                        if (res != 0)
                        {
                            MessageBox.Show("waiting to get vpn nodes from p2p network. try again...");
                            return(config_loaded);
                        }
                    }

                    string ip   = vpn_ip;
                    ushort port = vpn_port;
                    if (P2pLib.GetInstance().use_smart_route_)
                    {
                        ip   = route_ip;
                        port = route_port;
                    }

                    Server server = new Server()
                    {
                        server      = ip,
                        server_port = port,
                        password    = svr_passwd,
                        method      = P2pLib.GetInstance().enc_method_,
                        plugin      = "",
                        plugin_opts = "",
                        plugin_args = "",
                        remarks     = "",
                        timeout     = 10,
                    };

                    config_loaded.configs.Add(server);
                    config_loaded.proxy.CheckConfig();
                    loaded = true;
                    return(config_loaded);
                }
                catch (Exception e)
                {
                    if (!(e is FileNotFoundException))
                    {
                        Logging.LogUsefulException(e);
                    }
                    return(null);
                }
            }
        }
Пример #17
0
        private void OnAddressFullyRead(IAsyncResult ar)
        {
            if (_closed)
            {
                return;
            }
            try
            {
                int bytesRead = _connection.EndReceive(ar);

                var states = (object[])ar.AsyncState;

                int bytesRemain = (int)states[0];
                var onSuccess   = (Action)states[1];

                if (bytesRead >= bytesRemain)
                {
                    _firstPacketLength = bytesRead + 2;

                    int atyp = _connetionRecvBuffer[0];

                    string dstAddr = "Unknown";
                    int    dstPort = -1;
                    switch (atyp)
                    {
                    case ATYP_IPv4:     // IPv4 address, 4 bytes
                        dstAddr        = new IPAddress(_connetionRecvBuffer.Skip(1).Take(4).ToArray()).ToString();
                        dstPort        = (_connetionRecvBuffer[5] << 8) + _connetionRecvBuffer[6];
                        _addrBufLength = ADDR_ATYP_LEN + 4 + ADDR_PORT_LEN;
                        if (!P2pLib.GetInstance().global_mode_)
                        {
                            try
                            {
                                string ip_country = P2pLib.GetInstance().GetIpCountry(dstAddr.ToString());
                                if (ip_country == P2pLib.GetInstance().local_country_)
                                {
                                    P2pLib.GetInstance().AddLocalSites(dstAddr);
                                }
                            }
                            catch
                            {
                            }
                        }

                        break;

                    case ATYP_DOMAIN:     // domain name, length + str
                        int len = _connetionRecvBuffer[1];
                        dstAddr = System.Text.Encoding.UTF8.GetString(_connetionRecvBuffer, 2, len);
                        dstPort = (_connetionRecvBuffer[len + 2] << 8) + _connetionRecvBuffer[len + 3];

                        if (!P2pLib.GetInstance().global_mode_)
                        {
                            try
                            {
                                IPHostEntry IPinfo = Dns.GetHostEntry(dstAddr);
                                //显示IP地址
                                int valid_count = 0;
                                foreach (IPAddress IP in IPinfo.AddressList)
                                {
                                    string country = P2pLib.GetInstance().GetIpCountry(IP.ToString());
                                    if (country == P2pLib.GetInstance().local_country_)
                                    {
                                        valid_count++;
                                    }
                                }

                                if (valid_count > (IPinfo.AddressList.Length / 2))
                                {
                                    P2pLib.GetInstance().AddLocalSites(dstAddr);
                                }
                            }
                            catch (Exception e)
                            {
                            }
                        }


                        _addrBufLength = ADDR_ATYP_LEN + 1 + len + ADDR_PORT_LEN;
                        break;

                    case ATYP_IPv6:     // IPv6 address, 16 bytes
                        dstAddr = $"[{new IPAddress(_connetionRecvBuffer.Skip(1).Take(16).ToArray())}]";
                        dstPort = (_connetionRecvBuffer[17] << 8) + _connetionRecvBuffer[18];

                        _addrBufLength = ADDR_ATYP_LEN + 16 + ADDR_PORT_LEN;
                        break;
                    }


                    if (_config.isVerboseLogging)
                    {
                        Logging.Info($"connect to {dstAddr}:{dstPort}");
                    }

                    _destEndPoint = SocketUtil.GetEndPoint(dstAddr, dstPort);

                    onSuccess.Invoke(); /* StartConnect() */
                }
                else
                {
                    Logging.Debug("failed to recv data in Shadowsocks.Controller.TCPHandler.OnAddressFullyRead()");
                    Close();
                }
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }
Пример #18
0
        protected override void OnPaint(PaintEventArgs e)
        {
            if (P2pLib.GetInstance().connectSuccess)
            {
                _borderColor        = Color.FromArgb(0, 184, 170);
                _onHoverBorderColor = Color.FromArgb(86, 224, 208);
                _buttonColor        = Color.FromArgb(3, 134, 120);
                _onHoverButtonColor = Color.FromArgb(0, 184, 170);
                _textColor          = System.Drawing.SystemColors.ButtonHighlight;
                _onHoverTextColor   = System.Drawing.SystemColors.ButtonHighlight;
            }
            else
            {
                _borderColor        = System.Drawing.Color.WhiteSmoke;
                _onHoverBorderColor = System.Drawing.Color.Gainsboro;
                _buttonColor        = System.Drawing.Color.LightGray;
                _onHoverButtonColor = System.Drawing.Color.Silver;
                _textColor          = System.Drawing.SystemColors.ButtonHighlight;
                _onHoverTextColor   = System.Drawing.SystemColors.ButtonHighlight;
            }
            if (P2pLib.GetInstance().connectStarted || P2pLib.GetInstance().disConnectStarted)
            {
                _isHovering = false;
            }

            base.OnPaint(e);
            {
                Graphics g = e.Graphics;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                Brush brush = new SolidBrush(_isHovering ? _onHoverBorderColor : _borderColor);

                //Border
                //g.FillEllipse(brush, 0, 0, Height - 2, Height - 2);
                g.FillEllipse(brush, Width - Height + 1, 1, Height - 2, Height - 2);
                //g.FillRectangle(brush, Height / 2, 0, Width - Height, Height);

                brush.Dispose();
                brush = new SolidBrush(_isHovering ? _onHoverButtonColor : _buttonColor);

                //Inner part. Button itself
                g.FillEllipse(brush, _borderThicknessByTwo, _borderThicknessByTwo, Height - _borderThickness,
                              Height - _borderThickness);
                g.FillEllipse(brush, (Width - Height) + _borderThicknessByTwo, _borderThicknessByTwo,
                              Height - _borderThickness, Height - _borderThickness);
                g.FillRectangle(brush, Height / 2 + _borderThicknessByTwo, _borderThicknessByTwo,
                                Width - Height - _borderThickness, Height - _borderThickness);

                brush.Dispose();
                brush = new SolidBrush(_isHovering ? _onHoverTextColor : _textColor);
                //Button Text
                RectangleF rect = new RectangleF(Width / 2 - 35, Height / 2 - 55, 70, 70);
                e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
                if (P2pLib.GetInstance().connectSuccess)
                {
                    Text = "Connected";
                    SizeF stringSize = g.MeasureString(Text, _font1);
                    g.DrawString(Text, _font1, brush, (Width - stringSize.Width) / 2, 48 + (Height - stringSize.Height) / 2);
                    e.Graphics.DrawImage(Resources.connected, rect);
                }
                else
                {
                    Text = "Connect";
                    SizeF stringSize = g.MeasureString(Text, _font1);
                    g.DrawString(Text, _font1, brush, (Width - stringSize.Width) / 2, 48 + (Height - stringSize.Height) / 2);
                    e.Graphics.DrawImage(Resources.connect, rect);
                }
            }

            if (P2pLib.GetInstance().connectStarted || P2pLib.GetInstance().disConnectStarted)
            {
                var pen1 = new Pen(_color1, _line1Thinkness);
                var pen2 = new Pen(Color.FromArgb(0, 114, 108), _line1Thinkness);

                var circleRadius = _ignoreHeight
                    ? (Width - ProgressLineThikness)
                    : (Width > Height ? (Height - ProgressLineThikness) : (Width - ProgressLineThikness));
                var radiusByTwo      = circleRadius / 2;
                var progressEndAngle = (_angle) / 100F;

                e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
                e.Graphics.TranslateTransform(_line2Thinkness / 2F + radiusByTwo, _line2Thinkness / 2F + radiusByTwo);
                e.Graphics.RotateTransform((360 - _angle) / 2 + 90);

                if (P2pLib.GetInstance().disConnectStarted)
                {
                    e.Graphics.DrawArc(pen2, -radiusByTwo, -radiusByTwo, circleRadius, circleRadius, _progress, 30);
                }
                else
                {
                    e.Graphics.DrawArc(pen1, -radiusByTwo, -radiusByTwo, circleRadius, circleRadius, _progress, 30);
                }
                pen1.Dispose();
                pen2.Dispose();
            }
        }
Пример #19
0
        public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)
        {
            if (connect_times_ > 11)
            {
                P2pLib.GetInstance().ChooseOneVpnNode();
                if (old_ip != P2pLib.GetInstance().vpn_ip_)
                {
                    connect_times_ = 0;
                    old_ip         = P2pLib.GetInstance().vpn_ip_;
                }

                if (connect_times_ > 20)
                {
                    connect_times_ = 0;
//                     P2pLib.GetInstance().ServerStatusChange("cnn");
//                     return false;
                }
            }
            if (socket.ProtocolType != ProtocolType.Tcp ||
                (length < 2 || firstPacket[0] != 5))
            {
                return(false);
            }
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            TCPHandler handler = new TCPHandler(_controller, _config, this, socket);

            if (old_ip == 0)
            {
                old_ip = P2pLib.GetInstance().vpn_ip_;
            }
            ++connect_times_;
            IList <TCPHandler> handlersToClose = new List <TCPHandler>();

            lock (Handlers)
            {
                Handlers.Add(handler);
                DateTime now = DateTime.Now;
                if (now - _lastSweepTime > TimeSpan.FromSeconds(1))
                {
                    _lastSweepTime = now;
                    foreach (TCPHandler handler1 in Handlers)
                    {
                        if (now - handler1.lastActivity > TimeSpan.FromSeconds(900))
                        {
                            handlersToClose.Add(handler1);
                        }
                    }
                }
            }
            foreach (TCPHandler handler1 in handlersToClose)
            {
                Logging.Debug("Closing timed out TCP connection.");
                handler1.Close();
            }

            /*
             * Start after we put it into Handlers set. Otherwise if it failed in handler.Start()
             * then it will call handler.Close() before we add it into the set.
             * Then the handler will never release until the next Handle call. Sometimes it will
             * cause odd problems (especially during memory profiling).
             */
            handler.Start(firstPacket, length);

            return(true);
        }
Пример #20
0
 private void button3_Click(object sender, EventArgs e)
 {
     // account copy
     Clipboard.SetDataObject(P2pLib.GetInstance().account_id_);
 }
Пример #21
0
        private void PipeRemoteReceiveCallback(IAsyncResult ar)
        {
            if (_closed)
            {
                return;
            }
            try
            {
                var session   = (AsyncSession)ar.AsyncState;
                int bytesRead = session.Remote.EndReceive(ar);
                _totalRead += bytesRead;
                _tcprelay.UpdateInboundCounter(_server, bytesRead);

                if (bytesRead == 3)
                {
                    string str = System.Text.Encoding.Default.GetString(_remoteRecvBuffer, 0, 3);
                    if (str.Equals("bwo") || str.Equals("cni") || str.Equals("oul"))
                    {
                        P2pLib.GetInstance().ServerStatusChange(str);
                        Close();
                        return;
                    }
                }

                if (bytesRead > 0)
                {
                    lastActivity = DateTime.Now;
                    int bytesToSend = -1;
                    lock (_decryptionLock)
                    {
                        try
                        {
                            _encryptor.Decrypt(_remoteRecvBuffer, bytesRead, _remoteSendBuffer, out bytesToSend);
                        }
                        catch (CryptoErrorException)
                        {
                            Logging.Error("decryption error");
                            Close();
                            return;
                        }
                    }
                    if (bytesToSend == 0)
                    {
                        // need more to decrypt
                        Logging.Debug("Need more to decrypt");
                        session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None,
                                                    PipeRemoteReceiveCallback, session);
                        return;
                    }

                    TCPRelay.connect_times_ = 0;
                    Logging.Debug($"start sending {bytesToSend}");
                    _connection.BeginSend(_remoteSendBuffer, 0, bytesToSend, SocketFlags.None,
                                          PipeConnectionSendCallback, new object[] { session, bytesToSend });
                    IStrategy strategy = _controller.GetCurrentStrategy();
                    strategy?.UpdateLastRead(_server);
                }
                else
                {
                    _connection.Shutdown(SocketShutdown.Send);
                    _connectionShutdown = true;
                    CheckClose();
                }
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }
Пример #22
0
 private void button5_Click(object sender, EventArgs e)
 {
     // buy
     System.Diagnostics.Process.Start(P2pLib.GetInstance().buy_tenon_ip_ + "/chongzhi/" + P2pLib.GetInstance().account_id_);
 }
Пример #23
0
        public static void RandomNode()
        {
            lock (locker)
            {
                if (!loaded)
                {
                    return;
                }
                try
                {
                    string route_ip   = "";
                    ushort route_port = 0;
                    string def_route  = P2pLib.GetInstance().local_country_;
                    if (P2pLib.GetInstance().default_routing_map_.ContainsKey(P2pLib.GetInstance().local_country_))
                    {
                        def_route = P2pLib.GetInstance().default_routing_map_[P2pLib.GetInstance().local_country_];
                    }

                    int res = P2pLib.GetInstance().GetOneRouteNode(def_route, ref route_ip, ref route_port);
                    if (res != 0)
                    {
                        res = P2pLib.GetInstance().GetOneRouteNode(P2pLib.GetInstance().choose_country_, ref route_ip, ref route_port);
                        if (res != 0)
                        {
                            foreach (var country in P2pLib.GetInstance().def_vpn_country)
                            {
                                res = P2pLib.GetInstance().GetOneRouteNode(country, ref route_ip, ref route_port);
                                if (res == 0)
                                {
                                    break;
                                }
                            }
                        }

                        if (res != 0)
                        {
                            MessageBox.Show("waiting to get route nodes from p2p network. try again...");
                            return;
                        }
                    }

                    string vpn_ip     = "";
                    ushort vpn_port   = 0;
                    string svr_passwd = "";
                    res = P2pLib.GetInstance().GetOneVpnNode(P2pLib.GetInstance().choose_country_, ref vpn_ip, ref vpn_port, ref svr_passwd);
                    if (res != 0)
                    {
                        if (res != 0)
                        {
                            foreach (var country in P2pLib.GetInstance().now_countries_)
                            {
                                res = P2pLib.GetInstance().GetOneVpnNode(country, ref vpn_ip, ref vpn_port, ref svr_passwd);
                                if (res == 0)
                                {
                                    break;
                                }
                            }
                        }

                        if (res != 0)
                        {
                            MessageBox.Show("waiting to get vpn nodes from p2p network. try again...");
                            return;
                        }
                    }

                    string ip   = vpn_ip;
                    ushort port = vpn_port;
                    if (P2pLib.GetInstance().use_smart_route_)
                    {
                        ip   = route_ip;
                        port = route_port;
                    }

                    Server server = new Server()
                    {
                        server      = ip,
                        server_port = port,
                        password    = svr_passwd,
                        method      = P2pLib.GetInstance().enc_method_,
                        plugin      = "",
                        plugin_opts = "",
                        plugin_args = "",
                        remarks     = "",
                        timeout     = 10,
                    };

                    config_loaded.configs.Clear();
                    config_loaded.configs.Add(server);
                    config_loaded.proxy.CheckConfig();
                    loaded = true;

                    P2pLib.GetInstance().ChooseOneVpnNode();
                }
                catch (Exception e)
                {
                    if (!(e is FileNotFoundException))
                    {
                        Logging.LogUsefulException(e);
                    }
                }
            }
        }
Пример #24
0
        public void ResetBalance(object obj)
        {
            autoShowUpgrade();
            checkServerInfo(false);
            if (!P2pLib.GetInstance().server_status.Equals("ok"))
            {
                if (P2pLib.GetInstance().server_status.Equals("cni"))
                {
                    this.label8.Text = I18N.GetString("Agent service is not supported in your country or region.");
                }

                if (P2pLib.GetInstance().server_status.Equals("cnn"))
                {
                    this.label8.Text = I18N.GetString("Connect p2p vpn server failed.");
                }

                if (P2pLib.GetInstance().server_status.Equals("oul"))
                {
                    this.label8.Text = I18N.GetString("Your account is logged in elsewhere.");
                }
                SynchronizationContext syncContext = SynchronizationContext.Current;
                if (P2pLib.GetInstance().connectSuccess)
                {
                    if (!P2pLib.GetInstance().disConnectStarted)
                    {
                        P2pLib.GetInstance().disConnectStarted = true;

                        Thread tmp_thread = new Thread(() =>
                        {
                            controller.Stop();
                            controller.ToggleEnable(false);
                            P2pLib.GetInstance().connectSuccess = false;
                            P2pLib.GetInstance().connectStarted = false;
                            syncContext.Post(ConnectButton.ThreadRefresh, null);
                            P2pLib.GetInstance().disConnectStarted = false;
                        });
                        tmp_thread.IsBackground = true;
                        tmp_thread.Start();
                    }
                }
            }

            long balance = P2pLib.GetInstance().Balance();

            if (balance >= 0)
            {
                P2pLib.GetInstance().now_balance = balance;
                this.label10.Text = balance + " Tenon";
            }

            if (P2pLib.GetInstance().now_balance < 0)
            {
                P2pLib.createAccount();
            }

            if (check_vip_times < 10)
            {
                long tm = P2pLib.GetInstance().CheckVIP();
                if (P2pLib.GetInstance().payfor_timestamp == 0 || tm != long.MaxValue)
                {
                    if (tm != long.MaxValue && tm != 0)
                    {
                        check_vip_times = 11;
                    }
                    P2pLib.GetInstance().payfor_timestamp = tm;
                }
                ++check_vip_times;
            }
            else
            {
                P2pLib.GetInstance().PayforVpn();
            }

//             if (P2pLib.GetInstance().vip_left_days == -1 &&
//                     P2pLib.GetInstance().now_balance != -1)
//             {
//                 this.label9.Text = "";
//                 pictureBox2.Visible = false;
//                 button5.Visible = true;
//             }

            if (P2pLib.GetInstance().vip_left_days >= 0)
            {
//                 pictureBox2.Visible = true;
//                 button5.Visible = false;
                this.label9.Text = I18N.GetString("Due in ") + P2pLib.GetInstance().vip_left_days + I18N.GetString("days");
            }
        }