APIHandler.cs 11 KB

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