2
0

APIHandler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. try
  156. {
  157. var httpResponse = (HttpWebResponse)request.GetResponse();
  158. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  159. {
  160. var responseText = streamReader.ReadToEnd();
  161. List<ZeroTierNetwork> networkList = null;
  162. try
  163. {
  164. networkList = JsonConvert.DeserializeObject<List<ZeroTierNetwork>>(responseText);
  165. foreach (ZeroTierNetwork n in networkList)
  166. {
  167. // all networks received via JSON are connected by definition
  168. n.IsConnected = true;
  169. }
  170. }
  171. catch (JsonReaderException e)
  172. {
  173. Console.WriteLine(e.ToString());
  174. }
  175. cb(networkList);
  176. }
  177. }
  178. catch (System.Net.Sockets.SocketException)
  179. {
  180. cb(null);
  181. }
  182. catch (System.Net.WebException)
  183. {
  184. cb(null);
  185. }
  186. }
  187. public void JoinNetwork(string nwid, bool allowManaged = true, bool allowGlobal = false, bool allowDefault = false)
  188. {
  189. var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest;
  190. if (request == null)
  191. {
  192. return;
  193. }
  194. request.Method = "POST";
  195. request.ContentType = "applicaiton/json";
  196. using (var streamWriter = new StreamWriter(((HttpWebRequest)request).GetRequestStream()))
  197. {
  198. string json = "{\"allowManaged\":" + (allowManaged ? "true" : "false") + "," +
  199. "\"allowGlobal\":" + (allowGlobal ? "true" : "false") + "," +
  200. "\"allowDefault\":" + (allowDefault ? "true" : "false") + "}";
  201. streamWriter.Write(json);
  202. streamWriter.Flush();
  203. streamWriter.Close();
  204. }
  205. try
  206. {
  207. var httpResponse = (HttpWebResponse)request.GetResponse();
  208. if (httpResponse.StatusCode != HttpStatusCode.OK)
  209. {
  210. Console.WriteLine("Error sending join network message");
  211. }
  212. }
  213. catch (System.Net.Sockets.SocketException)
  214. {
  215. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  216. }
  217. catch (System.Net.WebException)
  218. {
  219. MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service.");
  220. }
  221. }
  222. public void LeaveNetwork(string nwid)
  223. {
  224. var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest;
  225. if (request == null)
  226. {
  227. return;
  228. }
  229. request.Method = "DELETE";
  230. try
  231. {
  232. var httpResponse = (HttpWebResponse)request.GetResponse();
  233. if (httpResponse.StatusCode != HttpStatusCode.OK)
  234. {
  235. Console.WriteLine("Error sending leave network message");
  236. }
  237. }
  238. catch (System.Net.Sockets.SocketException)
  239. {
  240. MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service.");
  241. }
  242. catch (System.Net.WebException)
  243. {
  244. MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service.");
  245. }
  246. }
  247. public delegate void PeersCallback(List<ZeroTierPeer> peers);
  248. public void GetPeers(PeersCallback cb)
  249. {
  250. var request = WebRequest.Create(url + "/peer" + "?auth=" + authtoken) as HttpWebRequest;
  251. if (request == null)
  252. {
  253. cb(null);
  254. }
  255. request.Method = "GET";
  256. request.ContentType = "application/json";
  257. try
  258. {
  259. var httpResponse = (HttpWebResponse)request.GetResponse();
  260. using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  261. {
  262. var responseText = streamReader.ReadToEnd();
  263. //Console.WriteLine(responseText);
  264. List<ZeroTierPeer> peerList = null;
  265. try
  266. {
  267. peerList = JsonConvert.DeserializeObject<List<ZeroTierPeer>>(responseText);
  268. }
  269. catch (JsonReaderException e)
  270. {
  271. Console.WriteLine(e.ToString());
  272. }
  273. cb(peerList);
  274. }
  275. }
  276. catch (System.Net.Sockets.SocketException)
  277. {
  278. cb(null);
  279. }
  280. catch (System.Net.WebException)
  281. {
  282. cb(null);
  283. }
  284. }
  285. }
  286. }