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.

663 lines
17KB

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