APIHandler.cs 13 KB

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