ssh-handler.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // SSH Handler
  2. //
  3. // Douglas Thrift
  4. //
  5. // ssh-handler.cs
  6. /* Copyright 2013 Douglas Thrift
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. using System;
  21. using System.Collections.Generic;
  22. using System.Diagnostics;
  23. using System.IO;
  24. using System.Text;
  25. using System.Text.RegularExpressions;
  26. using System.Windows.Forms;
  27. using Microsoft.Win32;
  28. public class SshHandler
  29. {
  30. private enum Handler { Unspecified, Putty };
  31. private static Handler handler = Handler.Unspecified;
  32. private static string puttyPath = null;
  33. public static int Main(string[] args)
  34. {
  35. Application.EnableVisualStyles();
  36. try
  37. {
  38. Regex usage = new Regex(@"^(?:/|--?)(?:h|help|usage|\?)$", RegexOptions.IgnoreCase);
  39. Regex putty = new Regex(@"^(?:/|--?)putty(?:[:=](?<putty_path>.*))?$", RegexOptions.IgnoreCase);
  40. IList<string> uriParts = null;
  41. foreach (string arg in args)
  42. if (uriParts == null)
  43. {
  44. if (usage.IsMatch(arg))
  45. return Usage(0);
  46. Match match;
  47. if ((match = putty.Match(arg)).Success)
  48. {
  49. handler = Handler.Putty;
  50. Group group = match.Groups["putty_path"];
  51. if (group.Success)
  52. puttyPath = group.Value;
  53. }
  54. else
  55. uriParts = new List<string>(new string[] { arg });
  56. }
  57. else
  58. uriParts.Add(arg);
  59. if (uriParts != null)
  60. {
  61. Uri uri = new Uri(string.Join(" ", uriParts), UriKind.Absolute);
  62. switch (handler)
  63. {
  64. case Handler.Unspecified:
  65. if (FindPutty())
  66. Putty(uri);
  67. else
  68. throw new Exception("Could not find a suitable SSH application.");
  69. break;
  70. case Handler.Putty:
  71. Putty(uri);
  72. break;
  73. }
  74. }
  75. else
  76. return Usage(1);
  77. }
  78. catch (Exception exception)
  79. {
  80. MessageBox.Show(exception.Message, "SSH Handler Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  81. return 2;
  82. }
  83. return 0;
  84. }
  85. private static int Usage(int code)
  86. {
  87. MessageBox.Show("ssh-handler [/putty[:<putty-path>]] <ssh-url>\n\n" +
  88. "/putty[:<putty-path>] -- Use PuTTY to connect", "SSH Handler Usage", MessageBoxButtons.OK, MessageBoxIcon.Information);
  89. return code;
  90. }
  91. private static void UserPassword(Uri uri, out string user, out string password)
  92. {
  93. if (uri.UserInfo.Length != 0)
  94. {
  95. string[] userInfo = uri.UserInfo.Split(new char[] { ':' }, 2);
  96. user = userInfo[0];
  97. password = userInfo.Length == 2 ? userInfo[1] : null;
  98. }
  99. else
  100. {
  101. user = null;
  102. password = null;
  103. }
  104. }
  105. private static bool FindPutty()
  106. {
  107. if (puttyPath != null)
  108. goto found;
  109. foreach (RegistryHive hive in new RegistryHive[] { RegistryHive.CurrentUser, RegistryHive.LocalMachine })
  110. {
  111. IList<RegistryView> views = new List<RegistryView>(new RegistryView[] { RegistryView.Registry32 });
  112. if (Environment.Is64BitOperatingSystem)
  113. views.Insert(0, RegistryView.Registry64);
  114. foreach (RegistryView view in views)
  115. using (RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view), key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\PuTTY_is1"))
  116. if (key != null)
  117. {
  118. string path = (string)key.GetValue("InstallLocation");
  119. if (path == null)
  120. continue;
  121. puttyPath = Path.Combine(path, "putty.exe");
  122. if (File.Exists(puttyPath))
  123. {
  124. Debug.WriteLine("Found PuTTY in registry: {0}", puttyPath, null);
  125. goto found;
  126. }
  127. else
  128. puttyPath = null;
  129. }
  130. }
  131. foreach (string path in Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator))
  132. {
  133. puttyPath = Path.Combine(path, "putty.exe");
  134. if (File.Exists(puttyPath))
  135. {
  136. Debug.WriteLine("Found PuTTY in path: {0}", puttyPath, null);
  137. goto found;
  138. }
  139. else
  140. puttyPath = null;
  141. }
  142. return false;
  143. found:
  144. puttyPath = puttyPath.Trim();
  145. return true;
  146. }
  147. private static void Putty(Uri uri)
  148. {
  149. if (!FindPutty())
  150. throw new Exception("Could not find PuTTY executable.");
  151. string user, password;
  152. UserPassword(uri, out user, out password);
  153. StringBuilder args = new StringBuilder();
  154. if (password != null)
  155. args.AppendFormat("-pw {0} ", password);
  156. if (uri.Port != -1)
  157. args.AppendFormat("-P {0} ", uri.Port);
  158. if (user != null)
  159. args.AppendFormat("{0}@", user);
  160. args.Append(uri.Host);
  161. Debug.WriteLine("Running PuTTY command: {0} {1}", puttyPath, args);
  162. Process.Start(puttyPath, args.ToString());
  163. }
  164. }