Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/source-lints.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ on:
branches: [main]
paths:
- "src/**/*.rs"
- "src/runtime/cli/install.sh"
- "src/**/*.h"
- "src/**/*.cpp"
- "src/**/*.classes.ts"
Expand All @@ -37,6 +38,7 @@ on:
pull_request:
paths:
- "src/**/*.rs"
- "src/runtime/cli/install.sh"
- "src/**/*.h"
- "src/**/*.cpp"
- "src/**/*.classes.ts"
Expand Down
2 changes: 1 addition & 1 deletion docs/installation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Bun ships as a single, dependency-free executable. Install it with the install s

</CodeGroup>
<Note>
**Linux users:** You need the `unzip` package to install Bun (`sudo apt install unzip`). We recommend kernel version 5.6 or higher. Bun runs on kernels as old as 3.10 (RHEL 7) with graceful degradation of newer syscalls. Use `uname -r` to check your kernel version.
**Linux users:** The install script needs `curl` or `wget`, and `unzip` (`sudo apt install unzip`). If `unzip` is missing, it also accepts `busybox`, `7z`, `bsdtar`, or `python3`. We recommend kernel version 5.6 or higher. Bun runs on kernels as old as 3.10 (RHEL 7) with graceful degradation of newer syscalls. Use `uname -r` to check your kernel version.
</Note>

</Tab>
Expand Down
53 changes: 47 additions & 6 deletions src/runtime/cli/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,27 @@ success() {
echo -e "${Green}$@ ${Color_Off}"
}

command -v unzip >/dev/null ||
error 'unzip is required to install bun'
if command -v curl >/dev/null; then
download_cmd=curl
elif command -v wget >/dev/null; then
download_cmd=wget
else
error 'curl or wget is required to install bun'
fi

unzip_cmd=''
for cmd in unzip busybox 7z 7zz 7za bsdtar python3; do
command -v "$cmd" >/dev/null || continue
# A busybox build can leave out the unzip applet.
if [[ $cmd = busybox ]] && ! busybox --list 2>/dev/null | grep -x unzip >/dev/null; then
continue
fi
unzip_cmd=$cmd
break
done
Comment thread
robobun marked this conversation as resolved.
Resolved

[[ $unzip_cmd ]] ||
error 'unzip is required to install bun (7z, busybox, bsdtar, python3 supported)'

if [[ $# -gt 2 ]]; then
error 'Too many arguments, only 2 are allowed. The first can be a specific tag of bun to install. (e.g. "bun-v0.1.4") The second can be a build variant of bun to install. (e.g. "debug-info")'
Expand Down Expand Up @@ -146,11 +165,33 @@ if [[ ! -d $bin_dir ]]; then
error "Failed to create install directory \"$bin_dir\""
fi

curl --fail --location --progress-bar --output "$exe.zip" "$bun_uri" ||
error "Failed to download bun from \"$bun_uri\""
case $download_cmd in
curl)
curl --fail --location --progress-bar --output "$exe.zip" "$bun_uri"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 nit (optional): users installing with the new wget fallback are left with an empty ~/.bun/bin/bun.zip whenever the download fails, which the curl path does not leave. wget -O at install.sh:170 creates the output file before the request, so a 404 (mistyped tag) or a network error still leaves a zero-byte $exe.zip in $bin_dir, and the error at install.sh:172 exits without removing it. Fix: on download failure remove the partial $exe.zip for both downloaders (e.g. esac || { rm -f "$exe.zip"; error ...; }), or download to a temp name and move it into place only on success.

Extended reasoning...

install.sh:56-62 picks wget when curl is absent. install.sh:170 runs wget -q -O "$exe.zip" "$bun_uri". GNU wget opens the -O target for writing before it sends the request, so the file exists even when the server answers 404 or the connection fails. wget then exits 8 (or 4), the case at…

Verification: nit. Trigger: host without curl but with GNU wget (install.sh:56-62 selects download_cmd=wget), and the download fails (404 from a mistyped tag, DNS/connection error). Mechanism: install.sh:173 runs wget -q -O "$exe.zip" "$bun_uri"; GNU wget's documented -O semantics are shell-redirection-like ("file will be truncated immediately, and all downloaded content will be written there"),…

;;
wget)
wget -q -O "$exe.zip" "$bun_uri"
;;
esac || error "Failed to download bun from \"$bun_uri\""

unzip -oqd "$bin_dir" "$exe.zip" ||
error 'Failed to extract bun'
# python3's zipfile does not restore the file mode; the chmod below covers it.
case $unzip_cmd in
unzip)
unzip -oqd "$bin_dir" "$exe.zip"
;;
busybox)
busybox unzip -oq "$exe.zip" -d "$bin_dir"
;;
7z | 7zz | 7za)
"$unzip_cmd" x -y -o"$bin_dir" "$exe.zip" >/dev/null
;;
bsdtar)
bsdtar --no-same-owner -xf "$exe.zip" -C "$bin_dir"
;;
python3)
python3 -m zipfile -e "$exe.zip" "$bin_dir"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 nit (optional) (security hardening): on hosts that fall back to python3, the installer now imports Python modules from whatever directory the user happens to run it in. install.sh:192 runs python3 -m zipfile, and -m puts the current directory first on sys.path, so a zipfile.py or a shadowing stdlib name such as types.py in the cwd runs with the user's privileges. Fix: run the interpreter isolated (python3 -I -m zipfile ..., available since Python 3.4) so neither the cwd nor PYTHONPATH/user site-packages can substitute modules; the bun upgrade row in upgrade_command.rs:118-122 runs from a private staging dir so it only needs the same flag for consistency.

Extended reasoning...

The base branch never spawns python3. This PR makes python3 -m zipfile -e "$exe.zip" "$bin_dir" the extractor on hosts without unzip, busybox, 7z or bsdtar (the PR names Fedora/Ubuntu/Debian minimal images as the common case). Python's -m handling is documented as 'the current directory will be added to the start of sys.path'. curl -fsSL https://bun.sh/install | bash is run from an arbitrary cwd, often a freshly cloned project. runpy then resolves zipfile and everything it imports (types, enum, shutil, struct, threading, importlib.util are not preloaded at interpreter start) against the cwd before the stdlib, so a same-named .py file in that directory executes. Cloning a repository does not otherwise run its contents; running the installer inside it now does, on python3-fallback hosts only. PYTHONPATH and PYTHONSTARTUP are inherited as well. -I disables the cwd entry, env-var overrides and user site-packages in one flag. bun upgrade (upgrade_command.rs:118-122, spawned with cwd = the 0o700 staging dir created at :829) is not exposed through the cwd, so the fix is needed at…

Verification: nit (security hardening, narrow trigger) — triggers when a host has none of unzip/busybox-with-unzip/7z/7zz/7za/bsdtar but has python3, and the user runs curl … | bash from a directory containing a zipfile.py/zipfile/ package or a shadow of a non-frozen stdlib module that zipfile imports (e.g. shutil.py, struct.py). Mechanism verified: the new extractor arm in…

;;
esac || error 'Failed to extract bun'

mv "$bin_dir/bun-$target/$exe_name" "$exe" ||
error 'Failed to move extracted bun to destination'
Expand Down
126 changes: 113 additions & 13 deletions src/runtime/cli/upgrade_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,96 @@ fn argv_contains(target: &[u8]) -> bool {
bun_core::argv().iter().any(|a| a == target)
}

/// A program that can extract the release zip on POSIX into the current
/// directory. `before` and `after` are the arguments around the archive path.
Comment on lines +66 to +67

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

#[cfg(unix)]
struct UnzipProgram {
bin: &'static [u8],
before: &'static [&'static [u8]],
after: &'static [&'static [u8]],
}

/// Probe order. Must match the `for cmd in ...` loop in `install.sh`.
/// The vendored libarchive has no zip reader, so an external program extracts it.
Comment on lines +77 to +78

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

#[cfg(unix)]
const UNZIP_PROGRAMS: &[UnzipProgram] = &[
UnzipProgram {
bin: b"unzip",
before: &[b"-q", b"-o"],
after: &[],
},
UnzipProgram {
bin: b"busybox",
before: &[b"unzip", b"-q", b"-o"],
after: &[],
},
UnzipProgram {
bin: b"7z",
before: &[b"x", b"-y"],
after: &[],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
UnzipProgram {
bin: b"7zz",
before: &[b"x", b"-y"],
after: &[],
},
UnzipProgram {
bin: b"7za",
before: &[b"x", b"-y"],
after: &[],
},
UnzipProgram {
bin: b"bsdtar",
before: &[b"--no-same-owner", b"-xf"],
after: &[],
},
UnzipProgram {
bin: b"python3",
before: &[b"-m", b"zipfile", b"-e"],
after: &[b"."],
},
];

/// A busybox build can leave out the unzip applet. `busybox --list` prints one
/// applet name per line.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(unix)]
fn busybox_has_unzip(busybox: &[u8]) -> bool {
let argv: [&[u8]; 2] = [busybox, b"--list"];
let Ok(Ok(result)) = spawn_sync::spawn(&spawn_sync::Options {
argv: build_argv(&argv),
envp: None,
stdin: spawn_sync::SyncStdio::Ignore,
stdout: spawn_sync::SyncStdio::Buffer,
stderr: spawn_sync::SyncStdio::Ignore,
..Default::default()
}) else {
return false;
};
result.status.is_ok()
&& strings::split(result.stdout.as_slice(), b"\n").any(|line| line == b"unzip")
}

/// Returns the argv of the first entry of `UNZIP_PROGRAMS` found in `path`.
#[cfg(unix)]
fn find_unzip_argv(path: &[u8], cwd: &[u8], archive: &[u8]) -> Option<Vec<Box<[u8]>>> {
let mut buf = bun_paths::path_buffer_pool::get();
for program in UNZIP_PROGRAMS {
let Some(exe) = which(&mut buf, path, cwd, program.bin) else {
continue;
};
if program.bin == b"busybox" && !busybox_has_unzip(exe.as_bytes()) {
continue;
}
let mut argv = Vec::with_capacity(program.before.len() + program.after.len() + 2);
argv.push(Box::<[u8]>::from(exe.as_bytes()));
argv.extend(program.before.iter().map(|a| Box::<[u8]>::from(*a)));
argv.push(Box::<[u8]>::from(archive));
argv.extend(program.after.iter().map(|a| Box::<[u8]>::from(*a)));
return Some(argv);
}
None
}

// ──────────────────────────────────────────────────────────────────────────

pub struct Version {
Expand Down Expand Up @@ -816,29 +906,20 @@ impl UpgradeCommand {

#[cfg(unix)]
{
let mut unzip_path_buf = bun_paths::path_buffer_pool::get();
let Some(unzip_exe) = which(
&mut unzip_path_buf,
let Some(unzip_argv) = find_unzip_argv(
env_loader.map.get(b"PATH").unwrap_or(b""),
filesystem.top_level_dir,
b"unzip",
tmpname.as_bytes(),
) else {
let _ = sys::unlinkat(&save_dir, tmpname);
bun_core::pretty_errorln!(
"<r><red>error:<r> Failed to locate \"unzip\" in PATH. bun upgrade needs \"unzip\" to work."
"<r><red>error:<r> Failed to locate \"unzip\" in PATH. bun upgrade needs \"unzip\" to work (7z, busybox, bsdtar, python3 supported)."
);
Global::exit(1);
};

// We could just embed libz2
// however, we want to be sure that xattrs are preserved
// xattrs are used for codesigning
// it'd be easy to mess that up
let unzip_argv: [&[u8]; 4] =
[unzip_exe.as_bytes(), b"-q", b"-o", tmpname.as_bytes()];

let unzip_result = match spawn_sync::spawn(&spawn_sync::Options {
argv: build_argv(&unzip_argv),
argv: unzip_argv,
envp: None,
cwd: Box::<[u8]>::from(&tmpdir_path_buf[..tmpdir_path_len]),
stdin: spawn_sync::SyncStdio::Inherit,
Comment on lines 937 to 941

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 nit (optional): users whose only extractor is 7z/7zz/7za see 7-Zip's banner and file listing in the middle of bun upgrade output, which the base's unzip -q never printed. The extractor spawn at upgrade_command.rs:926 inherits stdout for every table row, while install.sh:186 silences the same 7z invocation with >/dev/null. Fix: keep extractor stdout quiet for every row, e.g. use SyncStdio::Ignore for stdout at :926 (stderr can stay inherited so failures remain visible), or add a per-row stdout setting to UnzipProgram.

Extended reasoning...

UNZIP_PROGRAMS rows for 7z, 7zz and 7za (upgrade_command.rs:90-104) pass only x -y; 7-Zip has no quiet switch and always prints its version banner, 'Scanning the drive for archives', 'Extracting archive: bun.zip', the entry list and 'Everything is Ok' to stdout. The spawn at :921-931 sets stdout: spawn_sync::SyncStdio::Inherit, so that text lands on the user's terminal between the download progress and the 'Upgraded.' line. The shell installer for the same case, install.sh:186, appends >/dev/null. On the base branch only unzip -q -o ran, which prints nothing on success. Trigger: a host with no unzip/busybox but with p7zip or 7-Zip installed (the population this PR adds support for). Consequence: noisy, inconsistent upgrade output; no functional failure.

Verification: nit — triggers when find_unzip_argv selects one of the 7-Zip rows (host PATH has no unzip/busybox-with-unzip but has 7z, 7zz or 7za), a configuration the PR explicitly supports. Mechanism verified: /home/claude/bun/src/runtime/cli/upgrade_command.rs:90-104 define the 7z/7zz/7za rows with before: &[b"x", b"-y"] and no output-suppressing switch (-bso0/-bsp0), and the spawn…

Expand Down Expand Up @@ -883,6 +964,25 @@ impl UpgradeCommand {
Global::exit(1);
}
}

// `python3 -m zipfile` does not restore the file mode, and
// some busybox builds do not either.
Comment on lines +991 to +992

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

let exe_z: &ZStr = ZStr::from_static(if use_profile {
const_format::concatcp!(UpgradeCommand::PROFILE_EXE_SUBPATH, "\0")
.as_bytes()
} else {
const_format::concatcp!(UpgradeCommand::EXE_SUBPATH, "\0").as_bytes()
});
if let Err(err) = sys::fchmodat(&save_dir, exe_z, 0o755, 0) {
let _ = sys::unlinkat(&save_dir, tmpname);
let _ = save_dir_.delete_tree(&version_name);
bun_core::pretty_errorln!(
"<r><red>error:<r> Failed to set permissions on {} due to {}.",
bstr::BStr::new(exe),
bstr::BStr::new(err.name())
);
Global::exit(1);
}
}
#[cfg(windows)]
{
Expand Down
Loading
Loading