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.

ProtocolHandler.cs 3.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using Microsoft.Win32;
  2. using NLog;
  3. using Shadowsocks.Util;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Shadowsocks.Controller
  10. {
  11. static class ProtocolHandler
  12. {
  13. const string ssURLRegKey = @"SOFTWARE\Classes\ss";
  14. private static Logger logger = LogManager.GetCurrentClassLogger();
  15. public static bool Set(bool enabled)
  16. {
  17. RegistryKey ssURLAssociation = null;
  18. try
  19. {
  20. ssURLAssociation = Registry.CurrentUser.CreateSubKey(ssURLRegKey, RegistryKeyPermissionCheck.ReadWriteSubTree);
  21. if (ssURLAssociation == null)
  22. {
  23. logger.Error(@"Failed to create HKCU\SOFTWARE\Classes\ss to register ss:// association.");
  24. return false;
  25. }
  26. if (enabled)
  27. {
  28. ssURLAssociation.SetValue("", "URL:Shadowsocks");
  29. ssURLAssociation.SetValue("URL Protocol", "");
  30. var shellOpen = ssURLAssociation.CreateSubKey("shell").CreateSubKey("open").CreateSubKey("command");
  31. shellOpen.SetValue("", $"{Program.ExecutablePath} --open-url %1");
  32. logger.Info(@"Successfully added ss:// association.");
  33. }
  34. else
  35. {
  36. Registry.CurrentUser.DeleteSubKeyTree(ssURLRegKey);
  37. logger.Info(@"Successfully removed ss:// association.");
  38. }
  39. return true;
  40. }
  41. catch (Exception e)
  42. {
  43. logger.LogUsefulException(e);
  44. return false;
  45. }
  46. finally
  47. {
  48. if (ssURLAssociation != null)
  49. {
  50. try
  51. {
  52. ssURLAssociation.Close();
  53. ssURLAssociation.Dispose();
  54. }
  55. catch (Exception e)
  56. { logger.LogUsefulException(e); }
  57. }
  58. }
  59. }
  60. public static bool Check()
  61. {
  62. RegistryKey ssURLAssociation = null;
  63. try
  64. {
  65. ssURLAssociation = Registry.CurrentUser.OpenSubKey(ssURLRegKey, true);
  66. if (ssURLAssociation == null)
  67. {
  68. //logger.Info(@"ss:// links not associated.");
  69. return false;
  70. }
  71. var shellOpen = ssURLAssociation.OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command");
  72. return (string)shellOpen.GetValue("") == $"{Program.ExecutablePath} --open-url %1";
  73. }
  74. catch (Exception e)
  75. {
  76. logger.LogUsefulException(e);
  77. return false;
  78. }
  79. finally
  80. {
  81. if (ssURLAssociation != null)
  82. {
  83. try
  84. {
  85. ssURLAssociation.Close();
  86. ssURLAssociation.Dispose();
  87. }
  88. catch (Exception e)
  89. { logger.LogUsefulException(e); }
  90. }
  91. }
  92. }
  93. }
  94. }