APIHandler.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. using System.Windows.Threading;
  12. namespace WinUI
  13. {
  14. public class APIHandler
  15. {
  16. private string authtoken;
  17. private string url = null;
  18. private static volatile APIHandler instance;
  19. private static object syncRoot = new Object();
  20. public delegate void NetworkListCallback(List<ZeroTierNetwork> networks);
  21. public delegate void StatusCallback(ZeroTierStatus status);
  22. private string ZeroTierAddress = "";
  23. public static APIHandler Instance
  24. {
  25. get
  26. {
  27. if (instance == null)
  28. {
  29. lock (syncRoot)
  30. {
  31. if (instance == null)
  32. {
  33. if (!initHandler())
  34. {
  35. return null;
  36. }
  37. }
  38. }
  39. }
  40. return instance;
  41. }
  42. }
  43. private static bool initHandler(bool resetToken = false)
  44. {
  45. String localZtDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ZeroTier\\One";
  46. String globalZtDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\ZeroTier\\One";
  47. String authToken = "";
  48. Int32 port = 9993;
  49. if (resetToken)
  50. {
  51. instance = null;
  52. if (File.Exists(localZtDir + "\\authtoken.secret"))
  53. {
  54. File.Delete(localZtDir + "\\authtoken.secret");
  55. }
  56. if (File.Exists(localZtDir + "\\zerotier-one.port"))
  57. {
  58. File.Delete(localZtDir + "\\zerotier-one.port");
  59. }
  60. }
  61. if (!File.Exists(localZtDir + "\\authtoken.secret") || !File.Exists(localZtDir + "\\zerotier-one.port"))
  62. {
  63. // launch external process to copy file into place
  64. String curPath = System.Reflection.Assembly.GetEntryAssembly().Location;
  65. int index = curPath.LastIndexOf("\\");
  66. curPath = curPath.Substring(0, index);
  67. ProcessStartInfo startInfo = new ProcessStartInfo(curPath + "\\copyutil.exe", "\"" + globalZtDir + "\"" + " " + "\"" + localZtDir + "\"");
  68. startInfo.Verb = "runas";
  69. var process = Process.Start(startInfo);
  70. process.WaitForExit();
  71. }
  72. authToken = readAuthToken(localZtDir + "\\authtoken.secret");
  73. if ((authToken == null) || (authToken.Length <= 0))
  74. {
  75. MessageBox.Show("Unable to read ZeroTier One authtoken", "ZeroTier One");
  76. return false;
  77. }
  78. port = readPort(localZtDir + "\\zerotier-one.port");
  79. instance = new APIHandler(port, authToken);
  80. return true;
  81. }
  82. private static String readAuthToken(String path)
  83. {
  84. String authToken = "";
  85. if (File.Exists(path))
  86. {
  87. try
  88. {
  89. byte[] tmp = File.ReadAllBytes(path);
  90. authToken = System.Text.Encoding.UTF8.GetString(tmp).Trim();
  91. }
  92. catch
  93. {
  94. MessageBox.Show("Unable to read ZeroTier One Auth Token from:\r\n" + path, "ZeroTier One");
  95. }
  96. }
  97. return authToken;
  98. }
  99. private static Int32 readPort(String path)
  100. {
  101. Int32 port = 9993;
  102. try
  103. {
  104. byte[] tmp = File.ReadAllBytes(path);
  105. port = Int32.Parse(System.Text.Encoding.ASCII.GetString(tmp).Trim());
  106. if ((port <= 0) || (port > 65535))
  107. port = 9993;
  108. }
  109. catch
  110. {
  111. }
  112. return port;
  113. }
  114. private APIHandler()
  115. {
  116. url = "http://127.0.0.1:9993";
  117. }
  118. public APIHandler(int port, string authtoken)
  119. {
  120. url = "http://127.0.0.1:" + port;
  121. this.authtoken = authtoken;
  122. }
  123. public void GetStatus(StatusCallback cb)
  124. {
  125. var request = WebRequest.Create(url + "/status" + "?auth=" + authtoken) as HttpWebRequest;
  126. if (request != null)
  127. {
  128. request.Method = "GET";
  129. request.ContentType = "application/json";
  130. }
  131. try
  132. {
  133. var httpResponse = (HttpWebResponse)request.GetResponse();
  134. if (httpResponse.StatusCode == HttpStatusCode.OK)
  135. {
  136. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  137. {
  138. var responseText = streamReader.ReadToEnd();
  139. ZeroTierStatus status = null;
  140. try
  141. {
  142. status = JsonConvert.DeserializeObject<ZeroTierStatus>(responseText);
  143. if (ZeroTierAddress != status.Address)
  144. {
  145. ZeroTierAddress = status.Address;
  146. }
  147. }
  148. catch (JsonReaderException e)
  149. {
  150. Console.WriteLine(e.ToString());
  151. }
  152. cb(status);
  153. }
  154. }
  155. else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  156. {
  157. APIHandler.initHandler(true);
  158. }
  159. }
  160. catch (System.Net.Sockets.SocketException)
  161. {
  162. cb(null);
  163. }
  164. catch (System.Net.WebException e)
  165. {
  166. HttpWebResponse res = (HttpWebResponse)e.Response;
  167. if (res != null && res.StatusCode == HttpStatusCode.Unauthorized)
  168. {
  169. APIHandler.initHandler(true);
  170. }
  171. else
  172. {
  173. cb(null);
  174. }
  175. }
  176. }
  177. public void GetNetworks(NetworkListCallback cb)
  178. {
  179. var request = WebRequest.Create(url + "/network" + "?auth=" + authtoken) as HttpWebRequest;
  180. if (request == null)
  181. {
  182. cb(null);
  183. }
  184. request.Method = "GET";
  185. request.ContentType = "application/json";
  186. request.Timeout = 10000;
  187. try
  188. {
  189. var httpResponse = (HttpWebResponse)request.GetResponse();
  190. if (httpResponse.StatusCode == HttpStatusCode.OK)
  191. {
  192. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  193. {
  194. var responseText = streamReader.ReadToEnd();
  195. List<ZeroTierNetwork> networkList = null;
  196. try
  197. {
  198. networkList = JsonConvert.DeserializeObject<List<ZeroTierNetwork>>(responseText);
  199. foreach (ZeroTierNetwork n in networkList)
  200. {
  201. // all networks received via JSON are connected by definition
  202. n.IsConnected = true;
  203. }
  204. }
  205. catch (JsonReaderException e)
  206. {
  207. Console.WriteLine(e.ToString());
  208. }
  209. cb(networkList);
  210. }
  211. }
  212. else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  213. {
  214. APIHandler.initHandler(true);
  215. }
  216. }
  217. catch (System.Net.Sockets.SocketException)
  218. {
  219. cb(null);
  220. }
  221. catch (System.Net.WebException e)
  222. {
  223. HttpWebResponse res = (HttpWebResponse)e.Response;
  224. if (res != null && res.StatusCode == HttpStatusCode.Unauthorized)
  225. {
  226. APIHandler.initHandler(true);
  227. }
  228. else
  229. {
  230. cb(null);
  231. }
  232. }
  233. }
  234. public void JoinNetwork(Dispatcher d, string nwid, bool allowManaged = true, bool allowGlobal = false, bool allowDefault = false, bool allowDNS = false)
  235. {
  236. Task.Factory.StartNew(() =>
  237. {
  238. var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest;
  239. if (request == null)
  240. {
  241. return;
  242. }
  243. request.Method = "POST";
  244. request.ContentType = "applicaiton/json";
  245. request.Timeout = 30000;
  246. try
  247. {
  248. using (var streamWriter = new StreamWriter(((HttpWebRequest)request).GetRequestStream()))
  249. {
  250. string json = "{\"allowManaged\":" + (allowManaged ? "true" : "false") + "," +
  251. "\"allowGlobal\":" + (allowGlobal ? "true" : "false") + "," +
  252. "\"allowDefault\":" + (allowDefault ? "true" : "false") + "," +
  253. "\"allowDNS\":" + (allowDNS ? "true" : "false") + "}";
  254. streamWriter.Write(json);
  255. streamWriter.Flush();
  256. streamWriter.Close();
  257. }
  258. }
  259. catch (System.Net.WebException)
  260. {
  261. d.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  262. {
  263. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  264. }));
  265. return;
  266. }
  267. try
  268. {
  269. var httpResponse = (HttpWebResponse)request.GetResponse();
  270. if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  271. {
  272. APIHandler.initHandler(true);
  273. }
  274. else if (httpResponse.StatusCode != HttpStatusCode.OK)
  275. {
  276. Console.WriteLine("Error sending join network message");
  277. }
  278. }
  279. catch (System.Net.Sockets.SocketException)
  280. {
  281. d.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  282. {
  283. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  284. }));
  285. }
  286. catch (System.Net.WebException e)
  287. {
  288. HttpWebResponse res = (HttpWebResponse)e.Response;
  289. if (res != null && res.StatusCode == HttpStatusCode.Unauthorized)
  290. {
  291. APIHandler.initHandler(true);
  292. }
  293. d.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  294. {
  295. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  296. }));
  297. }
  298. });
  299. }
  300. public void LeaveNetwork(Dispatcher d, string nwid)
  301. {
  302. Task.Factory.StartNew(() =>
  303. {
  304. var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest;
  305. if (request == null)
  306. {
  307. return;
  308. }
  309. request.Method = "DELETE";
  310. request.Timeout = 30000;
  311. try
  312. {
  313. var httpResponse = (HttpWebResponse)request.GetResponse();
  314. if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  315. {
  316. APIHandler.initHandler(true);
  317. }
  318. else if (httpResponse.StatusCode != HttpStatusCode.OK)
  319. {
  320. Console.WriteLine("Error sending leave network message");
  321. }
  322. }
  323. catch (System.Net.Sockets.SocketException)
  324. {
  325. d.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  326. {
  327. MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service.");
  328. }));
  329. }
  330. catch (System.Net.WebException e)
  331. {
  332. HttpWebResponse res = (HttpWebResponse)e.Response;
  333. if (res != null && res.StatusCode == HttpStatusCode.Unauthorized)
  334. {
  335. APIHandler.initHandler(true);
  336. }
  337. d.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  338. {
  339. MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service.");
  340. }));
  341. }
  342. catch
  343. {
  344. Console.WriteLine("Error leaving network: Unknown error");
  345. }
  346. });
  347. }
  348. public delegate void PeersCallback(List<ZeroTierPeer> peers);
  349. public void GetPeers(PeersCallback cb)
  350. {
  351. var request = WebRequest.Create(url + "/peer" + "?auth=" + authtoken) as HttpWebRequest;
  352. if (request == null)
  353. {
  354. cb(null);
  355. }
  356. request.Method = "GET";
  357. request.ContentType = "application/json";
  358. try
  359. {
  360. var httpResponse = (HttpWebResponse)request.GetResponse();
  361. if (httpResponse.StatusCode == HttpStatusCode.OK)
  362. {
  363. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  364. {
  365. var responseText = streamReader.ReadToEnd();
  366. //Console.WriteLine(responseText);
  367. List<ZeroTierPeer> peerList = null;
  368. try
  369. {
  370. peerList = JsonConvert.DeserializeObject<List<ZeroTierPeer>>(responseText);
  371. }
  372. catch (JsonReaderException e)
  373. {
  374. Console.WriteLine(e.ToString());
  375. }
  376. cb(peerList);
  377. }
  378. }
  379. else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  380. {
  381. APIHandler.initHandler(true);
  382. }
  383. }
  384. catch (System.Net.Sockets.SocketException)
  385. {
  386. cb(null);
  387. }
  388. catch (System.Net.WebException e)
  389. {
  390. HttpWebResponse res = (HttpWebResponse)e.Response;
  391. if (res != null && res.StatusCode == HttpStatusCode.Unauthorized)
  392. {
  393. APIHandler.initHandler(true);
  394. }
  395. else
  396. {
  397. cb(null);
  398. }
  399. }
  400. }
  401. public string NodeAddress()
  402. {
  403. return ZeroTierAddress;
  404. }
  405. }
  406. }