瀏覽代碼

Merge branch 'feature/pr51'

Ka1-S 1 月之前
父節點
當前提交
ba1b9e08e1
共有 5 個文件被更改,包括 296 次插入 和 51 次删除
  1. 100 0
      src/Main.cpp
  2. 66 47
      src/core/MissingFiles.cpp
  3. 2 2
      src/core/MissingFiles.h
  4. 87 2
      src/engine/SessionPack.cpp
  5. 41 0
      tests/tests.cpp

+ 100 - 0
src/Main.cpp

@@ -30,6 +30,7 @@
 #include "engine/PluginHost.h"
 #include "engine/PluginSandbox.h"
 #include "engine/ProjectFile.h"
+#include "core/Sha256.h"
 #include "engine/SessionPack.h"
 #include "core/SessionIds.h"
 #include "core/SessionParts.h"
@@ -2015,6 +2016,105 @@ private:
                               && host.channels[(std::size_t) hitChannel].name == "Hit";
                 }
             }
+            // a crafted package whose project points at a file elsewhere on this computer: opening it must not
+            // reach that file, or merging would copy it into the project and the next package would send it on
+            if (mergeOk)
+            {
+                const auto secret = dir.getChildFile ("secret.wav");
+                wav.copyFileTo (secret);
+                auto evil = lynx::Song::makeDefault();
+                lynx::ChannelDef c;
+                c.instrument = lynx::InstrumentKind::sampler;
+                c.samplePath = secret.getFullPathName().toStdString();
+                evil.channels.push_back (c);
+                lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
+                keys.instrument = lynx::InstrumentKind::flkeys;
+                keys.zones.push_back ({});
+                keys.zones.back().path = c.samplePath;
+                evil.channels.push_back (keys);
+                lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
+                patch.instrument = lynx::InstrumentKind::patcher;
+                patch.patcher.nodes.resize (2);
+                patch.patcher.nodes[0].generator = true;
+                patch.patcher.nodes[0].channel = c;
+                patch.patcher.nodes[1].effect.samplePath = c.samplePath;
+                evil.channels.push_back (patch);
+                evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
+                const auto evilProject = dir.getChildFile ("evil.lynx");
+                lynx::sessionpack::Manifest em;
+                em.part = true;
+                juce::ZipFile::Builder b;
+                const auto json = lynx::sessionpack::manifestToJson (em);
+                b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
+                const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
+                bool zipped = false;
+                if (lynx::ProjectFile::save (evil, evilProject, e))
+                {
+                    b.addFile (evilProject, 0, "project.lynx");
+                    juce::FileOutputStream out (evilPack);
+                    zipped = out.openedOk() && b.writeToStream (out, nullptr);
+                }
+                auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
+                const auto media = dir.getChildFile ("Session media/Evil");
+                mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
+                          && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
+                                 return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
+                                        || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
+                             })
+                          && evilOpened->song.channels.back().patcher.nodes.size() == 2
+                          && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
+                          && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
+                          && evilOpened->song.mixer[1].recordTo.empty()
+                          && media.findChildFiles (juce::File::findFiles, true).isEmpty();
+                if (! mergeOk && e.isEmpty())
+                    e = "a received package reached a file outside it";
+            }
+            // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
+            // media entry outside the package (it must not even be read: "/dev/zero" would never end)
+            if (mergeOk)
+            {
+                const auto secret = dir.getChildFile ("secret.wav");
+                const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
+                const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
+                const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
+                auto evil = lynx::Song::makeDefault();
+                for (const auto& path : { climb, dotted })
+                {
+                    lynx::ChannelDef c;
+                    c.instrument = lynx::InstrumentKind::sampler;
+                    c.samplePath = path.toStdString();
+                    evil.channels.push_back (c);
+                }
+                juce::MemoryBlock secretBytes;
+                secret.loadFileAsData (secretBytes);
+                lynx::sessionpack::Manifest em;
+                em.part = true;
+                em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
+                                      "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
+                const auto evilProject = dir.getChildFile ("evil2.lynx");
+                juce::ZipFile::Builder b;
+                const auto json = lynx::sessionpack::manifestToJson (em);
+                b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
+                const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
+                bool zipped = false;
+                if (lynx::ProjectFile::save (evil, evilProject, e))
+                {
+                    b.addFile (evilProject, 0, "project.lynx");
+                    juce::FileOutputStream out (evilPack);
+                    zipped = out.openedOk() && b.writeToStream (out, nullptr);
+                }
+                auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
+                const auto media = dir.getChildFile ("Session media/Evil2");
+                mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
+                          && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
+                          && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
+                                 const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
+                                 return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
+                             })
+                          && media.findChildFiles (juce::File::findFiles, true).isEmpty();
+                if (! mergeOk && e.isEmpty())
+                    e = "a received package climbed out of its folder";
+            }
             if (! packOk && e.isEmpty())
                 e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
                     + written.missing.joinIntoString (";");

+ 66 - 47
src/core/MissingFiles.cpp

@@ -54,14 +54,69 @@ bool usesChannelSample (InstrumentKind kind)
            || kind == InstrumentKind::threeosc || kind == InstrumentKind::soundfont;
 }
 
-template <typename Fn>
-void forEachEffectSlot (std::vector<EffectSlot>& chain, Fn&& fn)
+// Every user sample of a channel / an effect slot, also inside parallel branches and Patcher graphs (any depth):
+// fn (path, user). Templates so one walk serves `const Song&` (finding) and `Song&` (relinking).
+template <typename Doc, typename Fn>
+void docSamples (Doc& doc, const std::string& user, Fn& fn);
+
+// "Rack (Patcher)" once, however deep the Patcher
+std::string inPatcher (const std::string& user)
+{
+    const std::string tag = " (Patcher)";
+    return user.size() >= tag.size() && user.compare (user.size() - tag.size(), tag.size(), tag) == 0 ? user : user + tag;
+}
+
+template <typename Slot, typename Fn>
+void slotSamples (Slot& slot, const std::string& user, Fn& fn)
+{
+    fn (slot.samplePath, user + ": effect");
+    for (auto& branch : slot.branches)
+        for (auto& child : branch.chain)
+            slotSamples (child, user, fn);
+    docSamples (slot.patcher, inPatcher (user), fn);
+}
+
+template <typename Channel, typename Fn>
+void channelSamples (Channel& c, const std::string& user, Fn& fn)
+{
+    if (usesChannelSample (c.instrument))
+        fn (c.samplePath, user.empty() ? channelUser (c) : user);
+    if (c.instrument != InstrumentKind::flkeys)
+        for (auto& z : c.zones)
+            fn (z.path, user.empty() ? c.name : user);
+    for (auto& s : c.standIns) // Online Sessions' renders (round 168a)
+        fn (s.path, (user.empty() ? c.name : user) + ": stand-in");
+    docSamples (c.patcher, inPatcher (user.empty() ? c.name : user), fn);
+}
+
+template <typename Doc, typename Fn>
+void docSamples (Doc& doc, const std::string& user, Fn& fn)
+{
+    for (auto& n : doc.nodes)
+    {
+        if (n.generator)
+            channelSamples (n.channel, user, fn);
+        else
+            slotSamples (n.effect, user, fn);
+        for (auto& h : n.busHeads)
+            if (h.head)
+                slotSamples (*h.head, user, fn);
+    }
+}
+
+template <typename SongT, typename Fn>
+void forEachSample (SongT& song, Fn&& fn)
 {
-    for (auto& slot : chain)
+    for (auto& c : song.channels)
+        channelSamples (c, {}, fn);
+    for (std::size_t t = 0; t < song.mixer.size(); ++t)
     {
-        fn (slot);
-        for (auto& branch : slot.branches)
-            forEachEffectSlot (branch.chain, fn);
+        auto& track = song.mixer[t];
+        for (auto& s : track.standIns)
+            fn (s.path, (track.name.empty() ? "Insert " + std::to_string (t) : track.name) + ": stand-in");
+        const auto name = track.name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : track.name;
+        for (auto& slot : track.effects)
+            slotSamples (slot, name, fn);
     }
 }
 } // namespace
@@ -108,31 +163,10 @@ std::vector<MissingFile> findMissingSamples (const Song& song, const std::functi
         return known[key] = ! fileExists (path);
     };
 
-    for (const auto& c : song.channels)
-    {
-        if (usesChannelSample (c.instrument) && gone (c.samplePath))
-            addMissingFile (list, c.samplePath, channelUser (c));
-        if (c.instrument != InstrumentKind::flkeys)
-            for (const auto& z : c.zones)
-                if (gone (z.path))
-                    addMissingFile (list, z.path, c.name);
-        for (const auto& s : c.standIns) // Online Sessions' renders (round 168a)
-            if (gone (s.path))
-                addMissingFile (list, s.path, c.name + ": stand-in");
-    }
-
-    for (std::size_t t = 0; t < song.mixer.size(); ++t)
-    {
-        for (const auto& s : song.mixer[t].standIns)
-            if (gone (s.path))
-                addMissingFile (list, s.path, (song.mixer[t].name.empty() ? "Insert " + std::to_string (t) : song.mixer[t].name) + ": stand-in");
-        auto chain = song.mixer[t].effects; // (a copy: the walker takes non-const slots)
-        const auto track = song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name;
-        forEachEffectSlot (chain, [&] (EffectSlot& slot) {
-            if (gone (slot.samplePath))
-                addMissingFile (list, slot.samplePath, track + ": effect");
-        });
-    }
+    forEachSample (song, [&] (const std::string& path, const std::string& user) {
+        if (gone (path))
+            addMissingFile (list, path, user);
+    });
     return list;
 }
 
@@ -253,22 +287,7 @@ int applyRelocations (Song& song, const std::map<std::string, std::string>& relo
         }
     };
 
-    for (auto& c : song.channels)
-    {
-        if (usesChannelSample (c.instrument))
-            relocate (c.samplePath);
-        if (c.instrument != InstrumentKind::flkeys)
-            for (auto& z : c.zones)
-                relocate (z.path);
-        for (auto& s : c.standIns)
-            relocate (s.path);
-    }
-    for (auto& track : song.mixer)
-    {
-        forEachEffectSlot (track.effects, [&] (EffectSlot& slot) { relocate (slot.samplePath); });
-        for (auto& s : track.standIns)
-            relocate (s.path);
-    }
+    forEachSample (song, [&] (std::string& path, const std::string&) { relocate (path); });
     return changed;
 }
 

+ 2 - 2
src/core/MissingFiles.h

@@ -40,7 +40,7 @@ void addMissingFile (std::vector<MissingFile>& list, const std::string& path, co
 
 // The user samples a .lynx song references that `fileExists` says are gone: channel samples (sampler, audio clip,
 // Granulizer, 3x Osc custom wave), sampler zones (not FL Keys' installation wavetables) and effect samples
-// (Newtone/Newtime). FL Studio installation data some engines keep in samplePath (DLLs, wave folders) is left out.
+// (Newtone/Newtime), also inside parallel containers and Patcher graphs. FL Studio installation data some engines keep in samplePath (DLLs, wave folders) is left out.
 std::vector<MissingFile> findMissingSamples (const Song& song, const std::function<bool (const std::string&)>& fileExists);
 
 // How well a found file matches a missing path: 0 = different file name; otherwise 1 + the number of trailing folder
@@ -65,7 +65,7 @@ std::map<std::string, std::string> relocationMap (const std::vector<MissingFile>
 std::string relocatedPath (const std::map<std::string, std::string>& relocations, const std::string& path);
 
 // Points every reference to a relocated file at its new place (channel samples, zones, effect samples, also inside
-// parallel containers); a channel whose sampler had lost its sample keeps its kind. Returns how many references changed.
+// parallel containers and Patcher graphs); a channel whose sampler had lost its sample keeps its kind. Returns how many references changed.
 int applyRelocations (Song& song, const std::map<std::string, std::string>& relocations);
 
 // The search folders list as saved (one folder per line): duplicates and empty lines dropped, order kept.

+ 87 - 2
src/engine/SessionPack.cpp

@@ -11,6 +11,7 @@
 #include "core/SessionIds.h"
 #include "core/Sha256.h"
 #include "core/StandIns.h"
+#include "engine/AudioEngine.h"
 #include "engine/Exporter.h"
 #include "engine/ProjectFile.h"
 #include "platform/Paths.h"
@@ -180,6 +181,20 @@ juce::File fileOf (const std::string& path)
 }
 
 bool samePath (const juce::File& a, const juce::File& b) { return a.getFullPathName().equalsIgnoreCase (b.getFullPathName()); }
+
+// `path` (absolute) names a file inside `root`. No "..", and no folder named only with dots and spaces either:
+// Windows drops a name's trailing dots and spaces, so ". ." or "... " can climb like "..". Compared as text (case
+// as the file system: JUCE's File ==), so a path spelled any other way than the folder (another Unicode form, an
+// 8.3 short name, \\?\ prefix) counts as outside: a missing file, never a file elsewhere.
+bool insideFolder (const std::string& path, const juce::File& root)
+{
+    if (root == juce::File() || path.empty())
+        return false;
+    for (const auto& part : juce::StringArray::fromTokens (str (path), "/\\", ""))
+        if (part.isNotEmpty() && part.trimCharactersAtEnd (". ").isEmpty())
+            return false;
+    return fileOf (path).isAChildOf (root);
+}
 } // namespace
 
 juce::String manifestToJson (const Manifest& m)
@@ -628,6 +643,12 @@ std::optional<Opened> open (const juce::File& file, const juce::File& destinatio
         error = "the package has no project";
         return std::nullopt;
     }
+    for (int i = 0; i < zip.getNumEntries(); ++i)
+        if (zip.getEntry (i)->isSymbolicLink) // (JUCE would create it, and copying "media" through it reads any file here)
+        {
+            error = "the package contains a link";
+            return std::nullopt;
+        }
     destinationRoot.createDirectory();
     const auto folder = destinationRoot.getNonexistentChildFile (juce::File::createLegalFileName (file.getFileNameWithoutExtension()), {}, false);
     if (! folder.createDirectory())
@@ -652,13 +673,77 @@ std::optional<Opened> open (const juce::File& file, const juce::File& destinatio
         opened.project = named;
     for (const auto& m : manifest->media)
     {
-        const auto f = folder.getChildFile (m.entry);
-        if (! f.existsAsFile() || "sha256-" + hashFile (f) != m.id)
+        const auto f = folder.getChildFile (m.entry); // (the manifest is the sender's too: "../" or "/dev/zero" is never read)
+        if (! insideFolder (utf8 (f.getFullPathName()), folder) || ! f.existsAsFile() || "sha256-" + hashFile (f) != m.id)
             opened.corrupt.add (m.name);
     }
     auto song = ProjectFile::load (opened.project, error);
     if (! song)
         return std::nullopt;
+    // a received project may only use its own media: a path anywhere else on this computer would be copied
+    // into the project and sent on with the next package. It becomes a missing file under its own name.
+    auto within = [] (const std::string& path, const juce::File& root) { return insideFolder (path, root); };
+    auto missing = [&] (const std::string& path) {
+        const auto p = str (path);
+        const auto name = juce::File::createLegalFileName (p.fromLastOccurrenceOf ("/", false, false).fromLastOccurrenceOf ("\\", false, false));
+        return utf8 (folder.getChildFile ("missing").getChildFile (name).getFullPathName());
+    };
+    std::map<std::string, std::string> outside;
+    for (const auto& path : safety::referencedSamples (*song))
+        if (! within (path, folder))
+            outside[path] = missing (path);
+    applyRelocations (*song, outside);
+    // every other path the engine reads, also inside Patcher graphs (not in the media list, never packed): only the
+    // package or FL Studio's own files (FL Keys' wavetables, the engines' DLLs)
+    const auto flInstall = findFlStudioRoots().factoryData;
+    const auto fl = flInstall.empty() ? juce::File() : juce::File (str (flInstall));
+    auto engineOnly = [&] (std::string& path) {
+        if (! path.empty() && ! within (path, folder) && ! within (path, fl))
+            path = missing (path);
+    };
+    std::function<void (EffectSlot&)> slot;
+    std::function<void (PatcherDoc&)> doc;
+    std::function<void (ChannelDef&)> channel;
+    slot = [&] (EffectSlot& s) {
+        engineOnly (s.samplePath);
+        for (auto& b : s.branches)
+            for (auto& child : b.chain)
+                slot (child);
+        doc (s.patcher);
+    };
+    doc = [&] (PatcherDoc& d) {
+        for (auto& n : d.nodes)
+        {
+            if (n.generator)
+                channel (n.channel);
+            else
+                slot (n.effect);
+            for (auto& h : n.busHeads)
+                if (h.head)
+                    slot (*h.head);
+        }
+    };
+    channel = [&] (ChannelDef& c) {
+        engineOnly (c.samplePath);
+        for (auto& z : c.zones)
+            engineOnly (z.path);
+        for (auto& s : c.standIns)
+            engineOnly (s.path);
+        doc (c.patcher);
+    };
+    for (auto& c : song->channels)
+        channel (c);
+    for (auto& t : song->mixer)
+    {
+        for (auto& s : t.effects)
+            slot (s);
+        for (auto& s : t.standIns)
+            engineOnly (s.path);
+        // a file the insert records and renders to: written, so only inside the package (else the automatic name)
+        if (! t.recordTo.empty() && ! within (t.recordTo, folder))
+            t.recordTo.clear();
+    }
+    song->dataFolder.clear(); // the sender's folder: nothing to do with this computer
     opened.song = std::move (*song);
     return opened;
 }

+ 41 - 0
tests/tests.cpp

@@ -15416,6 +15416,47 @@ TEST (missing_files_find_in_song)
     CHECK (lynx::applyRelocations (copy, { { "C:\\gone\\tune.wav", "/t.wav" } }) == 1 && copy.mixer[2].effects[0].branches[0].chain[0].samplePath == "/t.wav");
 }
 
+TEST (missing_files_inside_patcher)
+{
+    // a Patcher's instruments and effects (any depth) are the song's samples too: listed, packed and relinked
+    lynx::Song song;
+    lynx::ChannelDef inner;
+    inner.name = "Pad", inner.instrument = lynx::InstrumentKind::sampler, inner.samplePath = "C:\\gone\\pad.wav";
+    lynx::ChannelDef nested;
+    nested.instrument = lynx::InstrumentKind::patcher;
+    nested.patcher.nodes.resize (1);
+    nested.patcher.nodes[0].generator = true;
+    nested.patcher.nodes[0].channel = inner;
+    lynx::ChannelDef patch;
+    patch.name = "Rack", patch.instrument = lynx::InstrumentKind::patcher;
+    patch.patcher.nodes.resize (2);
+    patch.patcher.nodes[0].generator = true;
+    patch.patcher.nodes[0].channel = nested;
+    patch.patcher.nodes[1].effect.samplePath = "C:\\gone\\tune.wav";
+    patch.patcher.nodes[1].busHeads.push_back ({});
+    patch.patcher.nodes[1].busHeads[0].head = lynx::EffectSlot();
+    patch.patcher.nodes[1].busHeads[0].head->samplePath = "C:\\gone\\tune.wav"; // same file: one entry
+    song.channels = { patch };
+    song.mixer.resize (2);
+    lynx::EffectSlot fxPatcher;
+    fxPatcher.patcher.nodes.resize (1);
+    fxPatcher.patcher.nodes[0].generator = true;
+    fxPatcher.patcher.nodes[0].channel = inner;
+    fxPatcher.patcher.nodes[0].channel.samplePath = "C:\\gone\\hit.wav";
+    song.mixer[1].effects.push_back (fxPatcher);
+
+    const auto missing = lynx::findMissingSamples (song, [] (const std::string&) { return false; });
+    CHECK (missing.size() == 3);
+    CHECK (missing.size() == 3 && missing[0].path == "C:\\gone\\pad.wav" && missing[0].usedBy[0] == "Rack (Patcher)");
+    CHECK (missing.size() == 3 && missing[1].path == "C:\\gone\\tune.wav" && missing[1].usedBy[0] == "Rack (Patcher): effect");
+    CHECK (missing.size() == 3 && missing[2].path == "C:\\gone\\hit.wav" && missing[2].usedBy[0] == "Insert 1 (Patcher)");
+    CHECK (lynx::applyRelocations (song, { { "C:\\gone\\pad.wav", "/p.wav" }, { "C:\\gone\\tune.wav", "/t.wav" }, { "C:\\gone\\hit.wav", "/h.wav" } }) == 4);
+    CHECK (song.channels[0].patcher.nodes[1].busHeads[0].head->samplePath == "/t.wav");
+    CHECK (song.channels[0].patcher.nodes[0].channel.patcher.nodes[0].channel.samplePath == "/p.wav");
+    CHECK (song.channels[0].patcher.nodes[1].effect.samplePath == "/t.wav");
+    CHECK (song.mixer[1].effects[0].patcher.nodes[0].channel.samplePath == "/h.wav");
+}
+
 TEST (missing_files_folder_search)
 {
     namespace fs = std::filesystem;