You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

634 lines
15KB

  1. #include "plugin.hpp"
  2. #include "system.hpp"
  3. #include "network.hpp"
  4. #include "asset.hpp"
  5. #include "string.hpp"
  6. #include "app.hpp"
  7. #include "app/common.hpp"
  8. #include "plugin/callbacks.hpp"
  9. #include "settings.hpp"
  10. #include <unistd.h>
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13. #include <sys/param.h> // for MAXPATHLEN
  14. #include <fcntl.h>
  15. #include <thread>
  16. #include <map>
  17. #include <stdexcept>
  18. #define ZIP_STATIC
  19. #include <zip.h>
  20. #include <jansson.h>
  21. #if defined ARCH_WIN
  22. #include <windows.h>
  23. #include <direct.h>
  24. #define mkdir(_dir, _perms) _mkdir(_dir)
  25. #else
  26. #include <dlfcn.h>
  27. #endif
  28. #include <dirent.h>
  29. #include <osdialog.h>
  30. namespace rack {
  31. namespace plugin {
  32. ////////////////////
  33. // private API
  34. ////////////////////
  35. static bool loadPlugin(std::string path) {
  36. // Load plugin.json
  37. std::string metadataFilename = path + "/plugin.json";
  38. FILE *file = fopen(metadataFilename.c_str(), "r");
  39. if (!file) {
  40. WARN("Plugin metadata file %s does not exist", metadataFilename.c_str());
  41. return false;
  42. }
  43. DEFER({
  44. fclose(file);
  45. });
  46. json_error_t error;
  47. json_t *rootJ = json_loadf(file, 0, &error);
  48. if (!rootJ) {
  49. WARN("JSON parsing error at %s %d:%d %s", error.source, error.line, error.column, error.text);
  50. return false;
  51. }
  52. DEFER({
  53. json_decref(rootJ);
  54. });
  55. // Load plugin library
  56. std::string libraryFilename;
  57. #if defined ARCH_LIN
  58. libraryFilename = path + "/" + "plugin.so";
  59. #elif defined ARCH_WIN
  60. libraryFilename = path + "/" + "plugin.dll";
  61. #elif ARCH_MAC
  62. libraryFilename = path + "/" + "plugin.dylib";
  63. #endif
  64. // Check file existence
  65. if (!system::isFile(libraryFilename)) {
  66. WARN("Plugin file %s does not exist", libraryFilename.c_str());
  67. return false;
  68. }
  69. // Load dynamic/shared library
  70. #if defined ARCH_WIN
  71. SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
  72. HINSTANCE handle = LoadLibrary(libraryFilename.c_str());
  73. SetErrorMode(0);
  74. if (!handle) {
  75. int error = GetLastError();
  76. WARN("Failed to load library %s: code %d", libraryFilename.c_str(), error);
  77. return false;
  78. }
  79. #else
  80. void *handle = dlopen(libraryFilename.c_str(), RTLD_NOW);
  81. if (!handle) {
  82. WARN("Failed to load library %s: %s", libraryFilename.c_str(), dlerror());
  83. return false;
  84. }
  85. #endif
  86. // Call plugin's init() function
  87. typedef void (*InitCallback)(Plugin *);
  88. InitCallback initCallback;
  89. #if defined ARCH_WIN
  90. initCallback = (InitCallback) GetProcAddress(handle, "init");
  91. #else
  92. initCallback = (InitCallback) dlsym(handle, "init");
  93. #endif
  94. if (!initCallback) {
  95. WARN("Failed to read init() symbol in %s", libraryFilename.c_str());
  96. return false;
  97. }
  98. // Construct and initialize Plugin instance
  99. Plugin *plugin = new Plugin;
  100. plugin->path = path;
  101. plugin->handle = handle;
  102. initCallback(plugin);
  103. plugin->fromJson(rootJ);
  104. // Check slug
  105. if (!isSlugValid(plugin->slug)) {
  106. WARN("Plugin slug \"%s\" is invalid", plugin->slug.c_str());
  107. // TODO Fix memory leak with `plugin`
  108. return false;
  109. }
  110. // Reject plugin if slug already exists
  111. Plugin *oldPlugin = getPlugin(plugin->slug);
  112. if (oldPlugin) {
  113. WARN("Plugin \"%s\" is already loaded, not attempting to load it again", plugin->slug.c_str());
  114. // TODO Fix memory leak with `plugin`
  115. return false;
  116. }
  117. // Add plugin to list
  118. plugins.push_back(plugin);
  119. INFO("Loaded plugin %s v%s from %s", plugin->slug.c_str(), plugin->version.c_str(), libraryFilename.c_str());
  120. return true;
  121. }
  122. static bool syncPlugin(std::string slug, json_t *manifestJ, bool dryRun) {
  123. // Check that "status" is "available"
  124. json_t *statusJ = json_object_get(manifestJ, "status");
  125. if (!statusJ) {
  126. return false;
  127. }
  128. std::string status = json_string_value(statusJ);
  129. if (status != "available") {
  130. return false;
  131. }
  132. // Get latest version
  133. json_t *latestVersionJ = json_object_get(manifestJ, "latestVersion");
  134. if (!latestVersionJ) {
  135. WARN("Could not get latest version of plugin %s", slug.c_str());
  136. return false;
  137. }
  138. std::string latestVersion = json_string_value(latestVersionJ);
  139. // Check whether we already have a plugin with the same slug and version
  140. Plugin *plugin = getPlugin(slug);
  141. if (plugin && plugin->version == latestVersion) {
  142. return false;
  143. }
  144. json_t *nameJ = json_object_get(manifestJ, "name");
  145. std::string name;
  146. if (nameJ) {
  147. name = json_string_value(nameJ);
  148. }
  149. else {
  150. name = slug;
  151. }
  152. #if defined ARCH_WIN
  153. std::string arch = "win";
  154. #elif ARCH_MAC
  155. std::string arch = "mac";
  156. #elif defined ARCH_LIN
  157. std::string arch = "lin";
  158. #endif
  159. std::string downloadUrl;
  160. downloadUrl = app::API_URL;
  161. downloadUrl += "/download";
  162. if (dryRun) {
  163. downloadUrl += "/available";
  164. }
  165. downloadUrl += "?token=" + network::encodeUrl(settings.token);
  166. downloadUrl += "&slug=" + network::encodeUrl(slug);
  167. downloadUrl += "&version=" + network::encodeUrl(latestVersion);
  168. downloadUrl += "&arch=" + network::encodeUrl(arch);
  169. if (dryRun) {
  170. // Check if available
  171. json_t *availableResJ = network::requestJson(network::METHOD_GET, downloadUrl, NULL);
  172. if (!availableResJ) {
  173. WARN("Could not check whether download is available");
  174. return false;
  175. }
  176. DEFER({
  177. json_decref(availableResJ);
  178. });
  179. json_t *successJ = json_object_get(availableResJ, "success");
  180. return json_boolean_value(successJ);
  181. }
  182. else {
  183. downloadName = name;
  184. downloadProgress = 0.0;
  185. INFO("Downloading plugin %s %s %s", slug.c_str(), latestVersion.c_str(), arch.c_str());
  186. // Download zip
  187. std::string pluginDest = asset::user("plugins/" + slug + ".zip");
  188. if (!network::requestDownload(downloadUrl, pluginDest, &downloadProgress)) {
  189. WARN("Plugin %s download was unsuccessful", slug.c_str());
  190. return false;
  191. }
  192. downloadName = "";
  193. return true;
  194. }
  195. }
  196. static void loadPlugins(std::string path) {
  197. std::string message;
  198. for (std::string pluginPath : system::listEntries(path)) {
  199. if (!system::isDirectory(pluginPath))
  200. continue;
  201. if (!loadPlugin(pluginPath)) {
  202. message += string::f("Could not load plugin %s\n", pluginPath.c_str());
  203. }
  204. }
  205. if (!message.empty()) {
  206. message += "See log for details.";
  207. osdialog_message(OSDIALOG_WARNING, OSDIALOG_OK, message.c_str());
  208. }
  209. }
  210. /** Returns 0 if successful */
  211. static int extractZipHandle(zip_t *za, const char *dir) {
  212. int err;
  213. for (int i = 0; i < zip_get_num_entries(za, 0); i++) {
  214. zip_stat_t zs;
  215. err = zip_stat_index(za, i, 0, &zs);
  216. if (err) {
  217. WARN("zip_stat_index() failed: error %d", err);
  218. return err;
  219. }
  220. int nameLen = strlen(zs.name);
  221. char path[MAXPATHLEN];
  222. snprintf(path, sizeof(path), "%s/%s", dir, zs.name);
  223. if (zs.name[nameLen - 1] == '/') {
  224. if (mkdir(path, 0755)) {
  225. if (errno != EEXIST) {
  226. WARN("mkdir(%s) failed: error %d", path, errno);
  227. return errno;
  228. }
  229. }
  230. }
  231. else {
  232. zip_file_t *zf = zip_fopen_index(za, i, 0);
  233. if (!zf) {
  234. WARN("zip_fopen_index() failed");
  235. return -1;
  236. }
  237. FILE *outFile = fopen(path, "wb");
  238. if (!outFile)
  239. continue;
  240. while (1) {
  241. char buffer[1<<15];
  242. int len = zip_fread(zf, buffer, sizeof(buffer));
  243. if (len <= 0)
  244. break;
  245. fwrite(buffer, 1, len, outFile);
  246. }
  247. err = zip_fclose(zf);
  248. if (err) {
  249. WARN("zip_fclose() failed: error %d", err);
  250. return err;
  251. }
  252. fclose(outFile);
  253. }
  254. }
  255. return 0;
  256. }
  257. /** Returns 0 if successful */
  258. static int extractZip(const char *filename, const char *path) {
  259. int err;
  260. zip_t *za = zip_open(filename, 0, &err);
  261. if (!za) {
  262. WARN("Could not open zip %s: error %d", filename, err);
  263. return err;
  264. }
  265. DEFER({
  266. zip_close(za);
  267. });
  268. err = extractZipHandle(za, path);
  269. return err;
  270. }
  271. static void extractPackages(std::string path) {
  272. std::string message;
  273. for (std::string packagePath : system::listEntries(path)) {
  274. if (string::extension(packagePath) != "zip")
  275. continue;
  276. INFO("Extracting package %s", packagePath.c_str());
  277. // Extract package
  278. if (extractZip(packagePath.c_str(), path.c_str())) {
  279. WARN("Package %s failed to extract", packagePath.c_str());
  280. message += string::f("Could not extract package %s\n", packagePath.c_str());
  281. continue;
  282. }
  283. // Remove package
  284. if (remove(packagePath.c_str())) {
  285. WARN("Could not delete file %s: error %d", packagePath.c_str(), errno);
  286. }
  287. }
  288. if (!message.empty()) {
  289. osdialog_message(OSDIALOG_WARNING, OSDIALOG_OK, message.c_str());
  290. }
  291. }
  292. ////////////////////
  293. // public API
  294. ////////////////////
  295. void init(bool devMode) {
  296. // Load core
  297. // This function is defined in core.cpp
  298. Plugin *corePlugin = new Plugin;
  299. ::init(corePlugin);
  300. plugins.push_back(corePlugin);
  301. // Get user plugins directory
  302. std::string userPlugins = asset::user("plugins");
  303. mkdir(userPlugins.c_str(), 0755);
  304. // Copy Fundamental package to plugins directory if folder does not exist
  305. std::string fundamentalSrc = asset::system("Fundamental.zip");
  306. std::string fundamentalDest = asset::user("plugins/Fundamental.zip");
  307. std::string fundamentalDir = asset::user("plugins/Fundamental");
  308. if (system::isFile(fundamentalSrc) && !system::isFile(fundamentalDest) && !system::isDirectory(fundamentalDir)) {
  309. system::copyFile(fundamentalSrc, fundamentalDest);
  310. }
  311. // Extract packages and load plugins
  312. extractPackages(userPlugins);
  313. loadPlugins(userPlugins);
  314. }
  315. void destroy() {
  316. for (Plugin *plugin : plugins) {
  317. // Free library handle
  318. #if defined ARCH_WIN
  319. if (plugin->handle)
  320. FreeLibrary((HINSTANCE) plugin->handle);
  321. #else
  322. if (plugin->handle)
  323. dlclose(plugin->handle);
  324. #endif
  325. // For some reason this segfaults.
  326. // It might be best to let them leak anyway, because "crash on exit" issues would occur with badly-written plugins.
  327. // delete plugin;
  328. }
  329. plugins.clear();
  330. }
  331. void logIn(std::string email, std::string password) {
  332. json_t *reqJ = json_object();
  333. json_object_set(reqJ, "email", json_string(email.c_str()));
  334. json_object_set(reqJ, "password", json_string(password.c_str()));
  335. std::string tokenUrl = app::API_URL;
  336. tokenUrl += "/token";
  337. json_t *resJ = network::requestJson(network::METHOD_POST, tokenUrl, reqJ);
  338. json_decref(reqJ);
  339. if (resJ) {
  340. json_t *errorJ = json_object_get(resJ, "error");
  341. if (errorJ) {
  342. const char *errorStr = json_string_value(errorJ);
  343. loginStatus = errorStr;
  344. }
  345. else {
  346. json_t *tokenJ = json_object_get(resJ, "token");
  347. if (tokenJ) {
  348. const char *tokenStr = json_string_value(tokenJ);
  349. settings.token = tokenStr;
  350. loginStatus = "";
  351. }
  352. }
  353. json_decref(resJ);
  354. }
  355. }
  356. void logOut() {
  357. settings.token = "";
  358. }
  359. bool sync(bool dryRun) {
  360. if (settings.token.empty())
  361. return false;
  362. bool available = false;
  363. if (!dryRun) {
  364. isDownloading = true;
  365. downloadProgress = 0.0;
  366. downloadName = "Updating plugins...";
  367. }
  368. DEFER({
  369. isDownloading = false;
  370. });
  371. // Get user's plugins list
  372. json_t *pluginsReqJ = json_object();
  373. json_object_set(pluginsReqJ, "token", json_string(settings.token.c_str()));
  374. std::string pluginsUrl = app::API_URL;
  375. pluginsUrl += "/plugins";
  376. json_t *pluginsResJ = network::requestJson(network::METHOD_GET, pluginsUrl, pluginsReqJ);
  377. json_decref(pluginsReqJ);
  378. if (!pluginsResJ) {
  379. WARN("Request for user's plugins failed");
  380. return false;
  381. }
  382. DEFER({
  383. json_decref(pluginsResJ);
  384. });
  385. json_t *errorJ = json_object_get(pluginsResJ, "error");
  386. if (errorJ) {
  387. WARN("Request for user's plugins returned an error: %s", json_string_value(errorJ));
  388. return false;
  389. }
  390. // Get community manifests
  391. std::string manifestsUrl = app::API_URL;
  392. manifestsUrl += "/community/manifests";
  393. json_t *manifestsResJ = network::requestJson(network::METHOD_GET, manifestsUrl, NULL);
  394. if (!manifestsResJ) {
  395. WARN("Request for community manifests failed");
  396. return false;
  397. }
  398. DEFER({
  399. json_decref(manifestsResJ);
  400. });
  401. // Check each plugin in list of plugin slugs
  402. json_t *pluginsJ = json_object_get(pluginsResJ, "plugins");
  403. if (!pluginsJ) {
  404. WARN("No plugins array");
  405. return false;
  406. }
  407. json_t *manifestsJ = json_object_get(manifestsResJ, "manifests");
  408. if (!manifestsJ) {
  409. WARN("No manifests object");
  410. return false;
  411. }
  412. size_t slugIndex;
  413. json_t *slugJ;
  414. json_array_foreach(pluginsJ, slugIndex, slugJ) {
  415. std::string slug = json_string_value(slugJ);
  416. // Search for slug in manifests
  417. const char *manifestSlug;
  418. json_t *manifestJ = NULL;
  419. json_object_foreach(manifestsJ, manifestSlug, manifestJ) {
  420. if (slug == std::string(manifestSlug))
  421. break;
  422. }
  423. if (!manifestJ)
  424. continue;
  425. if (syncPlugin(slug, manifestJ, dryRun)) {
  426. available = true;
  427. }
  428. }
  429. return available;
  430. }
  431. void cancelDownload() {
  432. // TODO
  433. }
  434. bool isLoggedIn() {
  435. return settings.token != "";
  436. }
  437. Plugin *getPlugin(std::string pluginSlug) {
  438. for (Plugin *plugin : plugins) {
  439. if (plugin->slug == pluginSlug) {
  440. return plugin;
  441. }
  442. }
  443. return NULL;
  444. }
  445. Model *getModel(std::string pluginSlug, std::string modelSlug) {
  446. Plugin *plugin = getPlugin(pluginSlug);
  447. if (!plugin)
  448. return NULL;
  449. Model *model = plugin->getModel(modelSlug);
  450. if (!model)
  451. return NULL;
  452. return model;
  453. }
  454. /** List of allowed tags in human display form.
  455. All tags here should be in sentence caps for display consistency.
  456. However, tags are case-insensitive in plugin metadata.
  457. */
  458. const std::vector<std::string> allowedTags = {
  459. "Arpeggiator",
  460. "Attenuator", // With a level knob and not much else.
  461. "Blank", // No parameters or ports. Serves no purpose except visual.
  462. "Chorus",
  463. "Clock generator",
  464. "Clock modulator", // Clock dividers, multipliers, etc.
  465. "Compressor", // With threshold, ratio, knee, etc parameters.
  466. "Controller", // Use only if the artist "performs" with this module. Simply having knobs is not enough. Examples: on-screen keyboard, XY pad.
  467. "Delay",
  468. "Digital",
  469. "Distortion",
  470. "Drum",
  471. "Dual", // The core functionality times two. If multiple channels are a requirement for the module to exist (ring modulator, mixer, etc), it is not a Dual module.
  472. "Dynamics",
  473. "Effect",
  474. "Envelope follower",
  475. "Envelope generator",
  476. "Equalizer",
  477. "External",
  478. "Flanger",
  479. "Function generator",
  480. "Granular",
  481. "LFO",
  482. "Limiter",
  483. "Logic",
  484. "Low pass gate",
  485. "MIDI",
  486. "Mixer",
  487. "Multiple",
  488. "Noise",
  489. "Panning",
  490. "Phaser",
  491. "Physical modeling",
  492. "Polyphonic",
  493. "Quad", // The core functionality times four. If multiple channels are a requirement for the module to exist (ring modulator, mixer, etc), it is not a Quad module.
  494. "Quantizer",
  495. "Random",
  496. "Recording",
  497. "Reverb",
  498. "Ring modulator",
  499. "Sample and hold",
  500. "Sampler",
  501. "Sequencer",
  502. "Slew limiter",
  503. "Switch",
  504. "Synth voice", // A synth voice must have, at the minimum, a built-in oscillator and envelope.
  505. "Tuner",
  506. "Utility", // Serves only extremely basic functions, like inverting, max, min, multiplying by 2, etc.
  507. "VCA",
  508. "VCF",
  509. "VCO",
  510. "Visual",
  511. "Vocoder",
  512. "Waveshaper",
  513. };
  514. /** List of common synonyms for allowed tags.
  515. Aliases and tags must be lowercase.
  516. */
  517. const std::map<std::string, std::string> tagAliases = {
  518. {"amplifier", "vca"},
  519. {"clock", "clock generator"},
  520. {"drums", "drum"},
  521. {"eq", "equalizer"},
  522. {"filter", "vcf"},
  523. {"low frequency oscillator", "lfo"},
  524. {"lowpass gate", "low pass gate"},
  525. {"oscillator", "vco"},
  526. {"percussion", "drum"},
  527. {"poly", "polyphonic"},
  528. {"s&h", "sample and hold"},
  529. {"voltage controlled amplifier", "vca"},
  530. {"voltage controlled filter", "vcf"},
  531. {"voltage controlled oscillator", "vco"},
  532. };
  533. std::string getAllowedTag(std::string tag) {
  534. tag = string::lowercase(tag);
  535. // Transform aliases
  536. auto it = tagAliases.find(tag);
  537. if (it != tagAliases.end())
  538. tag = it->second;
  539. // Find allowed tag
  540. for (std::string allowedTag : allowedTags) {
  541. if (tag == string::lowercase(allowedTag))
  542. return allowedTag;
  543. }
  544. return "";
  545. }
  546. bool isSlugValid(std::string slug) {
  547. for (char c : slug) {
  548. if (!(std::isalnum(c) || c == '-' || c == '_'))
  549. return false;
  550. }
  551. return true;
  552. }
  553. std::list<Plugin*> plugins;
  554. bool isDownloading = false;
  555. float downloadProgress = 0.f;
  556. std::string downloadName;
  557. std::string loginStatus;
  558. } // namespace plugin
  559. } // namespace rack