Compare commits

...
35 Commits
Author SHA1 Message Date
clowwindy b238aaf8cc bump 2.5.3 2015-08-16 18:17:53 -07:00
clowwindy 674e120af3 fix proj 2015-08-16 18:17:22 -07:00
clowwindy fdf91705ac minor fixes 2015-08-16 18:13:08 -07:00
clowwindy 4e01a40dd8 replace polipo with privoxy 2015-08-16 18:07:05 -07:00
clowwindy 766b9aac56 revert gc 2015-08-16 15:46:57 -07:00
clowwindy 4e9113a7b5 Update README.md 2015-08-15 01:39:48 +08:00
clowwindy f5a63ef1cf Merge pull request #265 from icylogic/feature/availability_log
Add availability statistics service and a simple strategy
2015-08-11 14:50:17 +08:00
icylogic 26557bfdc3 adjust interval of statistics 2015-08-11 12:17:03 +08:00
icylogic 56ec95862c implicitly implement 2015-08-11 12:16:26 +08:00
icylogic 40cb772823 adjust description 2015-08-11 11:41:27 +08:00
icylogic 295beaf8ee prevent null reference exception log 2015-08-11 11:13:19 +08:00
icylogic b36b25af06 Avoid output when disabled 2015-08-11 10:56:12 +08:00
icylogic 0e4f0f17cd Add availability statistics service and a simple strategy
Strategy: Simply Choose By Statistics
2015-08-11 02:59:56 +08:00
clowwindy ae07f8772a Merge pull request #257 from li3shiyi/master
启用系统代理时禁用“自动检测设置”,并且无必要时不清除原有代理服务器设置。
2015-08-07 21:52:59 +08:00
li3shiyi 33e06067ac 全局模式切换到PAC模式时,清除ProxyServer 2015-08-07 18:22:23 +08:00
li3shiyi 0f748bd933 启用系统代理时禁用“自动检测设置”,并且无必要时不清除原有代理服务器设置。 2015-08-07 15:12:36 +08:00
clowwindy 1fec3a125c Merge pull request #256 from JeffreyZhang105/master
Added list of servers in QRCode generate window to select.
2015-08-07 03:11:31 +08:00
Jeffrey Zhang 5ed40c7565 Added list of servers in QRCode generate window to select.
To add multiple servers in android phone, now it is no need to chose server one by one and generate QRCode for each. Just need to select the server listed in right.
2015-08-07 00:53:07 +08:00
clowwindy fbbc9a70bd Update README.md 2015-08-04 02:20:43 +08:00
clowwindy 45e0968d29 fix #238 2015-08-04 02:17:37 -07:00
clowwindy e634b7eca1 remove unused var 2015-08-04 02:14:30 -07:00
clowwindy 7425e09ebc fix log not scrolled to bottom when first shown 2015-08-04 02:08:48 -07:00
clowwindy e1a90da2a4 will not distinguish .Net 2.0 and 4.0 2015-08-04 01:59:17 -07:00
clowwindy 6a5432c861 bump 2.5.2 2015-08-04 01:47:21 -07:00
clowwindy 5acfadcdb6 add log viewer 2015-08-04 01:39:07 -07:00
clowwindy 9901c2a574 upgrade to VS2015 and .Net 4.0 2015-08-02 23:30:38 -07:00
clowwindy e038beee3e Update README.md 2015-08-02 22:38:19 +08:00
clowwindy c66ede2f59 fix a warning 2015-07-26 12:38:08 +08:00
clowwindy c54735e0e4 small fix 2015-07-26 12:37:42 +08:00
clowwindy 60dc9e7d71 bump 2.5.1 2015-07-26 12:32:35 +08:00
clowwindy 02f75f899f update CHANGES 2015-07-26 12:32:17 +08:00
clowwindy eda92b80e1 refine logs 2015-07-26 12:27:34 +08:00
clowwindy ccec6be210 prevent jittering and fix server settings update in HA 2015-07-26 12:08:28 +08:00
clowwindy 01c059c4e3 fix server index problem 2015-07-26 11:37:09 +08:00
clowwindy a0e79f37bc fix #235 2015-07-26 10:44:44 +08:00
30 changed files with 1252 additions and 114 deletions
+10 -1
View File
@@ -1,4 +1,13 @@
2.5 2015-07-11
2.5.2 2015-08-04
- Add log viewer
2.5.1 2015-07-26
- Prevent HA from switching servers too frequently
- Fix server settings can not be updated when using HA
- Fix server port can't be 8123
- Other minor fixes
2.5 2015-07-25
- Support load balance
- Support high availability
+336 -19
View File
@@ -20,30 +20,348 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
3rd party projects
==================
polipo
Privoxy
------------------
https://github.com/jech/polipo
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (c) 2003-2008 by Juliusz Chroboczek
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
PolarSSL
@@ -98,7 +416,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
libsodium
---------
+5 -3
View File
@@ -16,9 +16,7 @@ Shadowsocks for Windows
Download a [latest release].
For >= Windows 8 or with .Net 4.0, download Shadowsocks-win-dotnet4.0-x.x.x.zip.
For <= Windows 7 or with .Net 2.0, download Shadowsocks-win-x.x.x.zip.
Notice: .Net 2.0 doesn't work well on Windows 10. We no longer support .Net 2.0. Both Shadowsocks-win-xxx.zip and Shadowsocks-win-dotnet4.0-xxx.zip are exactly the same file now. If you use Windows XP or 7, please install .Net 4.0 or higher.
#### Basic
@@ -48,6 +46,10 @@ with any editor, Shadowsocks will notify browsers about the change automatically
For UDP, you need to use SocksCap or ProxyCap to force programs you want
to proxy to tunnel over Shadowsocks
#### Develop
Visual Studio 2015 is required.
#### License
GPLv3
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
using Shadowsocks.Model;
using System.Reflection;
namespace Shadowsocks.Controller
{
class AvailabilityStatistics
{
private static readonly string StatisticsFilesName = "shadowsocks.availability.csv";
private static readonly string Delimiter = ",";
private static readonly int Timeout = 500;
private static readonly int Repeat = 4; //repeat times every evaluation
private static readonly int Interval = 10 * 60 * 1000; //evaluate proxies every 15 minutes
private Timer timer = null;
private State state = null;
private List<Server> servers;
public static string AvailabilityStatisticsFile;
//static constructor to initialize every public static fields before refereced
static AvailabilityStatistics()
{
string temppath = Path.GetTempPath();
AvailabilityStatisticsFile = Path.Combine(temppath, StatisticsFilesName);
}
public bool Set(bool enabled)
{
try
{
if (enabled)
{
if (timer?.Change(0, Interval) == null)
{
state = new State();
timer = new Timer(Evaluate, state, 0, Interval);
}
}
else
{
timer?.Dispose();
}
return true;
}
catch (Exception e)
{
Logging.LogUsefulException(e);
return false;
}
}
private void Evaluate(object obj)
{
Ping ping = new Ping();
State state = (State) obj;
foreach (var server in servers)
{
Logging.Debug("eveluating " + server.FriendlyName());
foreach (var _ in Enumerable.Range(0, Repeat))
{
//TODO: do simple analyze of data to provide friendly message, like package loss.
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
//ICMP echo. we can also set options and special bytes
//seems no need to use SendPingAsync
PingReply reply = ping.Send(server.server, Timeout);
state.data = new List<KeyValuePair<string, string>>();
state.data.Add(new KeyValuePair<string, string>("Timestamp", timestamp));
state.data.Add(new KeyValuePair<string, string>("Server", server.FriendlyName()));
state.data.Add(new KeyValuePair<string, string>("Status", reply.Status.ToString()));
state.data.Add(new KeyValuePair<string, string>("RoundtripTime", reply.RoundtripTime.ToString()));
//state.data.Add(new KeyValuePair<string, string>("data", reply.Buffer.ToString())); // The data of reply
Append(state.data);
}
}
}
private static void Append(List<KeyValuePair<string, string>> data)
{
string dataLine = string.Join(Delimiter, data.Select(kv => kv.Value).ToArray());
string[] lines;
if (!File.Exists(AvailabilityStatisticsFile))
{
string headerLine = string.Join(Delimiter, data.Select(kv => kv.Key).ToArray());
lines = new string[] { headerLine, dataLine };
}
else
{
lines = new string[] { dataLine };
}
File.AppendAllLines(AvailabilityStatisticsFile, lines);
}
internal void UpdateConfiguration(Configuration _config)
{
Set(_config.availabilityStatistics);
servers = _config.configs;
}
private class State
{
public List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();
}
}
}
@@ -8,6 +8,7 @@ using System.IO.Compression;
using System.Text;
using System.Net.NetworkInformation;
using System.Net;
using System.Runtime.InteropServices;
namespace Shadowsocks.Controller
{
@@ -22,7 +23,8 @@ namespace Shadowsocks.Controller
temppath = Path.GetTempPath();
try
{
FileManager.UncompressFile(temppath + "/ss_polipo.exe", Resources.polipo_exe);
FileManager.UncompressFile(temppath + "/ss_privoxy.exe", Resources.privoxy_exe);
FileManager.UncompressFile(temppath + "/mgwz.dll", Resources.mgwz_dll);
}
catch (IOException e)
{
@@ -43,7 +45,7 @@ namespace Shadowsocks.Controller
Server server = configuration.GetCurrentServer();
if (_process == null)
{
Process[] existingPolipo = Process.GetProcessesByName("ss_polipo");
Process[] existingPolipo = Process.GetProcessesByName("ss_privoxy");
foreach (Process p in existingPolipo)
{
try
@@ -56,17 +58,17 @@ namespace Shadowsocks.Controller
Console.WriteLine(e.ToString());
}
}
string polipoConfig = Resources.polipo_config;
string polipoConfig = Resources.privoxy_conf;
_runningPort = this.GetFreePort();
polipoConfig = polipoConfig.Replace("__SOCKS_PORT__", configuration.localPort.ToString());
polipoConfig = polipoConfig.Replace("__POLIPO_BIND_PORT__", _runningPort.ToString());
polipoConfig = polipoConfig.Replace("__POLIPO_BIND_IP__", configuration.shareOverLan ? "0.0.0.0" : "127.0.0.1");
FileManager.ByteArrayToFile(temppath + "/polipo.conf", System.Text.Encoding.UTF8.GetBytes(polipoConfig));
FileManager.ByteArrayToFile(temppath + "/privoxy.conf", System.Text.Encoding.UTF8.GetBytes(polipoConfig));
_process = new Process();
// Configure the process using the StartInfo properties.
_process.StartInfo.FileName = temppath + "/ss_polipo.exe";
_process.StartInfo.Arguments = "-c \"" + temppath + "/polipo.conf\"";
_process.StartInfo.FileName = temppath + "/ss_privoxy.exe";
_process.StartInfo.Arguments = " \"" + temppath + "/privoxy.conf\"";
_process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_process.StartInfo.UseShellExecute = true;
_process.StartInfo.CreateNoWindow = true;
@@ -74,6 +76,7 @@ namespace Shadowsocks.Controller
//_process.StartInfo.RedirectStandardError = true;
_process.Start();
}
RefreshTrayArea();
}
public void Stop()
@@ -91,6 +94,7 @@ namespace Shadowsocks.Controller
}
_process = null;
}
RefreshTrayArea();
}
private int GetFreePort()
@@ -122,5 +126,50 @@ namespace Shadowsocks.Controller
}
throw new Exception("No free port found.");
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
public void RefreshTrayArea()
{
IntPtr systemTrayContainerHandle = FindWindow("Shell_TrayWnd", null);
IntPtr systemTrayHandle = FindWindowEx(systemTrayContainerHandle, IntPtr.Zero, "TrayNotifyWnd", null);
IntPtr sysPagerHandle = FindWindowEx(systemTrayHandle, IntPtr.Zero, "SysPager", null);
IntPtr notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", "Notification Area");
if (notificationAreaHandle == IntPtr.Zero)
{
notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", "User Promoted Notification Area");
IntPtr notifyIconOverflowWindowHandle = FindWindow("NotifyIconOverflowWindow", null);
IntPtr overflowNotificationAreaHandle = FindWindowEx(notifyIconOverflowWindowHandle, IntPtr.Zero, "ToolbarWindow32", "Overflow Notification Area");
RefreshTrayArea(overflowNotificationAreaHandle);
}
RefreshTrayArea(notificationAreaHandle);
}
private static void RefreshTrayArea(IntPtr windowHandle)
{
const uint wmMousemove = 0x0200;
RECT rect;
GetClientRect(windowHandle, out rect);
for (var x = 0; x < rect.right; x += 5)
for (var y = 0; y < rect.bottom; y += 5)
SendMessage(windowHandle, wmMousemove, 0, (y << 16) + x);
}
}
}
@@ -83,6 +83,10 @@ namespace Shadowsocks.Controller
public void CreateRemote()
{
Server server = controller.GetAServer(IStrategyCallerType.TCP, (IPEndPoint)connection.RemoteEndPoint);
if (server == null || server.server == "")
{
throw new ArgumentException("No server configured");
}
this.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
this.server = server;
}
@@ -310,6 +314,7 @@ namespace Shadowsocks.Controller
StartConnect();
}
catch (Exception e)
{
Logging.LogUsefulException(e);
@@ -429,7 +434,7 @@ namespace Shadowsocks.Controller
StartPipe();
}
catch (ArgumentException e)
catch (ArgumentException)
{
}
catch (Exception e)
@@ -18,7 +18,7 @@ namespace Shadowsocks.Controller
public string LatestVersionURL;
public event EventHandler NewVersionFound;
public const string Version = "2.5";
public const string Version = "2.5.3";
public void CheckUpdate(Configuration config)
{
@@ -80,30 +80,6 @@ namespace Shadowsocks.Controller
{
return false;
}
// check dotnet 4.0
AssemblyName[] references = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
Version dotNetVersion = Environment.Version;
foreach (AssemblyName reference in references)
{
if (reference.Name == "mscorlib")
{
dotNetVersion = reference.Version;
}
}
if (dotNetVersion.Major >= 4)
{
if (url.IndexOf("dotnet4.0") < 0)
{
return false;
}
}
else
{
if (url.IndexOf("dotnet4.0") >= 0)
{
return false;
}
}
string version = ParseVersionFromURL(url);
if (version == null)
{
@@ -154,7 +130,7 @@ namespace Shadowsocks.Controller
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Logging.Debug(ex.ToString());
return;
}
}
@@ -25,6 +25,7 @@ namespace Shadowsocks.Controller
private StrategyManager _strategyManager;
private PolipoRunner polipoRunner;
private GFWListUpdater gfwListUpdater;
private AvailabilityStatistics _availabilityStatics;
private bool stopped = false;
private bool _systemProxyIsDirty = false;
@@ -53,6 +54,7 @@ namespace Shadowsocks.Controller
{
_config = Configuration.Load();
_strategyManager = new StrategyManager(this);
StartReleasingMemory();
}
public void Start()
@@ -109,6 +111,10 @@ namespace Shadowsocks.Controller
{
return strategy.GetAServer(type, localIPEndPoint);
}
if (_config.index < 0)
{
_config.index = 0;
}
return GetCurrentServer();
}
@@ -224,6 +230,11 @@ namespace Shadowsocks.Controller
public string GetQRCodeForCurrentServer()
{
Server server = GetCurrentServer();
return GetQRCode(server);
}
public static string GetQRCode(Server server)
{
string parts = server.method + ":" + server.password + "@" + server.server + ":" + server.server_port;
string base64 = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
return "ss://" + base64;
@@ -237,6 +248,16 @@ namespace Shadowsocks.Controller
}
}
public void ToggleAvailabilityStatistics(bool enabled)
{
if (_availabilityStatics != null)
{
_availabilityStatics.Set(enabled);
_config.availabilityStatistics = enabled;
SaveConfig(_config);
}
}
public void SavePACUrl(string pacUrl)
{
_config.pacUrl = pacUrl;
@@ -286,6 +307,12 @@ namespace Shadowsocks.Controller
_listener.Stop();
}
if (_availabilityStatics == null)
{
_availabilityStatics = new AvailabilityStatistics();
_availabilityStatics.UpdateConfiguration(_config);
}
// don't put polipoRunner.Start() before pacServer.Stop()
// or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
// though UseShellExecute is set to true now
@@ -293,7 +320,8 @@ namespace Shadowsocks.Controller
polipoRunner.Stop();
try
{
foreach (var strategy in GetStrategies())
var strategy = GetCurrentStrategy();
if (strategy != null)
{
strategy.ReloadServers();
}
@@ -7,7 +7,7 @@ namespace Shadowsocks.Controller.Strategy
{
class HighAvailabilityStrategy : IStrategy
{
protected Server _currentServer;
protected ServerStatus _currentServer;
protected Dictionary<Server, ServerStatus> _serverStatus;
ShadowsocksController _controller;
Random _random;
@@ -67,6 +67,11 @@ namespace Shadowsocks.Controller.Strategy
status.lastTimeDetectLatency = DateTime.Now;
newServerStatus[server] = status;
}
else
{
// update settings for existing server
newServerStatus[server].server = server;
}
}
_serverStatus = newServerStatus;
@@ -79,7 +84,11 @@ namespace Shadowsocks.Controller.Strategy
{
ChooseNewServer();
}
return _currentServer;
if (_currentServer == null)
{
return null;
}
return _currentServer.server;
}
/**
@@ -90,7 +99,7 @@ namespace Shadowsocks.Controller.Strategy
*/
public void ChooseNewServer()
{
Server oldServer = _currentServer;
ServerStatus oldServer = _currentServer;
List<ServerStatus> servers = new List<ServerStatus>(_serverStatus.Values);
DateTime now = DateTime.Now;
foreach (var status in servers)
@@ -120,12 +129,11 @@ namespace Shadowsocks.Controller.Strategy
}
if (max != null)
{
_currentServer = max.server;
if (_currentServer != oldServer)
if (_currentServer == null || max.score - _currentServer.score > 200)
{
Console.WriteLine("HA switching to server: {0}", _currentServer.FriendlyName());
_currentServer = max;
Console.WriteLine("HA switching to server: {0}", _currentServer.server.FriendlyName());
}
Logging.Debug(String.Format("choosing server: {0}", _currentServer.FriendlyName()));
}
}
@@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Shadowsocks.Model;
using System.IO;
using System.Net.NetworkInformation;
using System.Threading;
namespace Shadowsocks.Controller.Strategy
{
class SimplyChooseByStatisticsStrategy : IStrategy
{
private ShadowsocksController _controller;
private Server _currentServer;
private Timer timer;
private Dictionary<string, StatisticsData> statistics;
private static readonly int CachedInterval = 30 * 60 * 1000; //choose a new server every 30 minutes
public SimplyChooseByStatisticsStrategy(ShadowsocksController controller)
{
_controller = controller;
var servers = controller.GetCurrentConfiguration().configs;
int randomIndex = new Random().Next() % servers.Count();
_currentServer = servers[randomIndex]; //choose a server randomly at first
timer = new Timer(ReloadStatisticsAndChooseAServer);
}
private void ReloadStatisticsAndChooseAServer(object obj)
{
Logging.Debug("Reloading statistics and choose a new server....");
List<Server> servers = _controller.GetCurrentConfiguration().configs;
LoadStatistics();
ChooseNewServer(servers);
}
/*
return a dict:
{
'ServerFriendlyName1':StatisticsData,
'ServerFriendlyName2':...
}
*/
private void LoadStatistics()
{
try
{
var path = AvailabilityStatistics.AvailabilityStatisticsFile;
Logging.Debug(string.Format("loading statistics from{0}", path));
statistics = (from l in File.ReadAllLines(path)
.Skip(1)
let strings = l.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
let rawData = new
{
ServerName = strings[1],
IPStatus = strings[2],
RoundtripTime = int.Parse(strings[3])
}
group rawData by rawData.ServerName into server
select new
{
ServerName = server.Key,
data = new StatisticsData
{
SuccessTimes = server.Count(data => IPStatus.Success.ToString().Equals(data.IPStatus)),
TimedOutTimes = server.Count(data => IPStatus.TimedOut.ToString().Equals(data.IPStatus)),
AverageResponse = Convert.ToInt32(server.Average(data => data.RoundtripTime)),
MinResponse = server.Min(data => data.RoundtripTime),
MaxResponse = server.Max(data => data.RoundtripTime)
}
}).ToDictionary(server => server.ServerName, server => server.data);
}
catch (Exception e)
{
Logging.LogUsefulException(e);
}
}
//return the score by data
//server with highest score will be choosen
private static double GetScore(StatisticsData data)
{
return (double)data.SuccessTimes / (data.SuccessTimes + data.TimedOutTimes); //simply choose min package loss
}
private class StatisticsData
{
public int SuccessTimes;
public int TimedOutTimes;
public int AverageResponse;
public int MinResponse;
public int MaxResponse;
}
private void ChooseNewServer(List<Server> servers)
{
if (statistics == null)
{
return;
}
try
{
var bestResult = (from server in servers
let name = server.FriendlyName()
where statistics.ContainsKey(name)
select new
{
server,
score = GetScore(statistics[name])
}
).Aggregate((result1, result2) => result1.score > result2.score ? result1 : result2);
if (_controller.GetCurrentStrategy().ID == ID && _currentServer != bestResult.server) //output when enabled
{
Console.WriteLine("Switch to server: {0} by package loss:{1}", bestResult.server.FriendlyName(), 1 - bestResult.score);
}
_currentServer = bestResult.server;
}
catch (Exception e)
{
Logging.LogUsefulException(e);
}
}
public string ID
{
get { return "com.shadowsocks.strategy.scbs"; }
}
public string Name
{
get { return I18N.GetString("Choose By Total Package Loss"); }
}
public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint)
{
var oldServer = _currentServer;
if (oldServer == null)
{
ChooseNewServer(_controller.GetCurrentConfiguration().configs);
}
if (oldServer != _currentServer)
{
}
return _currentServer; //current server cached for CachedInterval
}
public void ReloadServers()
{
ChooseNewServer(_controller.GetCurrentConfiguration().configs);
timer?.Change(0, CachedInterval);
}
public void SetFailure(Server server)
{
Logging.Debug(String.Format("failure: {0}", server.FriendlyName()));
}
public void UpdateLastRead(Server server)
{
//TODO: combine this part of data with ICMP statics
}
public void UpdateLastWrite(Server server)
{
//TODO: combine this part of data with ICMP statics
}
public void UpdateLatency(Server server, TimeSpan latency)
{
//TODO: combine this part of data with ICMP statics
}
}
}
@@ -13,6 +13,7 @@ namespace Shadowsocks.Controller.Strategy
_strategies = new List<IStrategy>();
_strategies.Add(new BalancingStrategy(controller));
_strategies.Add(new HighAvailabilityStrategy(controller));
_strategies.Add(new SimplyChooseByStatisticsStrategy(controller));
// TODO: load DLL plugins
}
public IList<IStrategy> GetStrategies()
@@ -55,16 +55,23 @@ namespace Shadowsocks.Controller
else
pacUrl = "http://127.0.0.1:" + config.localPort.ToString() + "/pac?t=" + GetTimestamp(DateTime.Now);
registry.SetValue("ProxyEnable", 0);
registry.SetValue("ProxyServer", "");
var readProxyServer = registry.GetValue("ProxyServer");
if (readProxyServer != null && readProxyServer.Equals("127.0.0.1:" + config.localPort.ToString()))
registry.SetValue("ProxyServer", "");
registry.SetValue("AutoConfigURL", pacUrl);
}
}
else
{
registry.SetValue("ProxyEnable", 0);
registry.SetValue("ProxyServer", "");
if (global)
{
registry.SetValue("ProxyServer", "");
}
registry.SetValue("AutoConfigURL", "");
}
//Set AutoDetectProxy Off
IEAutoDetectProxy(false);
SystemProxy.NotifyIE();
//Must Notify IE first, or the connections do not chanage
CopyProxySettingFromLan();
@@ -106,5 +113,30 @@ namespace Shadowsocks.Controller
{
return value.ToString("yyyyMMddHHmmssffff");
}
/// <summary>
/// Checks or unchecks the IE Options Connection setting of "Automatically detect Proxy"
/// </summary>
/// <param name="set">Provide 'true' if you want to check the 'Automatically detect Proxy' check box. To uncheck, pass 'false'</param>
private static void IEAutoDetectProxy(bool set)
{
RegistryKey registry =
Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections",
true);
byte[] defConnection = (byte[])registry.GetValue("DefaultConnectionSettings");
byte[] savedLegacySetting = (byte[])registry.GetValue("SavedLegacySettings");
if (set)
{
defConnection[8] = Convert.ToByte(defConnection[8] & 8);
savedLegacySetting[8] = Convert.ToByte(savedLegacySetting[8] & 8);
}
else
{
defConnection[8] = Convert.ToByte(defConnection[8] & ~8);
savedLegacySetting[8] = Convert.ToByte(savedLegacySetting[8] & ~8);
}
registry.SetValue("DefaultConnectionSettings", defConnection);
registry.SetValue("SavedLegacySettings", savedLegacySetting);
}
}
}
+1
View File
@@ -25,6 +25,7 @@ Quit=退出
Edit Servers=编辑服务器
Load Balance=负载均衡
High Availability=高可用
Choose By Total Package Loss=累计丢包率
# Config Form
Binary file not shown.
Binary file not shown.
-10
View File
@@ -1,10 +0,0 @@
proxyAddress = "__POLIPO_BIND_IP__"
proxyPort = 8123
socksParentProxy = "127.0.0.1:__SOCKS_PORT__"
socksProxyType = socks5
diskCacheRoot = ""
localDocumentRoot = ""
allowedPorts = 1-65535
tunnelAllowedPorts = 1-65535
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
listen-address __POLIPO_BIND_IP__:8123
show-on-task-bar 0
activity-animation 0
forward-socks5 / 127.0.0.1:__SOCKS_PORT__ .
hide-console
+20
View File
@@ -22,6 +22,7 @@ namespace Shadowsocks.Model
public int localPort;
public string pacUrl;
public bool useOnlinePac;
public bool availabilityStatistics;
private static string CONFIG_FILE = "gui-config.json";
@@ -55,6 +56,13 @@ namespace Shadowsocks.Model
{
config.localPort = 1080;
}
if (config.index == -1)
{
if (config.strategy == null)
{
config.index = 0;
}
}
return config;
}
catch (Exception e)
@@ -86,6 +94,13 @@ namespace Shadowsocks.Model
{
config.index = -1;
}
if (config.index == -1)
{
if (config.strategy == null)
{
config.index = 0;
}
}
config.isDefault = false;
try
{
@@ -121,6 +136,11 @@ namespace Shadowsocks.Model
{
throw new ArgumentException(I18N.GetString("Port out of range"));
}
}
public static void CheckLocalPort(int port)
{
CheckPort(port);
if (port == 8123)
{
throw new ArgumentException(I18N.GetString("Port can't be 8123"));
+20 -15
View File
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -113,29 +113,34 @@ namespace Shadowsocks.Properties {
}
/// <summary>
/// Looks up a localized string similar to proxyAddress = &quot;__POLIPO_BIND_IP__&quot;
///proxyPort = 8123
///
///socksParentProxy = &quot;127.0.0.1:__SOCKS_PORT__&quot;
///socksProxyType = socks5
///diskCacheRoot = &quot;&quot;
///localDocumentRoot = &quot;&quot;
///
///allowedPorts = 1-65535
///tunnelAllowedPorts = 1-65535.
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static string polipo_config {
internal static byte[] mgwz_dll {
get {
return ResourceManager.GetString("polipo_config", resourceCulture);
object obj = ResourceManager.GetObject("mgwz_dll", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized string similar to listen-address __POLIPO_BIND_IP__:8123
///show-on-task-bar 0
///activity-animation 0
///forward-socks5 / 127.0.0.1:__SOCKS_PORT__ .
///hide-console.
/// </summary>
internal static string privoxy_conf {
get {
return ResourceManager.GetString("privoxy_conf", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] polipo_exe {
internal static byte[] privoxy_exe {
get {
object obj = ResourceManager.GetObject("polipo_exe", resourceCulture);
object obj = ResourceManager.GetObject("privoxy_exe", resourceCulture);
return ((byte[])(obj));
}
}
+10 -7
View File
@@ -112,12 +112,12 @@
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="abp_js" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\abp.js.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
@@ -127,11 +127,14 @@
<data name="libsscrypto_dll" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\libsscrypto.dll.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="polipo_config" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\polipo_config.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;gb2312</value>
<data name="mgwz_dll" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\mgwz.dll.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="polipo_exe" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\polipo.exe.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<data name="privoxy_conf" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\privoxy_conf.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
<data name="privoxy_exe" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\privoxy.exe.gz;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="proxy_pac_txt" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\proxy.pac.txt.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+1 -1
View File
@@ -84,7 +84,7 @@ namespace Shadowsocks.View
};
int localPort = int.Parse(ProxyPortTextBox.Text);
Configuration.CheckServer(server);
Configuration.CheckPort(localPort);
Configuration.CheckLocalPort(localPort);
_modifiedConfiguration.configs[_oldSelectedIndex] = server;
_modifiedConfiguration.localPort = localPort;
+113
View File
@@ -0,0 +1,113 @@
namespace Shadowsocks.View
{
partial class LogForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.textBox1 = new System.Windows.Forms.TextBox();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.BackColor = System.Drawing.Color.Black;
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBox1.ForeColor = System.Drawing.Color.White;
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.MaxLength = 2147483647;
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBox1.Size = new System.Drawing.Size(547, 382);
this.textBox1.TabIndex = 0;
this.textBox1.WordWrap = false;
//
// contextMenuStrip1
//
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(61, 4);
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem2,
this.menuItem4});
this.menuItem1.Text = "&File";
//
// menuItem2
//
this.menuItem2.Index = 0;
this.menuItem2.Text = "&Open Location";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// menuItem4
//
this.menuItem4.Index = 1;
this.menuItem4.Text = "E&xit";
this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
//
// LogForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(547, 382);
this.Controls.Add(this.textBox1);
this.Menu = this.mainMenu1;
this.Name = "LogForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Log Viewer";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.LogForm_FormClosing);
this.Load += new System.EventHandler(this.LogForm_Load);
this.Shown += new System.EventHandler(this.LogForm_Shown);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem4;
}
}
+113
View File
@@ -0,0 +1,113 @@
using Shadowsocks.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Shadowsocks.View
{
public partial class LogForm : Form
{
long lastOffset;
string filename;
Timer timer;
const int BACK_OFFSET = 65536;
public LogForm(string filename)
{
this.filename = filename;
InitializeComponent();
this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon());
}
private void Timer_Tick(object sender, EventArgs e)
{
UpdateContent();
}
private void InitContent()
{
using (StreamReader reader = new StreamReader(new FileStream(filename,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
if (reader.BaseStream.Length > BACK_OFFSET)
{
reader.BaseStream.Seek(-BACK_OFFSET, SeekOrigin.End);
reader.ReadLine();
}
string line = "";
while ((line = reader.ReadLine()) != null)
textBox1.AppendText(line + "\r\n");
textBox1.ScrollToCaret();
lastOffset = reader.BaseStream.Position;
}
}
private void UpdateContent()
{
using (StreamReader reader = new StreamReader(new FileStream(filename,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
reader.BaseStream.Seek(lastOffset, SeekOrigin.Begin);
string line = "";
bool changed = false;
while ((line = reader.ReadLine()) != null)
{
changed = true;
textBox1.AppendText(line + "\r\n");
}
if (changed)
{
textBox1.ScrollToCaret();
}
lastOffset = reader.BaseStream.Position;
}
}
private void LogForm_Load(object sender, EventArgs e)
{
InitContent();
timer = new Timer();
timer.Interval = 300;
timer.Tick += Timer_Tick;
timer.Start();
}
private void LogForm_FormClosing(object sender, FormClosingEventArgs e)
{
timer.Stop();
}
private void menuItem2_Click(object sender, EventArgs e)
{
string argument = @"/select, " + filename;
System.Diagnostics.Process.Start("explorer.exe", argument);
}
private void menuItem3_Click(object sender, EventArgs e)
{
}
private void menuItem4_Click(object sender, EventArgs e)
{
this.Close();
}
private void LogForm_Shown(object sender, EventArgs e)
{
textBox1.ScrollToCaret();
}
}
}
+126
View File
@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="contextMenuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="mainMenu1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>172, 17</value>
</metadata>
</root>
+10 -2
View File
@@ -29,6 +29,7 @@ namespace Shadowsocks.View
private MenuItem enableItem;
private MenuItem modeItem;
private MenuItem AutoStartupItem;
private MenuItem AvailabilityStatistics;
private MenuItem ShareOverLANItem;
private MenuItem SeperatorItem;
private MenuItem ConfigItem;
@@ -177,6 +178,7 @@ namespace Shadowsocks.View
}),
new MenuItem("-"),
this.AutoStartupItem = CreateMenuItem("Start on Boot", new EventHandler(this.AutoStartupItem_Click)),
this.AvailabilityStatistics = CreateMenuItem("Availability Statistics", new EventHandler(this.AvailabilityStatisticsItem_Click)),
this.ShareOverLANItem = CreateMenuItem("Allow Clients from LAN", new EventHandler(this.ShareOverLANItem_Click)),
new MenuItem("-"),
CreateMenuItem("Show Logs...", new EventHandler(this.ShowLogItem_Click)),
@@ -260,6 +262,7 @@ namespace Shadowsocks.View
PACModeItem.Checked = !config.global;
ShareOverLANItem.Checked = config.shareOverLan;
AutoStartupItem.Checked = AutoStartup.Check();
AvailabilityStatistics.Checked = config.availabilityStatistics;
onlinePACItem.Checked = onlinePACItem.Enabled && config.useOnlinePac;
localPACItem.Checked = !onlinePACItem.Checked;
UpdatePACItemsEnabledStatus();
@@ -349,7 +352,7 @@ namespace Shadowsocks.View
private void AboutItem_Click(object sender, EventArgs e)
{
Process.Start("https://github.com/shadowsocks/shadowsocks-csharp");
Process.Start("https://github.com/shadowsocks/shadowsocks-windows");
}
private void notifyIcon1_DoubleClick(object sender, MouseEventArgs e)
@@ -412,7 +415,7 @@ namespace Shadowsocks.View
{
string argument = Logging.LogFile;
System.Diagnostics.Process.Start("notepad.exe", argument);
new LogForm(argument).Show();
}
private void QRCodeItem_Click(object sender, EventArgs e)
@@ -524,6 +527,11 @@ namespace Shadowsocks.View
}
}
private void AvailabilityStatisticsItem_Click(object sender, EventArgs e) {
AvailabilityStatistics.Checked = !AvailabilityStatistics.Checked;
controller.ToggleAvailabilityStatistics(AvailabilityStatistics.Checked);
}
private void LocalPACItem_Click(object sender, EventArgs e)
{
if (!localPACItem.Checked)
+17 -1
View File
@@ -29,6 +29,7 @@
private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.listBox1 = new System.Windows.Forms.ListBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
@@ -42,6 +43,19 @@
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
//
// listBox1
//
this.listBox1.DisplayMember = "Value";
this.listBox1.FormattingEnabled = true;
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(224, 10);
this.listBox1.Name = "listBox1";
this.listBox1.ScrollAlwaysVisible = true;
this.listBox1.Size = new System.Drawing.Size(227, 208);
this.listBox1.TabIndex = 2;
this.listBox1.ValueMember = "Key";
this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
//
// QRCodeForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
@@ -49,7 +63,8 @@
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(338, 274);
this.ClientSize = new System.Drawing.Size(457, 228);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.pictureBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
@@ -67,5 +82,6 @@
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ListBox listBox1;
}
}
+19 -4
View File
@@ -8,8 +8,10 @@ using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Shadowsocks.Model;
namespace Shadowsocks.View
{
@@ -30,8 +32,8 @@ namespace Shadowsocks.View
string qrText = ssconfig;
QRCode code = ZXing.QrCode.Internal.Encoder.encode(qrText, ErrorCorrectionLevel.M);
ByteMatrix m = code.Matrix;
int blockSize = Math.Max(pictureBox1.Height / m.Height, 1);
Bitmap drawArea = new Bitmap((m.Width * blockSize), (m.Height * blockSize));
int blockSize = Math.Max(pictureBox1.Height/m.Height, 1);
Bitmap drawArea = new Bitmap((m.Width*blockSize), (m.Height*blockSize));
using (Graphics g = Graphics.FromImage(drawArea))
{
g.Clear(Color.White);
@@ -43,7 +45,7 @@ namespace Shadowsocks.View
{
if (m[row, col] != 0)
{
g.FillRectangle(b, blockSize * row, blockSize * col, blockSize, blockSize);
g.FillRectangle(b, blockSize*row, blockSize*col, blockSize, blockSize);
}
}
}
@@ -54,7 +56,20 @@ namespace Shadowsocks.View
private void QRCodeForm_Load(object sender, EventArgs e)
{
GenQR(code);
var servers = Configuration.Load();
var serverDatas = servers.configs.Select(
server =>
new KeyValuePair<string, string>(ShadowsocksController.GetQRCode(server), server.FriendlyName())
).ToList();
listBox1.DataSource = serverDatas;
var selectIndex = serverDatas.FindIndex(serverData => serverData.Key.StartsWith(code));
if (selectIndex >= 0) listBox1.SetSelected(selectIndex, true);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
GenQR((sender as ListBox)?.SelectedValue.ToString());
}
}
}
+2 -2
View File
@@ -112,9 +112,9 @@
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
+17 -6
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Shadowsocks</RootNamespace>
<AssemblyName>Shadowsocks</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<StartupObject>
</StartupObject>
@@ -21,8 +21,7 @@
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
@@ -124,7 +123,9 @@
<Compile Include="3rd\zxing\ResultPoint.cs" />
<Compile Include="3rd\zxing\ResultPointCallback.cs" />
<Compile Include="3rd\zxing\WriterException.cs" />
<Compile Include="Controller\Service\AvailabilityStatistics.cs" />
<Compile Include="Controller\Strategy\HighAvailabilityStrategy.cs" />
<Compile Include="Controller\Strategy\SimplyChooseByStatisticsStrategy.cs" />
<Compile Include="Controller\System\AutoStartup.cs" />
<Compile Include="Controller\FileManager.cs" />
<Compile Include="Controller\Service\GFWListUpdater.cs" />
@@ -167,6 +168,12 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Controller\ShadowsocksController.cs" />
<Compile Include="Controller\System\SystemProxy.cs" />
<Compile Include="View\LogForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="View\LogForm.Designer.cs">
<DependentUpon>LogForm.cs</DependentUpon>
</Compile>
<Compile Include="View\MenuViewController.cs" />
<Compile Include="View\QRCodeForm.cs">
<SubType>Form</SubType>
@@ -186,6 +193,9 @@
<SubType>Designer</SubType>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Include="View\LogForm.resx">
<DependentUpon>LogForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="View\QRCodeForm.resx">
<DependentUpon>QRCodeForm.cs</DependentUpon>
</EmbeddedResource>
@@ -195,7 +205,8 @@
</None>
<None Include="Data\abp.js.gz" />
<None Include="Data\libsscrypto.dll.gz" />
<None Include="Data\polipo.exe.gz" />
<None Include="Data\mgwz.dll.gz" />
<None Include="Data\privoxy.exe.gz" />
<None Include="Data\proxy.pac.txt.gz" />
</ItemGroup>
<ItemGroup>
@@ -204,9 +215,9 @@
<None Include="Resources\ss24.png" />
<None Include="Resources\ssw128.png" />
<Content Include="Data\cn.txt" />
<Content Include="Data\privoxy_conf.txt" />
<Content Include="Data\user-rule.txt" />
<Content Include="shadowsocks.ico" />
<None Include="Data\polipo_config.txt" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">