APIHandler.cs 10 KB

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