예제 #1
0
        private static void EchoServer(string[] args)
        {
            Console.WriteLine(@"EchoServer start");
            // {pipeName} {maxNumberOfServerInstances} {initialNumberOfServerInstances}
            var name = args.Length > 0 ? args[0] : "EchoServer";
            var max  = args.Length > 1 ? int.Parse(args[1]) : 1;
            var num  = args.Length > 2 ? int.Parse(args[2]) : 1;

            Console.Title = $"EchoServer [{name}]";

            var server = new NamedPipeServer(name, max, num,
                                             (s, e) => {
                switch (e.Request)
                {
                case "Ping": e.Response = "Pong"; break;

                case "Exit": e.Response = "OK"; ((NamedPipeServerInstance)s).Dispose(); break;

                default: e.Response = "ERROR unknown command"; break;
                }
            });

            _consoleCtrlHandler += sig => {
                if (sig == CtrlType.CTRL_CLOSE_EVENT)
                {
                    server.Dispose();
                }
                return(false);
            };
            SetConsoleCtrlHandler(_consoleCtrlHandler, true);

            server.Run();
            Console.WriteLine(@"EchoServer exit");
        }
예제 #2
0
        private static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Application.StartupPath);
            // todo: initialize the NLog configuartion
            Model.NLogConfig.TouchAndApplyNLogConfig();

            // .NET Framework 4.7.2 on Win7 compatibility
            ServicePointManager.SecurityProtocol |=
                SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | 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())
            {
                if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.7.2"),
                                                       "Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))
                {
                    Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net472");
                }
                return;
            }
            string pipename = $"Shadowsocks\\{Application.StartupPath.GetHashCode()}";

            string addedUrl = null;

            using (NamedPipeClientStream pipe = new NamedPipeClientStream(pipename))
            {
                bool pipeExist = false;
                try
                {
                    pipe.Connect(10);
                    pipeExist = true;
                }
                catch (TimeoutException)
                {
                    pipeExist = false;
                }

                // TODO: switch to better argv parser when it's getting complicate
                List <string> alist = Args.ToList();
                // check --open-url param
                int urlidx = alist.IndexOf("--open-url") + 1;
                if (urlidx > 0)
                {
                    if (Args.Length <= urlidx)
                    {
                        return;
                    }

                    // --open-url exist, and no other instance, add it later
                    if (!pipeExist)
                    {
                        addedUrl = Args[urlidx];
                    }
                    // has other instance, send url via pipe then exit
                    else
                    {
                        byte[] b        = Encoding.UTF8.GetBytes(Args[urlidx]);
                        byte[] opAddUrl = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(1));
                        byte[] blen     = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(b.Length));
                        pipe.Write(opAddUrl, 0, 4); // opcode addurl
                        pipe.Write(blen, 0, 4);
                        pipe.Write(b, 0, b.Length);
                        pipe.Close();
                        return;
                    }
                }
                // has another instance, and no need to communicate with it return
                else if (pipeExist)
                {
                    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;
                }
            }

            Utils.ReleaseMemory(true);

            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);

            Directory.SetCurrentDirectory(Application.StartupPath);

#if DEBUG
            // truncate privoxy log file while debugging
            string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
            if (File.Exists(privoxyLogFilename))
            {
                using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
            }
#endif
            MainController = new ShadowsocksController();
            MenuController = new MenuViewController(MainController);

            HotKeys.Init(MainController);
            MainController.Start();

            NamedPipeServer namedPipeServer = new NamedPipeServer();
            Task.Run(() => namedPipeServer.Run(pipename));
            namedPipeServer.AddUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);
            if (!addedUrl.IsNullOrEmpty())
            {
                MainController.AskAddServerBySSURL(addedUrl);
            }
            Application.Run();
        }