APIHandler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.IO;
  8. using System.Windows;
  9. using Newtonsoft.Json;
  10. using System.Diagnostics;
  11. namespace WinUI
  12. {
  13. public class APIHandler
  14. {
  15. private string authtoken;
  16. private string url = null;
  17. private static volatile APIHandler instance;
  18. private static object syncRoot = new Object();
  19. public delegate void NetworkListCallback(List<ZeroTierNetwork> networks);
  20. public delegate void StatusCallback(ZeroTierStatus status);
  21. public static APIHandler Instance
  22. {
  23. get
  24. {
  25. if (instance == null)
  26. {
  27. lock (syncRoot)
  28. {
  29. if (instance == null)
  30. {
  31. if (!initHandler())
  32. {
  33. return null;
  34. }
  35. }
  36. }
  37. }
  38. return instance;
  39. }
  40. }
  41. private static bool initHandler()
  42. {
  43. String localZtDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ZeroTier\\One";
  44. String globalZtDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\ZeroTier\\One";
  45. String authToken = "";
  46. Int32 port = 9993;
  47. if (!File.Exists(localZtDir + "\\authtoken.secret") || !File.Exists(localZtDir + "\\zerotier-one.port"))
  48. {
  49. // launch external process to copy file into place
  50. String curPath = System.Reflection.Assembly.GetEntryAssembly().Location;
  51. int index = curPath.LastIndexOf("\\");
  52. curPath = curPath.Substring(0, index);
  53. ProcessStartInfo startInfo = new ProcessStartInfo(curPath + "\\copyutil.exe", "\""+globalZtDir+"\"" + " " + "\""+localZtDir+"\"");
  54. startInfo.Verb = "runas";
  55. var process = Process.Start(startInfo);
  56. process.WaitForExit();
  57. }
  58. authToken = readAuthToken(localZtDir + "\\authtoken.secret");
  59. if ((authToken == null) || (authToken.Length <= 0))
  60. {
  61. MessageBox.Show("Unable to read ZeroTier One authtoken", "ZeroTier One");
  62. return false;
  63. }
  64. port = readPort(localZtDir + "\\zerotier-one.port");
  65. instance = new APIHandler(port, authToken);
  66. return true;
  67. }
  68. private static String readAuthToken(String path)
  69. {
  70. String authToken = "";
  71. if (File.Exists(path))
  72. {
  73. try
  74. {
  75. byte[] tmp = File.ReadAllBytes(path);
  76. authToken = System.Text.Encoding.UTF8.GetString(tmp).Trim();
  77. }
  78. catch
  79. {
  80. MessageBox.Show("Unable to read ZeroTier One Auth Token from:\r\n" + path, "ZeroTier One");
  81. }
  82. }
  83. return authToken;
  84. }
  85. private static Int32 readPort(String path)
  86. {
  87. Int32 port = 9993;
  88. try
  89. {
  90. byte[] tmp = File.ReadAllBytes(path);
  91. port = Int32.Parse(System.Text.Encoding.ASCII.GetString(tmp).Trim());
  92. if ((port <= 0) || (port > 65535))
  93. port = 9993;
  94. }
  95. catch
  96. {
  97. }
  98. return port;
  99. }
  100. private APIHandler()
  101. {
  102. url = "http://127.0.0.1:9993";
  103. }
  104. public APIHandler(int port, string authtoken)
  105. {
  106. url = "http://localhost:" + port;
  107. this.authtoken = authtoken;
  108. }
  109. public void GetStatus(StatusCallback cb)
  110. {
  111. var request = WebRequest.Create(url + "/status" + "?auth=" + authtoken) as HttpWebRequest;
  112. if (request != null)
  113. {
  114. request.Method = "GET";
  115. request.ContentType = "application/json";
  116. }
  117. try
  118. {
  119. var httpResponse = (HttpWebResponse)request.GetResponse();
  120. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  121. {
  122. var responseText = streamReader.ReadToEnd();
  123. ZeroTierStatus status = null;
  124. try
  125. {
  126. status = JsonConvert.DeserializeObject<ZeroTierStatus>(responseText);
  127. }
  128. catch (JsonReaderException e)
  129. {
  130. Console.WriteLine(e.ToString());
  131. }
  132. cb(status);
  133. }
  134. }
  135. catch (System.Net.Sockets.SocketException)
  136. {
  137. cb(null);
  138. }
  139. catch (System.Net.WebException)
  140. {
  141. cb(null);
  142. }
  143. }
  144. public void GetNetworks(NetworkListCallback cb)
  145. {
  146. var request = WebRequest.Create(url + "/network" + "?auth=" + authtoken) as HttpWebRequest;
  147. if (request == null)
  148. {
  149. cb(null);
  150. }
  151. request.Method = "GET";
  152. request.ContentType = "application/json";
  153. request.Timeout = 10000;
  154. try
  155. {
  156. var httpResponse = (HttpWebResponse)request.GetResponse();
  157. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  158. {
  159. var responseText = streamReader.ReadToEnd();
  160. List<ZeroTierNetwork> networkList = null;
  161. try
  162. {
  163. networkList = JsonConvert.DeserializeObject<List<ZeroTierNetwork>>(responseText);
  164. foreach (ZeroTierNetwork n in networkList)
  165. {
  166. // all networks received via JSON are connected by definition
  167. n.IsConnected = true;
  168. }
  169. }
  170. catch (JsonReaderException e)
  171. {
  172. Console.WriteLine(e.ToString());
  173. }
  174. cb(networkList);
  175. }
  176. }
  177. catch (System.Net.Sockets.SocketException)
  178. {
  179. cb(null);
  180. }
  181. catch (System.Net.WebException)
  182. {
  183. cb(null);
  184. }
  185. }
  186. public void JoinNetwork(string nwid, bool allowManaged = true, bool allowGlobal = false, bool allowDefault = false)
  187. {
  188. var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest;
  189. if (request == null)
  190. {
  191. return;
  192. }
  193. request.Method = "POST";
  194. request.ContentType = "applicaiton/json";
  195. request.Timeout = 10000;
  196. using (var streamWriter = new StreamWriter(((HttpWebRequest)request).GetRequestStream()))
  197. {
  198. string json = "{\"allowManaged\":" + (allowManaged ? "true" : "false") + "," +
  199. "\"allowGlobal\":" + (allowGlobal ? "true" : "false") + "," +
  200. "\"allowDefault\":" + (allowDefault ? "true" : "false") + "}";
  201. streamWriter.Write(json);
  202. streamWriter.Flush();
  203. streamWriter.Close();
  204. }
  205. try
  206. {
  207. var httpResponse = (HttpWebResponse)request.GetResponse();
  208. if (httpResponse.StatusCode != HttpStatusCode.OK)
  209. {
  210. Console.WriteLine("Error sending join network message");
  211. }
  212. }
  213. catch (System.Net.Sockets.SocketException)
  214. {
  215. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  216. }
  217. catch (System.Net.WebException)
  218. {
  219. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  220. }
  221. }
  222. public void LeaveNetwork(string nwid)
  223. {
  224. var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest;
  225. if (request == null)
  226. {
  227. return;
  228. }
  229. request.Method = "DELETE";
  230. request.Timeout = 10000;
  231. try
  232. {
  233. var httpResponse = (HttpWebResponse)request.GetResponse();
  234. if (httpResponse.StatusCode != HttpStatusCode.OK)
  235. {
  236. Console.WriteLine("Error sending leave network message");
  237. }
  238. }
  239. catch (System.Net.Sockets.SocketException)
  240. {
  241. MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service.");
  242. }
  243. catch (System.Net.WebException)
  244. {
  245. MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service.");
  246. }
  247. catch
  248. {
  249. Console.WriteLine("Error leaving network: Unknown error");
  250. }
  251. }
  252. public delegate void PeersCallback(List<ZeroTierPeer> peers);
  253. public void GetPeers(PeersCallback cb)
  254. {
  255. var request = WebRequest.Create(url + "/peer" + "?auth=" + authtoken) as HttpWebRequest;
  256. if (request == null)
  257. {
  258. cb(null);
  259. }
  260. request.Method = "GET";
  261. request.ContentType = "application/json";
  262. try
  263. {
  264. var httpResponse = (HttpWebResponse)request.GetResponse();
  265. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  266. {
  267. var responseText = streamReader.ReadToEnd();
  268. //Console.WriteLine(responseText);
  269. List<ZeroTierPeer> peerList = null;
  270. try
  271. {
  272. peerList = JsonConvert.DeserializeObject<List<ZeroTierPeer>>(responseText);
  273. }
  274. catch (JsonReaderException e)
  275. {
  276. Console.WriteLine(e.ToString());
  277. }
  278. cb(peerList);
  279. }
  280. }
  281. catch (System.Net.Sockets.SocketException)
  282. {
  283. cb(null);
  284. }
  285. catch (System.Net.WebException)
  286. {
  287. cb(null);
  288. }
  289. }
  290. }
  291. }