Skip to content

Implement pl_env_vars option for library/playlist/cache relocation - #1085

Merged
flyingmutant merged 3 commits into
cmus:masterfrom
pgaskin:pl-env
Jul 15, 2023
Merged

flyingmutant merged 3 commits into
cmus:masterfrom
pgaskin:pl-env

Conversation

@pgaskin

@pgaskin pgaskin commented Jun 2, 2021 •

Copy link
Copy Markdown
Member

See pl_env.h for more details.

closes #834
closes #245

Comment thread pl_env.c Resolved
Comment thread Doc/cmus.txt Resolved
Comment thread pl_env.h Resolved
@tonyfischetti

Copy link
Copy Markdown

Tested this PR—works great for me! No problems!

@pgaskin
pgaskin force-pushed the pl-env branch 4 times, most recently from 99bf2a0 to 46cdbe9 Compare June 4, 2021 13:34
@pgaskin
pgaskin marked this pull request as draft June 4, 2021 14:47
@nefthy

nefthy commented Jun 4, 2021

Copy link
Copy Markdown
Collaborator

The code is high quality and nicely documented. I'm however unsure if the whole concept of substituting environment variables is something we should persu. Sorry for not explaining in the coresponding issue.

@pgaskin pgaskin left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested:

  • :save/:load.
  • Launching and exiting cmus multiple times.
    • Ensuring the library remains consistent.
    • Ensuring the cache doesn't grow unexpectedly (due to filenames being mishandled or not handled everywhere).
    • Ensuring the play count is preserved.
    • Ensuring the cache is always in sync with the library.
    • Ensuring performance and memory usage is consistent.
  • Moving files and setting the environment variable to the new path.
  • Switching between pl_env_vars values, ensuring the paths are updated properly,
    • while cmus is running.
    • while cmus is stopped.
  • :add.
  • Normal cmus usage.

With:

  • pl_env_vars=.
  • pl_env_vars=HOME, pl_env_vars= HOME .
  • pl_env_vars=TEST,HOME with some files in $TEST, and with $TEST unset/set/invalid/empty (ensuring tracks are preserved while TEST is unset, empty, or invalid), and with $TEST having unnecessary ./, /, and ../s.
  • pl_env_vars=TEST , TEST1 , HOME with various combinations of files including some having a directory starting with $TEST but not within $TEST (e.g. TEST=/test with a filename starting with `/testtest).

I've also been using this PR (and my original patch which preceded it) for the last while to allow me to use a common cmus config dir synced between my computers, WSL, and Termux on my phone without needing to use bind mounts or proot.

Note that when an environment variable is not set, it'll display as <1f>VARIABLE<1f> due to cmus' utf8 handling, but I'm not yet comfortable enough with the text processing code to make it support the invisible ASCII delimiters yet. This isn't going to show up unless the user has a configuration problem, and if they do then it'll be pretty obvious what it is since they would have had to set pl_env_vars in the first place and the error when playing the track explains it, so I think it's OK to leave it this way for now.

@pgaskin
pgaskin marked this pull request as ready for review June 4, 2021 15:27
@pgaskin
pgaskin force-pushed the pl-env branch 2 times, most recently from f0f0230 to 05424c0 Compare June 4, 2021 15:30
@pgaskin

pgaskin commented Jun 4, 2021 •

Copy link
Copy Markdown
Member Author

I'm however unsure if the whole concept of substituting environment variables is something we should persue

I originally thought the same thing, but ended up changing my mind after going through the different options and resolving the remaining inconsistencies I found with the patch I wrote in #834 (comment). In particular:

  • I wanted to ensure this wouldn't have any effect or risk of regressions on users who don't use this option. The only thing this implementation adds to the default code path is a fast-failing check for if paths starts with \x1F (see pl_env_var). The second commit in this PR preprocesses the environment variables for performance reasons, but that commit can be reverted if necessary to limit the risk of regressions. I did fuzz the path normalization implementation to ensure it wouldn't ever crash (and I used indexes rather than pointer trickery to make it less error-prone to write and understand), though, so I'm confident in its safety.
  • I wanted to minimize the risk of losing the library/playlist contents if the user made a configuration mistake with pl_env_vars enabled. To do this, I added the special case to cache_get_ti to preserve the tracks if an environment variable is missing.
  • I wanted to ensure this option does not affect the expected behaviour of cmus. As explained in lib_pl.h, unlike alternative implementations, this implementation is identical whether the pl_env_vars is enabled to both cmus itself (since all processing is done when saving/loading the state) and to users.
  • I wanted this option to be self-contained to keep it maintainable. To do this, I moved all of the path processing into pl_env.{c,h} and documented how it affects other parts of cmus. In practice, this means that only 4 lines are changed in the rest of cmus to process the paths if required, another two lines are added to give better error messages, and one line is added for the optimized version.

Did you have a specific concern?


Also, one note about merging this: I'd prefer if this is merged with a merge commit or a rebase rather than a squash commit to keep the initial implementation and the optimized version separate.

@tonyfischetti

Copy link
Copy Markdown

@nefthy Just one person's opinion: I think it's super worthwhile to pursue this. I think it's a feature that a lot of people would like. For example, I have all my playlists version controlled. It's fine for my home gnu/linux machines but at work I have a mac and my home is /Users/tony. Before I could solve it with a symlink but now /home (and other things) are unwrite-able, even with root.

And it looks like the work is already done and works great/great documentation

@nefthy

nefthy commented Jun 4, 2021

Copy link
Copy Markdown
Collaborator

@pgaskin I'd summirize my reservations as follows:

  • It's a niche use case.
  • Pulling stuff out of the environment und doing string stuff always bares risk of security issues (especialy in C).
  • It does not feel like the way cmus does stuff.

That said, I'm ok with merging.

@pgaskin

pgaskin commented Jun 5, 2021 •

Copy link
Copy Markdown
Member Author

It's a niche use case.

On the other hand, most applications can follow the home directory around. I do admit it's somewhat niche though, but that's true for quite a few of cmus' features.

Pulling stuff out of the environment und doing string stuff always bares risk of security issues

While I agree with that statement in general, especially if this was server software or multi-year, I don't think it's relevant for cmus. A user with access to cmus, it's socket, or its config dir can already access everything it has access to via load, save, and commands like that, or even just modifying the cache/config. A more relevant point related to this would be the risk for regressions due to stability issues in the string manipulation code, and I was concerned with that too, hence the extensive testing I did on the side with the env var path simplification, the comments, and how I implemented it such that barely any of the code would run for non-users of the option.

In addition, I used allocated strings rather than shared buffers. Related to your third point, is somewhat un-cmus-like, but is a lot safer. Remember how many issues with memory safety, undefined behavior, and segmentation faults have been found in cmus' existing UI and string manipulation code.

And about consistency for the rest of cmus, I specifically limited substitution to the first absolute match for path prefixes only to prevent this from breaking assumptions about files in the cache.

It does not feel like the way cmus does stuff.

But, I'd say this implementation feels like the most cmus-like way to do things out of the different options I could think of (fake bind-mount implementation, arbitrary environment substitution, automatically attempting to search for files, hooking file loads themselves, etc). Plus, I'd argue this feature itself is cmus-like since it's a shell application, and most shell applications use environment variables rather than depending on fixed paths and support data synchronization using dotfile managers.

That said, I'm ok with merging

If you don't mind, can you quickly skim the documentation to ensure it makes sense to someone who didn't implement this feature?


Also, @flyingmutant, do you have an opinion on this (feature or implementation of it)?

@pgaskin
pgaskin force-pushed the pl-env branch 2 times, most recently from f45d709 to 5f6c91b Compare June 5, 2021 03:31
@flyingmutant

Copy link
Copy Markdown
Member

Also, @flyingmutant, do you have an opinion on this (feature or implementation of it)?

I think both feature and implementation approach are sensible. It is certainly a niche feature, but so is the whole concept of a console music player :-) I did not have time to review the code properly yet, but I see a lot of thought and polish has went into this PR.

@pgaskin

pgaskin commented Jun 7, 2021

Copy link
Copy Markdown
Member Author

a lot of thought and polish

Yes. I didn't want to risk introducing regressions with this, so I took a bit of time to properly understand and test this, and I took the most hands-off approach possible.

I did a few final optimizations with my last force-push. I've also tested this with Valgrind and ASAN. I think this PR is complete now unless you want any changes to the documentation or want any changes to the implementation.

I'm currently running and using this daily with 3 env vars on Termux (aarch64), Debian (in WSL), and Fedora (x86). The only thing I haven't tested is the Windows compatibility (I haven't got around to getting cmus to build in mingw-w64), but it should work fine and won't cause issues if it doesn't.

Comment thread cache.c Resolved
Comment thread options.c Resolved
Comment thread options.c Resolved
Comment thread job.c Resolved

@gavtroy gavtroy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall it looks reasonable. The use case isn't relevant to me and I'm not planning to test it.

Comment thread pl_env.c Resolved
Comment thread pl_env.c Resolved
Comment thread pl_env.c Resolved
Comment thread pl_env.c Resolved
Comment thread player.c Resolved
Comment thread Doc/cmus.txt Resolved
Comment thread Doc/cmus.txt Resolved
Comment thread cache.c Resolved
Comment thread pl_env.c Resolved
Comment thread pl_env.h Resolved
@pgaskin
pgaskin marked this pull request as draft July 17, 2021 22:17
@pgaskin

pgaskin commented Jul 13, 2023

Copy link
Copy Markdown
Member Author

Rebased.

@pgaskin
pgaskin force-pushed the pl-env branch 2 times, most recently from 7ddd468 to 0df3cbe Compare July 13, 2023 13:35
@pgaskin

pgaskin commented Jul 13, 2023 •

Copy link
Copy Markdown
Member Author

Addressed review comments @flyingmutant:

Details
diff --git a/Doc/cmus.txt b/Doc/cmus.txt
index 16f45c3..adb3c96 100644
--- a/Doc/cmus.txt
+++ b/Doc/cmus.txt
@@ -1700,7 +1700,8 @@ usually are. If the file is in the cache, it will be preserved, and an error
 will be displayed upon playback. If the file is not in the cache, it will be
 removed from playlists and the library. There is one special exception: if a
 file is missing due to the environment variable being invalid/empty/unset, but
-it is still in the cache, it will be preserved as-is.
+it is still in the cache, it will be preserved in the cache as-is, in addition
+to being preserved in the library like usual.
 
 When using `:save`/`:load` and in the on-disk library/cache/playlists, the paths
 will be stored with the environment variable delimited using the character
diff --git a/cache.c b/cache.c
index d2602dc..f02c501 100644
--- a/cache.c
+++ b/cache.c
@@ -129,11 +129,11 @@ static struct track_info *cache_entry_to_ti(struct cache_entry *e)
        struct keyval *kv;
        int str_size = e->size - sizeof(*e);
        int pos, i, count;
-       char *proc_fn;
+       char *proc_filename;
 
-       if (pl_env_var(strings, NULL) && (proc_fn = pl_env_restore(strings))) {
-               ti = track_info_new(proc_fn);
-               free(proc_fn);
+       if (pl_env_var(strings, NULL) && (proc_filename = pl_env_expand(strings))) {
+               ti = track_info_new(proc_filename);
+               free(proc_filename);
        } else {
                ti = track_info_new(strings);
        }
@@ -327,7 +327,7 @@ static void flush_buffer(int fd, struct gbuf *buf)
 
 static void write_ti(int fd, struct gbuf *buf, struct track_info *ti, unsigned int *offsetp)
 {
-       char *proc_fn = pl_env_save(ti->filename);
+       char *proc_filename = pl_env_reduce(ti->filename);
        const struct keyval *kv = ti->comments;
        unsigned int offset = *offsetp;
        unsigned int pad;
@@ -344,7 +344,7 @@ static void write_ti(int fd, struct gbuf *buf, struct track_info *ti, unsigned i
        e.mtime = ti->mtime;
        e.play_count = ti->play_count;
        e.bpm = ti->bpm;
-       len[count] = strlen(proc_fn) + 1;
+       len[count] = strlen(proc_filename) + 1;
        e.size += len[count++];
        len[count] = (ti->codec ? strlen(ti->codec) : 0) + 1;
        e.size += len[count++];
@@ -369,7 +369,7 @@ static void write_ti(int fd, struct gbuf *buf, struct track_info *ti, unsigned i
        if (pad)
                gbuf_set(buf, 0, pad);
        gbuf_add_bytes(buf, &e, sizeof(e));
-       gbuf_add_bytes(buf, proc_fn, len[count++]);
+       gbuf_add_bytes(buf, proc_filename, len[count++]);
        gbuf_add_bytes(buf, ti->codec ? ti->codec : "", len[count++]);
        gbuf_add_bytes(buf, ti->codec_profile ? ti->codec_profile : "", len[count++]);
        for (i = 0; kv[i].key; i++) {
@@ -380,7 +380,7 @@ static void write_ti(int fd, struct gbuf *buf, struct track_info *ti, unsigned i
        free(len);
        *offsetp = offset + pad + e.size;
 
-       free(proc_fn);
+       free(proc_filename);
 }
 
 int cache_close(void)
diff --git a/cmus.c b/cmus.c
index 88963d2..2b5ccf6 100644
--- a/cmus.c
+++ b/cmus.c
@@ -232,13 +232,13 @@ static int save_ext_playlist_cb(void *data, struct track_info *ti)
 
 static int save_playlist_cb(void *data, struct track_info *ti)
 {
-       char *proc_fn = pl_env_save(ti->filename);
+       char *proc_filename = pl_env_reduce(ti->filename);
        int fd = *(int *)data;
        const char nl = '\n';
        int rc;
 
-       rc = write_all(fd, proc_fn, strlen(proc_fn));
-       free(proc_fn);
+       rc = write_all(fd, proc_filename, strlen(proc_filename));
+       free(proc_filename);
        if (rc == -1)
                return -1;
 
diff --git a/job.c b/job.c
index 75ac3de..4560702 100644
--- a/job.c
+++ b/job.c
@@ -353,7 +353,7 @@ static int handle_line(void *data, const char *line)
                add_url(line);
        } else {
                char *absolute = pl_env_var(line, NULL)
-                       ? pl_env_restore(line)
+                       ? pl_env_expand(line)
                        : path_absolute_cwd(line, data);
                add_file(absolute, 0);
                free(absolute);
diff --git a/options.c b/options.c
index d9aa1c1..a87bb1b 100644
--- a/options.c
+++ b/options.c
@@ -520,12 +520,12 @@ static void get_pl_env_vars(void *data, char *buf, size_t size)
        for (char **x = pl_env_vars; *x; x++) {
                if (x != pl_env_vars) {
                        if (!--r)
-                               return;
+                               return; /* overflow */
                        *p++ = ',';
                }
                size_t l = strlen(*x);
                if (!(r -= l))
-                       return;
+                       return; /* overflow */
                strcpy(p, *x);
                p += l;
        }
@@ -543,9 +543,11 @@ static void set_pl_env_vars(void *data, const char *buf)
                pl_env_vars = NULL;
        }
        size_t n = 1;
-       for (const char *x = buf; *x; x++)
-               if (*x == ',')
+       for (const char *x = buf; *x; x++) {
+               if (*x == ',') {
                        n++;
+               }
+       }
        char **a = pl_env_vars = xnew(char*, n+1);
        for (char *x = *a++ = xstrdup(buf); *x; x++) {
                if (*x == ',') {
diff --git a/pl_env.c b/pl_env.c
index 5310f86..c89fc14 100644
--- a/pl_env.c
+++ b/pl_env.c
@@ -1,5 +1,5 @@
 /*
- * Copyright 2021 Patrick Gaskin
+ * Copyright 2021-2023 Patrick Gaskin
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License as
@@ -34,19 +34,21 @@ static bool pl_env_contains_delimiter(const char *str)
 }
 
 /**
- * pl_env_norm normalizes the provided path into the required format for
- * pl_env_save and pl_env_restore, which does exact string matching/replacement.
- * It converts backslashes to slashes on Windows, removes consecutive slashes,
- * removes './' path segments, simplifies '../' path segments (and returns NULL
- * if it would result in going above the uppermost directory), and removes the
- * trailing slash.
+ * pl_env_norm gets an env var and puts it into the required format for
+ * pl_env_reduce and pl_env_expand, which does exact string matching/replacement
+ * against the file paths. It converts backslashes to slashes on Windows,
+ * removes consecutive slashes, removes './' path segments, simplifies '../'
+ * path segments (and returns NULL if it would result in going above the
+ * uppermost directory), and removes the trailing slash. In addition, it trims
+ * the variable name before looking it up.
  */
 static char *pl_env_norm(char *path)
 {
 #ifdef _WIN32
        /* convert backslashes to slashes */
        /* note: cmus uses forward slashes internally, but Windows accepts both */
-       for (char *p = new; *p; p++)
+       /* even though they will get normalized on windows, we need paths to match exactly */
+       for (char *p = path; *p; p++)
                *p = *p == '\\' ? '/' : *p;
 #endif
 
@@ -159,7 +161,7 @@ void pl_env_init(void)
        *new = NULL;
 }
 
-char *pl_env_save(const char *path)
+char *pl_env_reduce(const char *path)
 {
        if (!pl_env_vars || !*pl_env_vars || pl_env_var(path, NULL))
                return xstrdup(path);
@@ -206,7 +208,7 @@ char *pl_env_save(const char *path)
        return xstrdup(path);
 }
 
-char *pl_env_restore(const char *path)
+char *pl_env_expand(const char *path)
 {
        if (!path)
                return NULL;
diff --git a/pl_env.h b/pl_env.h
index 0dba0fb..d287808 100644
--- a/pl_env.h
+++ b/pl_env.h
@@ -89,7 +89,7 @@
  *      to be an (old-fashioned) invisible delimiter, which makes sense for our
  *      purposes.
  *   3. Since it is invisible, we don't need to deal with everywhere it might be
- *      printed to the UI if it is not substituted by pl_env_restore (i.e. if
+ *      printed to the UI if it is not substituted by pl_env_expand (i.e. if
  *      the env var is missing or invalid).
  *
  * - Why not remove the substitution if the env var is missing or invalid?
@@ -178,23 +178,23 @@
 void pl_env_init(void);
 
 /**
- * pl_env_save checks the base path against the configured environment
+ * pl_env_reduce checks the base path against the configured environment
  * variables, replaces the first match with a substitution, and returns a
  * malloc'd copy of the result. If there isn't any valid match or the path
  * already contains a substitution, a copy of the original path is returned
  * as-is.
  */
-char *pl_env_save(const char *path);
+char *pl_env_reduce(const char *path);
 
 /**
- * pl_env_restore returns a malloc'd copy of path, with the environment variable
+ * pl_env_expand returns a malloc'd copy of path, with the environment variable
  * substitution. The provided path must use forward slashes, and begin with a
  * slash or a substitution followed by a slash (which will always be true for
  * library paths within cmus). If the path does not have a substitution, the
  * original path is returned. If the environment variable does not exist or is
  * invalid, the original path is also returned.
  */
-char *pl_env_restore(const char *path);
+char *pl_env_expand(const char *path);
 
 /**
  * pl_env_var returns a pointer to the start of the substituted environment

@pgaskin
pgaskin marked this pull request as ready for review July 13, 2023 13:40
@pgaskin
pgaskin requested a review from flyingmutant July 13, 2023 13:40

@pgaskin pgaskin left a comment •

Copy link
Copy Markdown
Member Author

@pgaskin

pgaskin commented Jul 13, 2023

Copy link
Copy Markdown
Member Author

@flyingmutant, ready for a final review, then a rebase (not a squash -- I'd prefer to keep the history on this one) merge, then probably a release.

@gavtroy gavtroy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed again, it's still fine. My only reservation is what we've already covered: that the use case is niche, and that it's hard to discover even if you do need it. I do wonder if it would have been better only to support HOME through a more discoverable option like "cross_platform_home" or "lib_relative_to_home" or whatever. Anyway I'm still fine with merging the current solution.

I ended up also briefly testing it to understand it better, and it seemed to work well for me.

@flyingmutant
flyingmutant merged commit 1c3c25c into cmus:master Jul 15, 2023
@flyingmutant

Copy link
Copy Markdown
Member

@pgaskin thanks for the code, @gavtroy thanks for the review! I do agree about the approach being hacky, but it is clever, self-contained and solves a real problem for people. I think the documentation does a good job explaining the feature, so it should be relatively discoverable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Relative paths in lib.pl and playlist.pl relative paths for playlist (pls) files?

5 participants