APIHandler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. if (((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized)
  161. {
  162. APIHandler.initHandler(true);
  163. }
  164. else
  165. {
  166. cb(null);
  167. }
  168. }
  169. }
  170. public void GetNetworks(NetworkListCallback cb)
  171. {
  172. var request = WebRequest.Create(url + "/network" + "?auth=" + authtoken) as HttpWebRequest;
  173. if (request == null)
  174. {
  175. cb(null);
  176. }
  177. request.Method = "GET";
  178. request.ContentType = "application/json";
  179. request.Timeout = 10000;
  180. try
  181. {
  182. var httpResponse = (HttpWebResponse)request.GetResponse();
  183. if (httpResponse.StatusCode == HttpStatusCode.OK)
  184. {
  185. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  186. {
  187. var responseText = streamReader.ReadToEnd();
  188. List<ZeroTierNetwork> networkList = null;
  189. try
  190. {
  191. networkList = JsonConvert.DeserializeObject<List<ZeroTierNetwork>>(responseText);
  192. foreach (ZeroTierNetwork n in networkList)
  193. {
  194. // all networks received via JSON are connected by definition
  195. n.IsConnected = true;
  196. }
  197. }
  198. catch (JsonReaderException e)
  199. {
  200. Console.WriteLine(e.ToString());
  201. }
  202. cb(networkList);
  203. }
  204. }
  205. else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  206. {
  207. APIHandler.initHandler(true);
  208. }
  209. }
  210. catch (System.Net.Sockets.SocketException)
  211. {
  212. cb(null);
  213. }
  214. catch (System.Net.WebException e)
  215. {
  216. if (((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized)
  217. {
  218. APIHandler.initHandler(true);
  219. }
  220. else
  221. {
  222. cb(null);
  223. }
  224. }
  225. }
  226. public void JoinNetwork(string nwid, bool allowManaged = true, bool allowGlobal = false, bool allowDefault = false)
  227. {
  228. var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest;
  229. if (request == null)
  230. {
  231. return;
  232. }
  233. request.Method = "POST";
  234. request.ContentType = "applicaiton/json";
  235. request.Timeout = 10000;
  236. try
  237. {
  238. using (var streamWriter = new StreamWriter(((HttpWebRequest)request).GetRequestStream()))
  239. {
  240. string json = "{\"allowManaged\":" + (allowManaged ? "true" : "false") + "," +
  241. "\"allowGlobal\":" + (allowGlobal ? "true" : "false") + "," +
  242. "\"allowDefault\":" + (allowDefault ? "true" : "false") + "}";
  243. streamWriter.Write(json);
  244. streamWriter.Flush();
  245. streamWriter.Close();
  246. }
  247. }
  248. catch (System.Net.WebException)
  249. {
  250. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  251. return;
  252. }
  253. try
  254. {
  255. var httpResponse = (HttpWebResponse)request.GetResponse();
  256. if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  257. {
  258. APIHandler.initHandler(true);
  259. }
  260. else if (httpResponse.StatusCode != HttpStatusCode.OK)
  261. {
  262. Console.WriteLine("Error sending join network message");
  263. }
  264. }
  265. catch (System.Net.Sockets.SocketException)
  266. {
  267. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  268. }
  269. catch (System.Net.WebException e)
  270. {
  271. if (((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized)
  272. {
  273. APIHandler.initHandler(true);
  274. }
  275. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  276. }
  277. }
  278. public void LeaveNetwork(string nwid)
  279. {
  280. var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest;
  281. if (request == null)
  282. {
  283. return;
  284. }
  285. request.Method = "DELETE";
  286. request.Timeout = 10000;
  287. try
  288. {
  289. var httpResponse = (HttpWebResponse)request.GetResponse();
  290. if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  291. {
  292. APIHandler.initHandler(true);
  293. }
  294. else if (httpResponse.StatusCode != HttpStatusCode.OK)
  295. {
  296. Console.WriteLine("Error sending leave network message");
  297. }
  298. }
  299. catch (System.Net.Sockets.SocketException)
  300. {
  301. MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service.");
  302. }
  303. catch (System.Net.WebException e)
  304. {
  305. if (((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized)
  306. {
  307. APIHandler.initHandler(true);
  308. }
  309. MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service.");
  310. }
  311. catch
  312. {
  313. Console.WriteLine("Error leaving network: Unknown error");
  314. }
  315. }
  316. public delegate void PeersCallback(List<ZeroTierPeer> peers);
  317. public void GetPeers(PeersCallback cb)
  318. {
  319. var request = WebRequest.Create(url + "/peer" + "?auth=" + authtoken) as HttpWebRequest;
  320. if (request == null)
  321. {
  322. cb(null);
  323. }
  324. request.Method = "GET";
  325. request.ContentType = "application/json";
  326. try
  327. {
  328. var httpResponse = (HttpWebResponse)request.GetResponse();
  329. if (httpResponse.StatusCode == HttpStatusCode.OK)
  330. {
  331. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  332. {
  333. var responseText = streamReader.ReadToEnd();
  334. //Console.WriteLine(responseText);
  335. List<ZeroTierPeer> peerList = null;
  336. try
  337. {
  338. peerList = JsonConvert.DeserializeObject<List<ZeroTierPeer>>(responseText);
  339. }
  340. catch (JsonReaderException e)
  341. {
  342. Console.WriteLine(e.ToString());
  343. }
  344. cb(peerList);
  345. }
  346. }
  347. else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
  348. {
  349. APIHandler.initHandler(true);
  350. }
  351. }
  352. catch (System.Net.Sockets.SocketException)
  353. {
  354. cb(null);
  355. }
  356. catch (System.Net.WebException e)
  357. {
  358. if (((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized)
  359. {
  360. APIHandler.initHandler(true);
  361. }
  362. else
  363. {
  364. cb(null);
  365. }
  366. }
  367. }
  368. }
  369. }