WebServiceAppsApi.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2024 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.ApplicationCommon;
  16. using DnsServerCore.Auth;
  17. using DnsServerCore.Dns.Applications;
  18. using Microsoft.AspNetCore.Http;
  19. using System;
  20. using System.Collections.Generic;
  21. using System.IO;
  22. using System.Net;
  23. using System.Net.Http;
  24. using System.Text.Json;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. using TechnitiumLibrary.Net.Http.Client;
  28. namespace DnsServerCore
  29. {
  30. sealed class WebServiceAppsApi : IDisposable
  31. {
  32. #region variables
  33. readonly DnsWebService _dnsWebService;
  34. readonly Uri _appStoreUri;
  35. string _storeAppsJsonData;
  36. DateTime _storeAppsJsonDataUpdatedOn;
  37. const int STORE_APPS_JSON_DATA_CACHE_TIME_SECONDS = 900;
  38. Timer _appUpdateTimer;
  39. const int APP_UPDATE_TIMER_INITIAL_INTERVAL = 10000;
  40. const int APP_UPDATE_TIMER_PERIODIC_INTERVAL = 86400000;
  41. #endregion
  42. #region constructor
  43. public WebServiceAppsApi(DnsWebService dnsWebService, Uri appStoreUri)
  44. {
  45. _dnsWebService = dnsWebService;
  46. _appStoreUri = appStoreUri;
  47. }
  48. #endregion
  49. #region IDisposable
  50. bool _disposed;
  51. public void Dispose()
  52. {
  53. if (_disposed)
  54. return;
  55. if (_appUpdateTimer is not null)
  56. _appUpdateTimer.Dispose();
  57. _disposed = true;
  58. }
  59. #endregion
  60. #region private
  61. private void StartAutomaticUpdate()
  62. {
  63. if (_appUpdateTimer is null)
  64. {
  65. _appUpdateTimer = new Timer(async delegate (object state)
  66. {
  67. try
  68. {
  69. if (_dnsWebService.DnsServer.DnsApplicationManager.Applications.Count < 1)
  70. return;
  71. _dnsWebService._log.Write("DNS Server has started automatic update check for DNS Apps.");
  72. string storeAppsJsonData = await GetStoreAppsJsonData(true);
  73. using JsonDocument jsonDocument = JsonDocument.Parse(storeAppsJsonData);
  74. JsonElement jsonStoreAppsArray = jsonDocument.RootElement;
  75. foreach (DnsApplication application in _dnsWebService.DnsServer.DnsApplicationManager.Applications.Values)
  76. {
  77. foreach (JsonElement jsonStoreApp in jsonStoreAppsArray.EnumerateArray())
  78. {
  79. string name = jsonStoreApp.GetProperty("name").GetString();
  80. if (name.Equals(application.Name))
  81. {
  82. string url = null;
  83. Version storeAppVersion = null;
  84. Version lastServerVersion = null;
  85. foreach (JsonElement jsonVersion in jsonStoreApp.GetProperty("versions").EnumerateArray())
  86. {
  87. string strServerVersion = jsonVersion.GetProperty("serverVersion").GetString();
  88. Version requiredServerVersion = new Version(strServerVersion);
  89. if (_dnsWebService._currentVersion < requiredServerVersion)
  90. continue;
  91. if ((lastServerVersion is not null) && (lastServerVersion > requiredServerVersion))
  92. continue;
  93. string version = jsonVersion.GetProperty("version").GetString();
  94. url = jsonVersion.GetProperty("url").GetString();
  95. storeAppVersion = new Version(version);
  96. lastServerVersion = requiredServerVersion;
  97. }
  98. if ((storeAppVersion is not null) && (storeAppVersion > application.Version))
  99. {
  100. try
  101. {
  102. await DownloadAndUpdateAppAsync(application.Name, url, true);
  103. _dnsWebService._log.Write("DNS application '" + application.Name + "' was automatically updated successfully from: " + url);
  104. }
  105. catch (Exception ex)
  106. {
  107. _dnsWebService._log.Write("Failed to automatically download and update DNS application '" + application.Name + "': " + ex.ToString());
  108. }
  109. }
  110. break;
  111. }
  112. }
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. _dnsWebService._log.Write(ex);
  118. }
  119. });
  120. _appUpdateTimer.Change(APP_UPDATE_TIMER_INITIAL_INTERVAL, APP_UPDATE_TIMER_PERIODIC_INTERVAL);
  121. }
  122. }
  123. private void StopAutomaticUpdate()
  124. {
  125. if (_appUpdateTimer is not null)
  126. {
  127. _appUpdateTimer.Dispose();
  128. _appUpdateTimer = null;
  129. }
  130. }
  131. private async Task<string> GetStoreAppsJsonData(bool doRetry)
  132. {
  133. if ((_storeAppsJsonData is null) || (DateTime.UtcNow > _storeAppsJsonDataUpdatedOn.AddSeconds(STORE_APPS_JSON_DATA_CACHE_TIME_SECONDS)))
  134. {
  135. SocketsHttpHandler handler = new SocketsHttpHandler();
  136. handler.Proxy = _dnsWebService.DnsServer.Proxy;
  137. handler.UseProxy = _dnsWebService.DnsServer.Proxy is not null;
  138. handler.AutomaticDecompression = DecompressionMethods.All;
  139. HttpClientNetworkHandler networkHandler = new HttpClientNetworkHandler(handler, _dnsWebService.DnsServer.PreferIPv6 ? HttpClientNetworkType.PreferIPv6 : HttpClientNetworkType.Default, _dnsWebService.DnsServer);
  140. if (!doRetry)
  141. networkHandler.Retries = 1;
  142. using (HttpClient http = new HttpClient(networkHandler))
  143. {
  144. _storeAppsJsonData = await http.GetStringAsync(_appStoreUri);
  145. _storeAppsJsonDataUpdatedOn = DateTime.UtcNow;
  146. }
  147. }
  148. return _storeAppsJsonData;
  149. }
  150. private async Task<DnsApplication> DownloadAndUpdateAppAsync(string applicationName, string url, bool doRetry)
  151. {
  152. string tmpFile = Path.GetTempFileName();
  153. try
  154. {
  155. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  156. {
  157. //download to temp file
  158. SocketsHttpHandler handler = new SocketsHttpHandler();
  159. handler.Proxy = _dnsWebService.DnsServer.Proxy;
  160. handler.UseProxy = _dnsWebService.DnsServer.Proxy is not null;
  161. handler.AutomaticDecompression = DecompressionMethods.All;
  162. HttpClientNetworkHandler networkHandler = new HttpClientNetworkHandler(handler, _dnsWebService.DnsServer.PreferIPv6 ? HttpClientNetworkType.PreferIPv6 : HttpClientNetworkType.Default, _dnsWebService.DnsServer);
  163. if (!doRetry)
  164. networkHandler.Retries = 1;
  165. using (HttpClient http = new HttpClient(networkHandler))
  166. {
  167. using (Stream httpStream = await http.GetStreamAsync(url))
  168. {
  169. await httpStream.CopyToAsync(fS);
  170. }
  171. }
  172. //update app
  173. fS.Position = 0;
  174. return await _dnsWebService.DnsServer.DnsApplicationManager.UpdateApplicationAsync(applicationName, fS);
  175. }
  176. }
  177. finally
  178. {
  179. try
  180. {
  181. File.Delete(tmpFile);
  182. }
  183. catch (Exception ex)
  184. {
  185. _dnsWebService._log.Write(ex);
  186. }
  187. }
  188. }
  189. private void WriteAppAsJson(Utf8JsonWriter jsonWriter, DnsApplication application, JsonElement jsonStoreAppsArray = default)
  190. {
  191. jsonWriter.WriteStartObject();
  192. jsonWriter.WriteString("name", application.Name);
  193. jsonWriter.WriteString("description", application.Description);
  194. jsonWriter.WriteString("version", DnsWebService.GetCleanVersion(application.Version));
  195. if (jsonStoreAppsArray.ValueKind != JsonValueKind.Undefined)
  196. {
  197. foreach (JsonElement jsonStoreApp in jsonStoreAppsArray.EnumerateArray())
  198. {
  199. string name = jsonStoreApp.GetProperty("name").GetString();
  200. if (name.Equals(application.Name))
  201. {
  202. string version = null;
  203. string url = null;
  204. Version storeAppVersion = null;
  205. Version lastServerVersion = null;
  206. foreach (JsonElement jsonVersion in jsonStoreApp.GetProperty("versions").EnumerateArray())
  207. {
  208. string strServerVersion = jsonVersion.GetProperty("serverVersion").GetString();
  209. Version requiredServerVersion = new Version(strServerVersion);
  210. if (_dnsWebService._currentVersion < requiredServerVersion)
  211. continue;
  212. if ((lastServerVersion is not null) && (lastServerVersion > requiredServerVersion))
  213. continue;
  214. version = jsonVersion.GetProperty("version").GetString();
  215. url = jsonVersion.GetProperty("url").GetString();
  216. storeAppVersion = new Version(version);
  217. lastServerVersion = requiredServerVersion;
  218. }
  219. if (storeAppVersion is null)
  220. break; //no compatible update available
  221. jsonWriter.WriteString("updateVersion", version);
  222. jsonWriter.WriteString("updateUrl", url);
  223. jsonWriter.WriteBoolean("updateAvailable", storeAppVersion > application.Version);
  224. break;
  225. }
  226. }
  227. }
  228. jsonWriter.WritePropertyName("dnsApps");
  229. {
  230. jsonWriter.WriteStartArray();
  231. foreach (KeyValuePair<string, IDnsApplication> dnsApp in application.DnsApplications)
  232. {
  233. jsonWriter.WriteStartObject();
  234. jsonWriter.WriteString("classPath", dnsApp.Key);
  235. jsonWriter.WriteString("description", dnsApp.Value.Description);
  236. if (dnsApp.Value is IDnsAppRecordRequestHandler appRecordHandler)
  237. {
  238. jsonWriter.WriteBoolean("isAppRecordRequestHandler", true);
  239. jsonWriter.WriteString("recordDataTemplate", appRecordHandler.ApplicationRecordDataTemplate);
  240. }
  241. else
  242. {
  243. jsonWriter.WriteBoolean("isAppRecordRequestHandler", false);
  244. }
  245. jsonWriter.WriteBoolean("isRequestController", dnsApp.Value is IDnsRequestController);
  246. jsonWriter.WriteBoolean("isAuthoritativeRequestHandler", dnsApp.Value is IDnsAuthoritativeRequestHandler);
  247. jsonWriter.WriteBoolean("isRequestBlockingHandler", dnsApp.Value is IDnsRequestBlockingHandler);
  248. jsonWriter.WriteBoolean("isQueryLogger", dnsApp.Value is IDnsQueryLogger);
  249. jsonWriter.WriteBoolean("isPostProcessor", dnsApp.Value is IDnsPostProcessor);
  250. jsonWriter.WriteEndObject();
  251. }
  252. jsonWriter.WriteEndArray();
  253. }
  254. jsonWriter.WriteEndObject();
  255. }
  256. #endregion
  257. #region public
  258. public async Task ListInstalledAppsAsync(HttpContext context)
  259. {
  260. UserSession session = context.GetCurrentSession();
  261. if (
  262. !_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.View) &&
  263. !_dnsWebService._authManager.IsPermitted(PermissionSection.Zones, session.User, PermissionFlag.View) &&
  264. !_dnsWebService._authManager.IsPermitted(PermissionSection.Logs, session.User, PermissionFlag.View)
  265. )
  266. {
  267. throw new DnsWebServiceException("Access was denied.");
  268. }
  269. List<string> apps = new List<string>(_dnsWebService.DnsServer.DnsApplicationManager.Applications.Keys);
  270. apps.Sort();
  271. JsonDocument jsonDocument = null;
  272. try
  273. {
  274. JsonElement jsonStoreAppsArray = default;
  275. if (apps.Count > 0)
  276. {
  277. try
  278. {
  279. string storeAppsJsonData = await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  280. {
  281. return GetStoreAppsJsonData(false);
  282. }, 5000);
  283. jsonDocument = JsonDocument.Parse(storeAppsJsonData);
  284. jsonStoreAppsArray = jsonDocument.RootElement;
  285. }
  286. catch (Exception ex)
  287. {
  288. _dnsWebService._log.Write(ex);
  289. }
  290. }
  291. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  292. jsonWriter.WritePropertyName("apps");
  293. jsonWriter.WriteStartArray();
  294. foreach (string app in apps)
  295. {
  296. if (_dnsWebService.DnsServer.DnsApplicationManager.Applications.TryGetValue(app, out DnsApplication application))
  297. WriteAppAsJson(jsonWriter, application, jsonStoreAppsArray);
  298. }
  299. jsonWriter.WriteEndArray();
  300. }
  301. finally
  302. {
  303. if (jsonDocument is not null)
  304. jsonDocument.Dispose();
  305. }
  306. }
  307. public async Task ListStoreApps(HttpContext context)
  308. {
  309. UserSession session = context.GetCurrentSession();
  310. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.View))
  311. throw new DnsWebServiceException("Access was denied.");
  312. string storeAppsJsonData = await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  313. {
  314. return GetStoreAppsJsonData(false);
  315. }, 30000);
  316. using JsonDocument jsonDocument = JsonDocument.Parse(storeAppsJsonData);
  317. JsonElement jsonStoreAppsArray = jsonDocument.RootElement;
  318. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  319. jsonWriter.WritePropertyName("storeApps");
  320. jsonWriter.WriteStartArray();
  321. foreach (JsonElement jsonStoreApp in jsonStoreAppsArray.EnumerateArray())
  322. {
  323. string name = jsonStoreApp.GetProperty("name").GetString();
  324. string description = jsonStoreApp.GetProperty("description").GetString();
  325. string version = null;
  326. string url = null;
  327. string size = null;
  328. Version storeAppVersion = null;
  329. Version lastServerVersion = null;
  330. foreach (JsonElement jsonVersion in jsonStoreApp.GetProperty("versions").EnumerateArray())
  331. {
  332. string strServerVersion = jsonVersion.GetProperty("serverVersion").GetString();
  333. Version requiredServerVersion = new Version(strServerVersion);
  334. if (_dnsWebService._currentVersion < requiredServerVersion)
  335. continue;
  336. if ((lastServerVersion is not null) && (lastServerVersion > requiredServerVersion))
  337. continue;
  338. version = jsonVersion.GetProperty("version").GetString();
  339. url = jsonVersion.GetProperty("url").GetString();
  340. size = jsonVersion.GetProperty("size").GetString();
  341. storeAppVersion = new Version(version);
  342. lastServerVersion = requiredServerVersion;
  343. }
  344. if (storeAppVersion is null)
  345. continue; //app is not compatible
  346. jsonWriter.WriteStartObject();
  347. jsonWriter.WriteString("name", name);
  348. jsonWriter.WriteString("description", description);
  349. jsonWriter.WriteString("version", version);
  350. jsonWriter.WriteString("url", url);
  351. jsonWriter.WriteString("size", size);
  352. bool installed = _dnsWebService.DnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication installedApp);
  353. jsonWriter.WriteBoolean("installed", installed);
  354. if (installed)
  355. {
  356. jsonWriter.WriteString("installedVersion", DnsWebService.GetCleanVersion(installedApp.Version));
  357. jsonWriter.WriteBoolean("updateAvailable", storeAppVersion > installedApp.Version);
  358. }
  359. jsonWriter.WriteEndObject();
  360. }
  361. jsonWriter.WriteEndArray();
  362. }
  363. public async Task DownloadAndInstallAppAsync(HttpContext context)
  364. {
  365. UserSession session = context.GetCurrentSession();
  366. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.Delete))
  367. throw new DnsWebServiceException("Access was denied.");
  368. HttpRequest request = context.Request;
  369. string name = request.GetQueryOrForm("name").Trim();
  370. string url = request.GetQueryOrForm("url");
  371. if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  372. throw new DnsWebServiceException("Parameter 'url' value must start with 'https://'.");
  373. string tmpFile = Path.GetTempFileName();
  374. try
  375. {
  376. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  377. {
  378. //download to temp file
  379. SocketsHttpHandler handler = new SocketsHttpHandler();
  380. handler.Proxy = _dnsWebService.DnsServer.Proxy;
  381. handler.UseProxy = _dnsWebService.DnsServer.Proxy is not null;
  382. handler.AutomaticDecompression = DecompressionMethods.All;
  383. using (HttpClient http = new HttpClient(new HttpClientNetworkHandler(handler, _dnsWebService.DnsServer.PreferIPv6 ? HttpClientNetworkType.PreferIPv6 : HttpClientNetworkType.Default, _dnsWebService.DnsServer)))
  384. {
  385. using (Stream httpStream = await http.GetStreamAsync(url))
  386. {
  387. await httpStream.CopyToAsync(fS);
  388. }
  389. }
  390. //install app
  391. fS.Position = 0;
  392. DnsApplication application = await _dnsWebService.DnsServer.DnsApplicationManager.InstallApplicationAsync(name, fS);
  393. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] DNS application '" + name + "' was installed successfully from: " + url);
  394. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  395. jsonWriter.WritePropertyName("installedApp");
  396. WriteAppAsJson(jsonWriter, application);
  397. }
  398. }
  399. finally
  400. {
  401. try
  402. {
  403. File.Delete(tmpFile);
  404. }
  405. catch (Exception ex)
  406. {
  407. _dnsWebService._log.Write(ex);
  408. }
  409. }
  410. }
  411. public async Task DownloadAndUpdateAppAsync(HttpContext context)
  412. {
  413. UserSession session = context.GetCurrentSession();
  414. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.Delete))
  415. throw new DnsWebServiceException("Access was denied.");
  416. HttpRequest request = context.Request;
  417. string name = request.GetQueryOrForm("name").Trim();
  418. string url = request.GetQueryOrForm("url");
  419. if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  420. throw new DnsWebServiceException("Parameter 'url' value must start with 'https://'.");
  421. DnsApplication application = await DownloadAndUpdateAppAsync(name, url, false);
  422. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] DNS application '" + name + "' was updated successfully from: " + url);
  423. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  424. jsonWriter.WritePropertyName("updatedApp");
  425. WriteAppAsJson(jsonWriter, application);
  426. }
  427. public async Task InstallAppAsync(HttpContext context)
  428. {
  429. UserSession session = context.GetCurrentSession();
  430. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.Delete))
  431. throw new DnsWebServiceException("Access was denied.");
  432. HttpRequest request = context.Request;
  433. string name = request.GetQueryOrForm("name").Trim();
  434. if (!request.HasFormContentType || (request.Form.Files.Count == 0))
  435. throw new DnsWebServiceException("DNS application zip file is missing.");
  436. string tmpFile = Path.GetTempFileName();
  437. try
  438. {
  439. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  440. {
  441. //write to temp file
  442. await request.Form.Files[0].CopyToAsync(fS);
  443. //install app
  444. fS.Position = 0;
  445. DnsApplication application = await _dnsWebService.DnsServer.DnsApplicationManager.InstallApplicationAsync(name, fS);
  446. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] DNS application '" + name + "' was installed successfully.");
  447. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  448. jsonWriter.WritePropertyName("installedApp");
  449. WriteAppAsJson(jsonWriter, application);
  450. }
  451. }
  452. finally
  453. {
  454. try
  455. {
  456. File.Delete(tmpFile);
  457. }
  458. catch (Exception ex)
  459. {
  460. _dnsWebService._log.Write(ex);
  461. }
  462. }
  463. }
  464. public async Task UpdateAppAsync(HttpContext context)
  465. {
  466. UserSession session = context.GetCurrentSession();
  467. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.Delete))
  468. throw new DnsWebServiceException("Access was denied.");
  469. HttpRequest request = context.Request;
  470. string name = request.GetQueryOrForm("name").Trim();
  471. if (!request.HasFormContentType || (request.Form.Files.Count == 0))
  472. throw new DnsWebServiceException("DNS application zip file is missing.");
  473. string tmpFile = Path.GetTempFileName();
  474. try
  475. {
  476. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  477. {
  478. //write to temp file
  479. await request.Form.Files[0].CopyToAsync(fS);
  480. //update app
  481. fS.Position = 0;
  482. DnsApplication application = await _dnsWebService.DnsServer.DnsApplicationManager.UpdateApplicationAsync(name, fS);
  483. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] DNS application '" + name + "' was updated successfully.");
  484. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  485. jsonWriter.WritePropertyName("updatedApp");
  486. WriteAppAsJson(jsonWriter, application);
  487. }
  488. }
  489. finally
  490. {
  491. try
  492. {
  493. File.Delete(tmpFile);
  494. }
  495. catch (Exception ex)
  496. {
  497. _dnsWebService._log.Write(ex);
  498. }
  499. }
  500. }
  501. public void UninstallApp(HttpContext context)
  502. {
  503. UserSession session = context.GetCurrentSession();
  504. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.Delete))
  505. throw new DnsWebServiceException("Access was denied.");
  506. HttpRequest request = context.Request;
  507. string name = request.GetQueryOrForm("name").Trim();
  508. _dnsWebService.DnsServer.DnsApplicationManager.UninstallApplication(name);
  509. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] DNS application '" + name + "' was uninstalled successfully.");
  510. }
  511. public async Task GetAppConfigAsync(HttpContext context)
  512. {
  513. UserSession session = context.GetCurrentSession();
  514. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.View))
  515. throw new DnsWebServiceException("Access was denied.");
  516. HttpRequest request = context.Request;
  517. string name = request.GetQueryOrForm("name").Trim();
  518. if (!_dnsWebService.DnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
  519. throw new DnsWebServiceException("DNS application was not found: " + name);
  520. string config = await application.GetConfigAsync();
  521. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  522. jsonWriter.WriteString("config", config);
  523. }
  524. public async Task SetAppConfigAsync(HttpContext context)
  525. {
  526. UserSession session = context.GetCurrentSession();
  527. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Apps, session.User, PermissionFlag.Modify))
  528. throw new DnsWebServiceException("Access was denied.");
  529. HttpRequest request = context.Request;
  530. string name = request.GetQueryOrForm("name").Trim();
  531. if (!_dnsWebService.DnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
  532. throw new DnsWebServiceException("DNS application was not found: " + name);
  533. string config = request.QueryOrForm("config");
  534. if (config is null)
  535. throw new DnsWebServiceException("Parameter 'config' missing.");
  536. if (config.Length == 0)
  537. config = null;
  538. await application.SetConfigAsync(config);
  539. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] DNS application '" + name + "' app config was saved successfully.");
  540. }
  541. #endregion
  542. #region properties
  543. public bool EnableAutomaticUpdate
  544. {
  545. get { return _appUpdateTimer is not null; }
  546. set
  547. {
  548. if (value)
  549. StartAutomaticUpdate();
  550. else
  551. StopAutomaticUpdate();
  552. }
  553. }
  554. #endregion
  555. }
  556. }