APIHandler.cs 13 KB

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