You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Configuration.cs 11 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using Newtonsoft.Json;
  7. using NLog;
  8. using Shadowsocks.Controller;
  9. namespace Shadowsocks.Model
  10. {
  11. [Serializable]
  12. public class Configuration
  13. {
  14. [JsonIgnore]
  15. private static readonly Logger logger = LogManager.GetCurrentClassLogger();
  16. public string version;
  17. public List<Server> configs;
  18. public List<string> onlineConfigSource;
  19. // when strategy is set, index is ignored
  20. public string strategy;
  21. public int index;
  22. public bool global;
  23. public bool enabled;
  24. public bool shareOverLan;
  25. public bool isDefault;
  26. public int localPort;
  27. public bool portableMode;
  28. public bool showPluginOutput;
  29. public string pacUrl;
  30. public bool useOnlinePac;
  31. public bool secureLocalPac;
  32. public bool availabilityStatistics;
  33. public bool autoCheckUpdate;
  34. public bool checkPreRelease;
  35. public bool isVerboseLogging;
  36. // hidden options
  37. public bool isIPv6Enabled; // for experimental ipv6 support
  38. public bool generateLegacyUrl = false; // for pre-sip002 url compatibility
  39. public string geositeUrl; // for custom geosite source (and rule group)
  40. public string geositeGroup;
  41. public bool geositeBlacklistMode;
  42. public string userAgent;
  43. //public NLogConfig.LogLevel logLevel;
  44. public LogViewerConfig logViewer;
  45. public ProxyConfig proxy;
  46. public HotkeyConfig hotkey;
  47. [JsonIgnore]
  48. public bool updated;
  49. public Configuration()
  50. {
  51. version = UpdateChecker.Version;
  52. strategy = "";
  53. index = 0;
  54. global = false;
  55. enabled = false;
  56. shareOverLan = false;
  57. isDefault = true;
  58. localPort = 1080;
  59. portableMode = true;
  60. showPluginOutput = false;
  61. pacUrl = "";
  62. useOnlinePac = false;
  63. secureLocalPac = true;
  64. availabilityStatistics = false;
  65. autoCheckUpdate = false;
  66. checkPreRelease = false;
  67. isVerboseLogging = false;
  68. // hidden options
  69. isIPv6Enabled = false;
  70. generateLegacyUrl = false;
  71. geositeUrl = "";
  72. geositeGroup = "geolocation-!cn";
  73. geositeBlacklistMode = true;
  74. userAgent = "ShadowsocksWindows/$version";
  75. logViewer = new LogViewerConfig();
  76. proxy = new ProxyConfig();
  77. hotkey = new HotkeyConfig();
  78. updated = false;
  79. configs = new List<Server>();
  80. onlineConfigSource = new List<string>();
  81. }
  82. [JsonIgnore]
  83. public string userAgentString; // $version substituted with numeral version in it
  84. [JsonIgnore]
  85. NLogConfig nLogConfig;
  86. private static readonly string CONFIG_FILE = "gui-config.json";
  87. #if DEBUG
  88. private static readonly NLogConfig.LogLevel verboseLogLevel = NLogConfig.LogLevel.Trace;
  89. #else
  90. private static readonly NLogConfig.LogLevel verboseLogLevel = NLogConfig.LogLevel.Debug;
  91. #endif
  92. [JsonIgnore]
  93. public string localHost => GetLocalHost();
  94. private string GetLocalHost()
  95. {
  96. return isIPv6Enabled ? "[::1]" : "127.0.0.1";
  97. }
  98. public Server GetCurrentServer()
  99. {
  100. if (index >= 0 && index < configs.Count)
  101. return configs[index];
  102. else
  103. return GetDefaultServer();
  104. }
  105. public WebProxy WebProxy => enabled
  106. ? new WebProxy(
  107. isIPv6Enabled
  108. ? $"[{IPAddress.IPv6Loopback}]"
  109. : IPAddress.Loopback.ToString(),
  110. localPort)
  111. : null;
  112. public static void CheckServer(Server server)
  113. {
  114. CheckServer(server.server);
  115. CheckPort(server.server_port);
  116. CheckPassword(server.password);
  117. CheckTimeout(server.timeout, Server.MaxServerTimeoutSec);
  118. }
  119. public static bool ChecksServer(Server server)
  120. {
  121. try
  122. {
  123. CheckServer(server);
  124. return true;
  125. }
  126. catch (Exception)
  127. {
  128. return false;
  129. }
  130. }
  131. public static Configuration Load()
  132. {
  133. Configuration config;
  134. try
  135. {
  136. string configContent = File.ReadAllText(CONFIG_FILE);
  137. config = JsonConvert.DeserializeObject<Configuration>(configContent);
  138. config.isDefault = false;
  139. config.version = UpdateChecker.Version;
  140. if (UpdateChecker.Asset.CompareVersion(UpdateChecker.Version, config.version ?? "0") > 0)
  141. {
  142. config.updated = true;
  143. }
  144. if (config.configs.Count == 0)
  145. config.configs.Add(GetDefaultServer());
  146. if (config.index == -1 && string.IsNullOrEmpty(config.strategy))
  147. config.index = 0;
  148. if (!System.Net.Sockets.Socket.OSSupportsIPv6)
  149. {
  150. config.isIPv6Enabled = false; // disable IPv6 if os not support
  151. }
  152. //TODO if remote host(server) do not support IPv6 (or DNS resolve AAAA TYPE record) disable IPv6?
  153. config.proxy.CheckConfig();
  154. }
  155. catch (Exception e)
  156. {
  157. if (!(e is FileNotFoundException))
  158. logger.LogUsefulException(e);
  159. config = new Configuration();
  160. config.configs.Add(GetDefaultServer());
  161. }
  162. try
  163. {
  164. config.nLogConfig = NLogConfig.LoadXML();
  165. switch (config.nLogConfig.GetLogLevel())
  166. {
  167. case NLogConfig.LogLevel.Fatal:
  168. case NLogConfig.LogLevel.Error:
  169. case NLogConfig.LogLevel.Warn:
  170. case NLogConfig.LogLevel.Info:
  171. config.isVerboseLogging = false;
  172. break;
  173. case NLogConfig.LogLevel.Debug:
  174. case NLogConfig.LogLevel.Trace:
  175. config.isVerboseLogging = true;
  176. break;
  177. }
  178. }
  179. catch (Exception e)
  180. {
  181. // todo: route the error to UI since there is no log file in this scenario
  182. logger.Error(e, "Cannot get the log level from NLog config file. Please check if the nlog config file exists with corresponding XML nodes.");
  183. }
  184. config.userAgentString = config.userAgent.Replace("$version", config.version);
  185. return config;
  186. }
  187. public static void Save(Configuration config)
  188. {
  189. config.configs = SortByOnlineConfig(config.configs);
  190. if (config.index >= config.configs.Count)
  191. config.index = config.configs.Count - 1;
  192. if (config.index < -1)
  193. config.index = -1;
  194. if (config.index == -1 && string.IsNullOrEmpty(config.strategy))
  195. config.index = 0;
  196. config.isDefault = false;
  197. try
  198. {
  199. using (StreamWriter sw = new StreamWriter(File.Open(CONFIG_FILE, FileMode.Create)))
  200. {
  201. string jsonString = JsonConvert.SerializeObject(config, Formatting.Indented);
  202. sw.Write(jsonString);
  203. sw.Flush();
  204. }
  205. try
  206. {
  207. // apply changes to NLog.config
  208. config.nLogConfig.SetLogLevel(config.isVerboseLogging ? verboseLogLevel : NLogConfig.LogLevel.Info);
  209. NLogConfig.SaveXML(config.nLogConfig);
  210. }
  211. catch (Exception e)
  212. {
  213. logger.Error(e, "Cannot set the log level to NLog config file. Please check if the nlog config file exists with corresponding XML nodes.");
  214. }
  215. }
  216. catch (IOException e)
  217. {
  218. logger.LogUsefulException(e);
  219. }
  220. }
  221. public static List<Server> SortByOnlineConfig(IEnumerable<Server> servers)
  222. {
  223. var groups = servers.GroupBy(s => s.group);
  224. List<Server> ret = new List<Server>();
  225. ret.AddRange(groups.Where(g => string.IsNullOrEmpty(g.Key)).SelectMany(g => g));
  226. ret.AddRange(groups.Where(g => !string.IsNullOrEmpty(g.Key)).SelectMany(g => g));
  227. return ret;
  228. }
  229. public static Server AddDefaultServerOrServer(Configuration config, Server server = null, int? index = null)
  230. {
  231. if (config?.configs != null)
  232. {
  233. server = (server ?? GetDefaultServer());
  234. config.configs.Insert(index.GetValueOrDefault(config.configs.Count), server);
  235. //if (index.HasValue)
  236. // config.configs.Insert(index.Value, server);
  237. //else
  238. // config.configs.Add(server);
  239. }
  240. return server;
  241. }
  242. public static Server GetDefaultServer()
  243. {
  244. return new Server();
  245. }
  246. public static void CheckPort(int port)
  247. {
  248. if (port <= 0 || port > 65535)
  249. throw new ArgumentException(I18N.GetString("Port out of range"));
  250. }
  251. public static void CheckLocalPort(int port)
  252. {
  253. CheckPort(port);
  254. if (port == 8123)
  255. throw new ArgumentException(I18N.GetString("Port can't be 8123"));
  256. }
  257. private static void CheckPassword(string password)
  258. {
  259. if (string.IsNullOrEmpty(password))
  260. throw new ArgumentException(I18N.GetString("Password can not be blank"));
  261. }
  262. public static void CheckServer(string server)
  263. {
  264. if (string.IsNullOrEmpty(server))
  265. throw new ArgumentException(I18N.GetString("Server IP can not be blank"));
  266. }
  267. public static void CheckTimeout(int timeout, int maxTimeout)
  268. {
  269. if (timeout <= 0 || timeout > maxTimeout)
  270. throw new ArgumentException(
  271. I18N.GetString("Timeout is invalid, it should not exceed {0}", maxTimeout));
  272. }
  273. public static void CheckProxyAuthUser(string user)
  274. {
  275. if (string.IsNullOrEmpty(user))
  276. throw new ArgumentException(I18N.GetString("Auth user can not be blank"));
  277. }
  278. public static void CheckProxyAuthPwd(string pwd)
  279. {
  280. if (string.IsNullOrEmpty(pwd))
  281. throw new ArgumentException(I18N.GetString("Auth pwd can not be blank"));
  282. }
  283. }
  284. }