Repository navigation
discord: fetch distros at build time - #507728
Conversation
This comment has been minimized.
This comment has been minimized.
|
As talked about here: #507728 (comment) I couldn't figure out a way to make the proprietary rust cli discord ships to download a specific version of discord, so I think best approach might be to just bootstrap it ourselves If anyone else could figure out how to bend the CLI to behave feel free to let me know, but from what I saw it isn't really possible I'm leaving 0e6d04f as separate commit for easier review (previous commit f4c3856) - but if we can't find better solution, I'll squash this one |
This comment has been minimized.
This comment has been minimized.
|
did some reverse engineering on the tl;drthere is no way to make the bootstrapping ourselves (fetching directly from the CDN) is the only viable path here reverse engineering methodologygrabbed the tarball, extracted the binary, ran it through ghidra headless (ghidra auto-applied setup (reproducible with nix-shell)# download the tarball
mkdir -p ~/discord-re && cd ~/discord-re
curl -sL -o discord-dev.tar.gz \
"https://development.dl2.discordapp.net/apps/linux/0.0.239/discord-development-0.0.239.tar.gz"
tar xzf discord-dev.tar.gz
# verify we have the right thing
file DiscordDevelopment/updater_bootstrap
# ELF 64-bit LSB pie executable, x86-64, stripped
# quick string analysis
nix-shell -p binutils --run \
'strings DiscordDevelopment/updater_bootstrap | grep -iE "(manifest|version|update|channel|pinned|install|query)" | sort -u'ghidra headless analysismkdir -p ~/discord-re/ghidra_project ~/discord-re/ghidra_scripts
# step 1: import + auto-analysis (ghidra applies rust-common types automatically)
nix-shell -p ghidra --run \
"ghidra-analyzeHeadless ~/discord-re/ghidra_project discord_updater \
-import ~/discord-re/DiscordDevelopment/updater_bootstrap -overwrite"
# step 2: run analysis scripts (see below)
nix-shell -p ghidra --run \
"ghidra-analyzeHeadless ~/discord-re/ghidra_project discord_updater \
-process updater_bootstrap -noanalysis \
-scriptPath ~/discord-re/ghidra_scripts \
-postScript AnalyzeUpdater.java"AnalyzeUpdater.java (ghidra script - finds key string xrefs and decompiles referencing functions)// Analyze Discord updater_bootstrap - find key string xrefs and decompile
// @category Analysis
import ghidra.app.script.GhidraScript;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.*;
import ghidra.program.model.address.*;
import ghidra.program.model.mem.*;
import ghidra.app.decompiler.*;
import java.io.*;
import java.util.*;
public class AnalyzeUpdater extends GhidraScript {
PrintWriter out;
DecompInterface decomp;
@Override
public void run() throws Exception {
out = new PrintWriter(new FileWriter(System.getProperty("user.home") + "/discord-re/analysis_output.txt"));
Program program = currentProgram;
Listing listing = program.getListing();
FunctionManager funcMgr = program.getFunctionManager();
ReferenceManager refMgr = program.getReferenceManager();
decomp = new DecompInterface();
decomp.openProgram(program);
decomp.setOptions(new DecompileOptions());
w("Total functions: " + funcMgr.getFunctionCount());
// search memory for critical strings and trace back to functions
Memory mem = program.getMemory();
String[] patterns = {
"/manifests/latest", "update_to_latest", "installer.db",
"updater-client-worker", "failed to spawn updater thread",
"invalid updater configuration", "Discord-Updater/1",
"release_channel", "query_update_plan", "query_current_version",
"pinned_update", "host_updates", "required_update",
"distributions/", "set_manifests", "collect_garbage",
"Blocked: Transition flag", "Mismatch between last update",
"delta_manifest.json"
};
Set<String> funcAddrs = new LinkedHashSet<>();
for (String pattern : patterns) {
byte[] bytes = pattern.getBytes("UTF-8");
Address found = mem.findBytes(mem.getMinAddress(), bytes, null, true, monitor);
while (found != null) {
ReferenceIterator refs = refMgr.getReferencesTo(found);
while (refs.hasNext()) {
Reference ref = refs.next();
Function func = funcMgr.getFunctionContaining(ref.getFromAddress());
if (func != null) {
String addr = func.getEntryPoint().toString();
w("'" + pattern + "' @ " + found + " -> " + func.getName() + " @ " + addr);
funcAddrs.add(addr);
}
}
found = mem.findBytes(found.add(1), bytes, null, true, monitor);
}
}
// decompile all discovered functions + their callers
Set<String> decompiled = new HashSet<>();
for (String addr : funcAddrs) {
decompFunc(funcMgr, addr, decompiled);
}
for (String addr : new ArrayList<>(funcAddrs)) {
try {
Function func = funcMgr.getFunctionAt(
currentProgram.getAddressFactory().getAddress(addr));
if (func != null) {
for (Function caller : func.getCallingFunctions(monitor)) {
decompFunc(funcMgr, caller.getEntryPoint().toString(), decompiled);
}
}
} catch (Exception e) {}
}
out.flush();
out.close();
decomp.dispose();
}
private void decompFunc(FunctionManager funcMgr, String addrStr, Set<String> done) {
if (done.contains(addrStr)) return;
done.add(addrStr);
try {
Address addr = currentProgram.getAddressFactory().getAddress(addrStr);
Function func = funcMgr.getFunctionAt(addr);
if (func == null) func = funcMgr.getFunctionContaining(addr);
if (func != null) {
DecompileResults r = decomp.decompileFunction(func, 120, monitor);
if (r != null && r.decompileCompleted() && r.getDecompiledFunction() != null) {
String code = r.getDecompiledFunction().getC();
if (code != null) {
w("\n--- " + func.getName() + " @ " + func.getEntryPoint() + " ---");
w(code.length() > 15000 ? code.substring(0, 15000) + "\n[truncated]" : code);
}
}
}
} catch (Exception e) {
w("[error decompiling " + addrStr + ": " + e.getMessage() + "]");
}
}
private void w(String s) { out.println(s); println(s); }
}what the binary actually isit's a stripped Rust ELF (4.13 MB) built from Discord's internal dependencies (from crate paths in the binary): how it worksthe shell wrapper ( $BOOTSTRAP $CONFIG_HOME/$DIR $DOWNLOAD $CHANNEL $CONFIG_HOME/$DIR
# e.g.: updater_bootstrap ~/.config/discorddevelopment https://updates.discord.com/ development ~/.config/discorddevelopmentthere's no argument parsing library (no clap, structopt, getopts), it's just raw positional args internally it spawns a why
|
|
Great work! In that case our only option is probably FHSenv or (!)an wrapper that has a bunch of libraries in LD_LIBRARY_PATH. |
@Scrumplex What about 0e6d04f ? We can just boostrap ourselves, Discord has only just just moved away what we need to a different end point and added annoying cli in the way that we can entirely bypass, if in the future they improve their CLI to be able to do versioning then we can switch back to it |
winterqt
left a comment
There was a problem hiding this comment.
Tiny nits that you may or may not care about
0e6d04f to
d3d5ced
Compare
|
@winterqt Thanks a lot for the review Some updates on what has happened since: Canary moved to the distro layout too, since I opened this PR, canary jumped from 0.0.946 straight to 1.0.927 and is now on the same distro format as development Added canary to Dropped the hardcoded module list new manifest ships 12 modules on both canary and development (adds New runtime deps for canary/dev native modules, the bundled .node files want: libssl.so.1.1 / libcrypto.so.1.1 -> openssl_1_1 Added both to One annoying thing: This is upstream Discord shipping native modules linked against openssl 1.1, not something I can really fix here, open to ideas if anyone has a cleaner approach |
updater_bootstrap tarball, bump all channels|
not sure if related but openasar recently added some stuff relating to 2 options We already modify discord settings.json by default to block updates. If these are useful we can extend it further to also mess with those. |
|
Not really related and out of the scope of this PR imo |
Scrumplex
left a comment
There was a problem hiding this comment.
Excellent work and investigation. I think this is a good way to go for now. Most of my comments are closer to nits than actual issues, but I do think that most of them will make this more maintainable in the future.
1e2617e to
ad39f92
Compare
|
@Scrumplex Thanks a lot for your kinds words and the review You can more easily see the diff here: https://github.com/NixOS/nixpkgs/compare/d3d5ced49bf0bbe57aadee2bebb7237ea002e6e5..1e2617e1a9530bfbe29228c4e1c6e1e8cfd8a6af The only remaining concern is:
From: #507728 (comment) If anyone has any ideas on a better approach please let me know Other than that, I think everything else is done |
ad39f92 to
fa784b1
Compare
Infinidoge
left a comment
There was a problem hiding this comment.
Why must Discord be such frustrating software...
Need to bypass the package itself to pin version, need to use OpenSSL, what nonsense will they throw next.
Great work with your analysis and thank you for figuring this out!
Code looks good, packages build (grumble at needing to compile OpenSSL) and run on our machine.
I will relish the day we can leave this Titan-forsaken platform.
|
I wonder if SKIP_HOST_UPDATE will keep working after the new updater reforms... |
2ce831f to
2a1c2ef
Compare
|
It has already trickled down to PTB, so I think we should try to get this PR over the line sooner rather than later Once this reaches stable, nixpkgs will lag behind Discord’s current Linux packaging format, and that will prob cause breakage for Vencord, Equicord, and other 3rd party mods I think a reasonable short-term compromise is to let the affected Discord variants (soon stable probably) become "insecure packages", that is technically true now, since the shipped native modules depend on OpenSSL 1.1, and it keeps the warning visible This would buy us more time to decide whether that is acceptable long-term. My preference is still not to keep it that way forever, even if it is technically accurate
@dtomvan It should still work in the future
const SKIP_HOST_UPDATE = 'SKIP_HOST_UPDATE';
skipHostUpdate = settings?.get(SKIP_HOST_UPDATE) || !hostUpdatable;On the the "distro" variants |
`discord-development` linux tarball changed layout in 0.0.235, `discord-canary` followed in 1.0.927, and `discord-ptb` followed in 1.0.188 Instead of bundling the channel binary directly, these channels now ship only a small `updater_bootstrap` ELF that downloads the real app into `$XDG_CONFIG_HOME/<channel>/app-<version>/` on first run That bootstrap always hits `/manifests/latest` with no way to pin a version, which would make the build impure and the nix version a lie Reverse engineering the Rust ELF confirmed there is no CLI flag, env var, or config to override this First seen downstream in FlameFlag/nixcord workflow run 24025186671 Fetch the brotli-compressed `.distro` tars directly from the distributions API at build time instead `update.py` resolves the latest version via `updates.discord.com/distributions/app/manifests/latest?channel=<ch>` and pins the host + all module URLs with SHA256s into `sources.json` `installPhase` detects the distro layout via `isDistro`, brotli-decodes the host tar into `$out/opt/<binaryName>`, and extracts each module under `$out/opt/<binaryName>/modules/<name>/`. `autoPatchelfHook` handles the binary and native `.node` modules as usual Discord's JS `moduleUpdater` looks for modules under `<host_dir>/<version>/modules/<name>/` A `stageModules` wrapper symlinks them from the nix store on first launch and pre-writes `installed.json` so the updater treats them as already installed, otherwise the first launch crashes with `Cannot find module 'discord_desktop_core'` The bundled native modules link against openssl 1.1 and libpulseaudio, added both to `buildInputs` gated on `isDistro` so the legacy stable package is unaffected
2a1c2ef to
c153f6b
Compare
|
|
Backport failed for Please cherry-pick the changes locally and resolve any conflicts. git fetch origin release-25.11
git worktree add -d .worktree/backport-507728-to-release-25.11 origin/release-25.11
cd .worktree/backport-507728-to-release-25.11
git switch --create backport-507728-to-release-25.11
git cherry-pick -x c153f6b738fe45d2850db8575c4205537cf4c958 |
The package depends on OpenSSL 1.1 now, which causes issues. See NixOS/nixpkgs#507728 (comment).
|
Hey everyone, coral from discord here. Yes, we are moving to a bootstrap updater flow as the #1 feature request we got from users on Linux has been " PLEASE MAKE UPDATING AUTOMATIC ". I realize this breaks some of the NixOS flows but we are going to keep respecting the Our goal is to align with how Steam ships updates, as our JS code often depends on new native code. That didn't use to be a problem as we frankly haven't done much on Linux over the past years but that's changing as we've spent effort on improving the Linux client lately. You can run the One thing I take away from this thread is that you all want to be able to give It's hard for us to keep an eye on all the distros but if you ever find something that seems odd/malicious just email me at [email protected] . |
|
Heya coral, thank you for taking that into account and for letting us know! Hopefully the pinned version comes around as that would theoretically make this work well. For anyone who comes across this PR with regards to the OpenSSL 1.1 issue, coral responded to this in #513122. TLDR, old module unused on Linux that should be removed soon, so we should be able to drop OpenSSL 1.1 when that happens |
|
Backport failed for Please cherry-pick the changes locally and resolve any conflicts. git fetch origin release-25.11
git worktree add -d .worktree/backport-507728-to-release-25.11 origin/release-25.11
cd .worktree/backport-507728-to-release-25.11
git switch --create backport-507728-to-release-25.11
git cherry-pick -x c153f6b738fe45d2850db8575c4205537cf4c958 |
discord-developmentlinux tarball changed layout in 0.0.235Instead of bundling
DiscordDevelopmentdirectly, it now ships onlya small
updater_bootstrapELF that downloads the real channel into$XDG_CONFIG_HOME/discorddevelopment/app-<version>/on first runThe old install phase blindly chmod'd the channel binary and broke as
soon as 0.0.235 hit
(First seen downstream in https://github.com/FlameFlag/nixcord/actions/runs/24025186671/job/70062037830#step:8:689 the previous runs earlier still built 0.0.234 normally)
Darwin not affected (yet?)
Things done
passthru.tests.nixpkgs-reviewon this PR. See nixpkgs-review usage../result/bin/.