diff --git a/.version b/.version index ed1d60050..3953e8ad5 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -2.26.2 +2.26.3 diff --git a/doc/manual/rl-next/curl-cloexec.md b/doc/manual/rl-next/curl-cloexec.md new file mode 100644 index 000000000..2fcdfb0d1 --- /dev/null +++ b/doc/manual/rl-next/curl-cloexec.md @@ -0,0 +1,10 @@ +--- +synopsis: Set FD_CLOEXEC on sockets created by curl +issues: [] +prs: [12439] +--- + + +Curl creates sockets without setting FD_CLOEXEC/SOCK_CLOEXEC, this can cause connections to remain open forever when using commands like `nix shell` + +This change sets the FD_CLOEXEC flag using a CURLOPT_SOCKOPTFUNCTION callback. diff --git a/flake.nix b/flake.nix index 04f3e4d87..9cac46d09 100644 --- a/flake.nix +++ b/flake.nix @@ -167,6 +167,7 @@ f = import ./packaging/components.nix { inherit (final) lib; inherit officialRelease; + pkgs = final; src = self; }; }; @@ -237,6 +238,30 @@ LANG=C.UTF-8 ${pkgs.changelog-d}/bin/changelog-d ${./doc/manual/rl-next} >$out ''; repl-completion = nixpkgsFor.${system}.native.callPackage ./tests/repl-completion.nix { }; + + /** + Checks for our packaging expressions. + This shouldn't build anything significant; just check that things + (including derivations) are _set up_ correctly. + */ + packaging-overriding = + let + pkgs = nixpkgsFor.${system}.native; + nix = self.packages.${system}.nix; + in + assert (nix.appendPatches [ pkgs.emptyFile ]).libs.nix-util.src.patches == [ pkgs.emptyFile ]; + if pkgs.stdenv.buildPlatform.isDarwin then + lib.warn "packaging-overriding check currently disabled because of a permissions issue on macOS" pkgs.emptyFile + else + # If this fails, something might be wrong with how we've wired the scope, + # or something could be broken in Nixpkgs. + pkgs.testers.testEqualContents { + assertion = "trivial patch does not change source contents"; + expected = "${./.}"; + actual = + # Same for all components; nix-util is an arbitrary pick + (nix.appendPatches [ pkgs.emptyFile ]).libs.nix-util.src; + }; } // (lib.optionalAttrs (builtins.elem system linux64BitSystems)) { dockerImage = self.hydraJobs.dockerImage.${system}; diff --git a/packaging/components.nix b/packaging/components.nix index 07bb209cd..9da864887 100644 --- a/packaging/components.nix +++ b/packaging/components.nix @@ -1,5 +1,6 @@ { lib, + pkgs, src, officialRelease, }: @@ -7,7 +8,23 @@ scope: let - inherit (scope) callPackage; + inherit (scope) + callPackage + ; + inherit + (scope.callPackage ( + { stdenv }: + { + inherit stdenv; + } + ) { }) + stdenv + ; + inherit (pkgs.buildPackages) + meson + ninja + pkg-config + ; baseVersion = lib.fileContents ../.version; @@ -20,6 +37,165 @@ let }_${src.shortRev or "dirty"}"; fineVersion = baseVersion + fineVersionSuffix; + + root = ../.; + + # Indirection for Nixpkgs to override when package.nix files are vendored + filesetToSource = lib.fileset.toSource; + + /** + Given a set of layers, create a mkDerivation-like function + */ + mkPackageBuilder = + exts: userFn: stdenv.mkDerivation (lib.extends (lib.composeManyExtensions exts) userFn); + + setVersionLayer = finalAttrs: prevAttrs: { + preConfigure = + prevAttrs.prevAttrs or "" + + + # Update the repo-global .version file. + # Symlink ./.version points there, but by default only workDir is writable. + '' + chmod u+w ./.version + echo ${finalAttrs.version} > ./.version + ''; + }; + + localSourceLayer = + finalAttrs: prevAttrs: + let + workDirPath = + # Ideally we'd pick finalAttrs.workDir, but for now `mkDerivation` has + # the requirement that everything except passthru and meta must be + # serialized by mkDerivation, which doesn't work for this. + prevAttrs.workDir; + + workDirSubpath = lib.path.removePrefix root workDirPath; + sources = + assert prevAttrs.fileset._type == "fileset"; + prevAttrs.fileset; + src = lib.fileset.toSource { + fileset = sources; + inherit root; + }; + + in + { + sourceRoot = "${src.name}/" + workDirSubpath; + inherit src; + + # Clear what `derivation` can't/shouldn't serialize; see prevAttrs.workDir. + fileset = null; + workDir = null; + }; + + resolveRelPath = p: lib.path.removePrefix root p; + + makeFetchedSourceLayer = + finalScope: finalAttrs: prevAttrs: + let + workDirPath = + # Ideally we'd pick finalAttrs.workDir, but for now `mkDerivation` has + # the requirement that everything except passthru and meta must be + # serialized by mkDerivation, which doesn't work for this. + prevAttrs.workDir; + + workDirSubpath = resolveRelPath workDirPath; + + in + { + sourceRoot = "${finalScope.patchedSrc.name}/" + workDirSubpath; + src = finalScope.patchedSrc; + version = + let + n = lib.length finalScope.patches; + in + if n == 0 then finalAttrs.version else finalAttrs.version + "+${toString n}"; + + # Clear what `derivation` can't/shouldn't serialize; see prevAttrs.workDir. + fileset = null; + workDir = null; + }; + + mesonLayer = finalAttrs: prevAttrs: { + # NOTE: + # As of https://github.com/NixOS/nixpkgs/blob/8baf8241cea0c7b30e0b8ae73474cb3de83c1a30/pkgs/by-name/me/meson/setup-hook.sh#L26, + # `mesonBuildType` defaults to `plain` if not specified. We want our Nix-built binaries to be optimized by default. + # More on build types here: https://mesonbuild.com/Builtin-options.html#details-for-buildtype. + mesonBuildType = "release"; + # NOTE: + # Users who are debugging Nix builds are expected to set the environment variable `mesonBuildType`, per the + # guidance in https://github.com/NixOS/nix/blob/8a3fc27f1b63a08ac983ee46435a56cf49ebaf4a/doc/manual/source/development/debugging.md?plain=1#L10. + # For this reason, we don't want to refer to `finalAttrs.mesonBuildType` here, but rather use the environment variable. + preConfigure = + prevAttrs.preConfigure or "" + + + lib.optionalString + ( + !stdenv.hostPlatform.isWindows + # build failure + && !stdenv.hostPlatform.isStatic + # LTO breaks exception handling on x86-64-darwin. + && stdenv.system != "x86_64-darwin" + ) + '' + case "$mesonBuildType" in + release|minsize) appendToVar mesonFlags "-Db_lto=true" ;; + *) appendToVar mesonFlags "-Db_lto=false" ;; + esac + ''; + nativeBuildInputs = [ + meson + ninja + ] ++ prevAttrs.nativeBuildInputs or [ ]; + mesonCheckFlags = prevAttrs.mesonCheckFlags or [ ] ++ [ + "--print-errorlogs" + ]; + }; + + mesonBuildLayer = finalAttrs: prevAttrs: { + nativeBuildInputs = prevAttrs.nativeBuildInputs or [ ] ++ [ + pkg-config + ]; + separateDebugInfo = !stdenv.hostPlatform.isStatic; + hardeningDisable = lib.optional stdenv.hostPlatform.isStatic "pie"; + env = + prevAttrs.env or { } + // lib.optionalAttrs ( + stdenv.isLinux + && !(stdenv.hostPlatform.isStatic && stdenv.system == "aarch64-linux") + && !(stdenv.hostPlatform.useLLVM or false) + ) { LDFLAGS = "-fuse-ld=gold"; }; + }; + + mesonLibraryLayer = finalAttrs: prevAttrs: { + outputs = prevAttrs.outputs or [ "out" ] ++ [ "dev" ]; + }; + + # Work around weird `--as-needed` linker behavior with BSD, see + # https://github.com/mesonbuild/meson/issues/3593 + bsdNoLinkAsNeeded = + finalAttrs: prevAttrs: + lib.optionalAttrs stdenv.hostPlatform.isBSD { + mesonFlags = [ (lib.mesonBool "b_asneeded" false) ] ++ prevAttrs.mesonFlags or [ ]; + }; + + miscGoodPractice = finalAttrs: prevAttrs: { + strictDeps = prevAttrs.strictDeps or true; + enableParallelBuilding = true; + }; + + /** + Append patches to the source layer. + */ + appendPatches = + scope: patches: + scope.overrideScope ( + finalScope: prevScope: { + patches = prevScope.patches ++ patches; + } + ); + in # This becomes the pkgs.nixComponents attribute set @@ -27,6 +203,110 @@ in version = baseVersion + versionSuffix; inherit versionSuffix; + inherit filesetToSource; + + /** + A user-provided extension function to apply to each component derivation. + */ + mesonComponentOverrides = finalAttrs: prevAttrs: { }; + + /** + An overridable derivation layer for handling the sources. + */ + sourceLayer = localSourceLayer; + + /** + Resolve a path value to either itself or a path in the `src`, depending + whether `overrideSource` was called. + */ + resolvePath = p: p; + + /** + Apply an extension function (i.e. overlay-shaped) to all component derivations. + */ + overrideAllMesonComponents = + f: + scope.overrideScope ( + finalScope: prevScope: { + mesonComponentOverrides = lib.composeExtensions scope.mesonComponentOverrides f; + } + ); + + /** + Provide an alternate source. This allows the expressions to be vendored without copying the sources, + but it does make the build non-granular; all components will use a complete source. + + Packaging expressions will be ignored. + */ + overrideSource = + src: + scope.overrideScope ( + finalScope: prevScope: { + sourceLayer = makeFetchedSourceLayer finalScope; + /** + Unpatched source for the build of Nix. Packaging expressions will be ignored. + */ + src = src; + /** + Patches for the whole Nix source. Changes to packaging expressions will be ignored. + */ + patches = [ ]; + /** + Fetched and patched source to be used in component derivations. + */ + patchedSrc = + if finalScope.patches == [ ] then + src + else + pkgs.buildPackages.srcOnly ( + pkgs.buildPackages.stdenvNoCC.mkDerivation { + name = "${finalScope.src.name or "nix-source"}-patched"; + inherit (finalScope) src patches; + } + ); + resolvePath = p: finalScope.patchedSrc + "/${resolveRelPath p}"; + appendPatches = appendPatches finalScope; + } + ); + + /** + Append patches to be applied to the whole Nix source. + This affects all components. + + Changes to the packaging expressions will be ignored. + */ + appendPatches = + patches: + # switch to "fetched" source first, so that patches apply to the whole tree. + (scope.overrideSource "${./..}").appendPatches patches; + + mkMesonDerivation = mkPackageBuilder [ + miscGoodPractice + scope.sourceLayer + setVersionLayer + mesonLayer + scope.mesonComponentOverrides + ]; + mkMesonExecutable = mkPackageBuilder [ + miscGoodPractice + bsdNoLinkAsNeeded + scope.sourceLayer + setVersionLayer + mesonLayer + mesonBuildLayer + scope.mesonComponentOverrides + ]; + mkMesonLibrary = mkPackageBuilder [ + miscGoodPractice + bsdNoLinkAsNeeded + scope.sourceLayer + mesonLayer + setVersionLayer + mesonBuildLayer + mesonLibraryLayer + scope.mesonComponentOverrides + ]; + nix-util = callPackage ../src/libutil/package.nix { }; nix-util-c = callPackage ../src/libutil-c/package.nix { }; nix-util-test-support = callPackage ../src/libutil-test-support/package.nix { }; @@ -66,5 +346,33 @@ in nix-perl-bindings = callPackage ../src/perl/package.nix { }; - nix-everything = callPackage ../packaging/everything.nix { }; + nix-everything = callPackage ../packaging/everything.nix { } // { + # Note: no `passthru.overrideAllMesonComponents` + # This would propagate into `nix.overrideAttrs f`, but then discard + # `f` when `.overrideAllMesonComponents` is used. + # Both "methods" should be views on the same fixpoint overriding mechanism + # for that to work. For now, we intentionally don't support the broken + # two-fixpoint solution. + /** + Apply an extension function (i.e. overlay-shaped) to all component derivations, and return the nix package. + */ + overrideAllMesonComponents = f: (scope.overrideAllMesonComponents f).nix-everything; + + /** + Append patches to be applied to the whole Nix source. + This affects all components. + + Changes to the packaging expressions will be ignored. + */ + appendPatches = ps: (scope.appendPatches ps).nix-everything; + + /** + Provide an alternate source. This allows the expressions to be vendored without copying the sources, + but it does make the build non-granular; all components will use a complete source. + + Packaging expressions will be ignored. + */ + overrideSource = src: (scope.overrideSource src).nix-everything; + + }; } diff --git a/packaging/dependencies.nix b/packaging/dependencies.nix index afbc31fc6..535b3ff37 100644 --- a/packaging/dependencies.nix +++ b/packaging/dependencies.nix @@ -17,8 +17,6 @@ in let inherit (pkgs) lib; - root = ../.; - stdenv = if prevStdenv.isDarwin && prevStdenv.isx86_64 then darwinStdenv else prevStdenv; # Fix the following error with the default x86_64-darwin SDK: @@ -30,113 +28,6 @@ let # all the way back to 10.6. darwinStdenv = pkgs.overrideSDK prevStdenv { darwinMinVersion = "10.13"; }; - # Nixpkgs implements this by returning a subpath into the fetched Nix sources. - resolvePath = p: p; - - # Indirection for Nixpkgs to override when package.nix files are vendored - filesetToSource = lib.fileset.toSource; - - /** - Given a set of layers, create a mkDerivation-like function - */ - mkPackageBuilder = - exts: userFn: stdenv.mkDerivation (lib.extends (lib.composeManyExtensions exts) userFn); - - localSourceLayer = - finalAttrs: prevAttrs: - let - workDirPath = - # Ideally we'd pick finalAttrs.workDir, but for now `mkDerivation` has - # the requirement that everything except passthru and meta must be - # serialized by mkDerivation, which doesn't work for this. - prevAttrs.workDir; - - workDirSubpath = lib.path.removePrefix root workDirPath; - sources = - assert prevAttrs.fileset._type == "fileset"; - prevAttrs.fileset; - src = lib.fileset.toSource { - fileset = sources; - inherit root; - }; - - in - { - sourceRoot = "${src.name}/" + workDirSubpath; - inherit src; - - # Clear what `derivation` can't/shouldn't serialize; see prevAttrs.workDir. - fileset = null; - workDir = null; - }; - - mesonLayer = finalAttrs: prevAttrs: { - # NOTE: - # As of https://github.com/NixOS/nixpkgs/blob/8baf8241cea0c7b30e0b8ae73474cb3de83c1a30/pkgs/by-name/me/meson/setup-hook.sh#L26, - # `mesonBuildType` defaults to `plain` if not specified. We want our Nix-built binaries to be optimized by default. - # More on build types here: https://mesonbuild.com/Builtin-options.html#details-for-buildtype. - mesonBuildType = "release"; - # NOTE: - # Users who are debugging Nix builds are expected to set the environment variable `mesonBuildType`, per the - # guidance in https://github.com/NixOS/nix/blob/8a3fc27f1b63a08ac983ee46435a56cf49ebaf4a/doc/manual/source/development/debugging.md?plain=1#L10. - # For this reason, we don't want to refer to `finalAttrs.mesonBuildType` here, but rather use the environment variable. - preConfigure = - prevAttrs.preConfigure or "" - + - lib.optionalString - ( - !stdenv.hostPlatform.isWindows - # build failure - && !stdenv.hostPlatform.isStatic - # LTO breaks exception handling on x86-64-darwin. - && stdenv.system != "x86_64-darwin" - ) - '' - case "$mesonBuildType" in - release|minsize) appendToVar mesonFlags "-Db_lto=true" ;; - *) appendToVar mesonFlags "-Db_lto=false" ;; - esac - ''; - nativeBuildInputs = [ - pkgs.buildPackages.meson - pkgs.buildPackages.ninja - ] ++ prevAttrs.nativeBuildInputs or [ ]; - mesonCheckFlags = prevAttrs.mesonCheckFlags or [ ] ++ [ - "--print-errorlogs" - ]; - }; - - mesonBuildLayer = finalAttrs: prevAttrs: { - nativeBuildInputs = prevAttrs.nativeBuildInputs or [ ] ++ [ - pkgs.buildPackages.pkg-config - ]; - separateDebugInfo = !stdenv.hostPlatform.isStatic; - hardeningDisable = lib.optional stdenv.hostPlatform.isStatic "pie"; - env = - prevAttrs.env or { } - // lib.optionalAttrs ( - stdenv.isLinux - && !(stdenv.hostPlatform.isStatic && stdenv.system == "aarch64-linux") - && !(stdenv.hostPlatform.useLLVM or false) - ) { LDFLAGS = "-fuse-ld=gold"; }; - }; - - mesonLibraryLayer = finalAttrs: prevAttrs: { - outputs = prevAttrs.outputs or [ "out" ] ++ [ "dev" ]; - }; - - # Work around weird `--as-needed` linker behavior with BSD, see - # https://github.com/mesonbuild/meson/issues/3593 - bsdNoLinkAsNeeded = - finalAttrs: prevAttrs: - lib.optionalAttrs stdenv.hostPlatform.isBSD { - mesonFlags = [ (lib.mesonBool "b_asneeded" false) ] ++ prevAttrs.mesonFlags or [ ]; - }; - - miscGoodPractice = finalAttrs: prevAttrs: { - strictDeps = prevAttrs.strictDeps or true; - enableParallelBuilding = true; - }; in scope: { inherit stdenv; @@ -174,56 +65,39 @@ scope: { installPhase = lib.replaceStrings [ "--without-python" ] [ "" ] old.installPhase; }); - libgit2 = pkgs.libgit2.overrideAttrs (attrs: { - cmakeFlags = attrs.cmakeFlags or [ ] ++ [ "-DUSE_SSH=exec" ]; - nativeBuildInputs = - attrs.nativeBuildInputs or [ ] - # gitMinimal does not build on Windows. See packbuilder patch. - ++ lib.optionals (!stdenv.hostPlatform.isWindows) [ - # Needed for `git apply`; see `prePatch` - pkgs.buildPackages.gitMinimal - ]; - # Only `git apply` can handle git binary patches - prePatch = - attrs.prePatch or "" - + lib.optionalString (!stdenv.hostPlatform.isWindows) '' - patch() { - git apply - } - ''; - patches = - attrs.patches or [ ] - ++ [ - ./patches/libgit2-mempack-thin-packfile.patch - ] - # gitMinimal does not build on Windows, but fortunately this patch only - # impacts interruptibility - ++ lib.optionals (!stdenv.hostPlatform.isWindows) [ - # binary patch; see `prePatch` - ./patches/libgit2-packbuilder-callback-interruptible.patch - ]; - }); - - inherit resolvePath filesetToSource; - - mkMesonDerivation = mkPackageBuilder [ - miscGoodPractice - localSourceLayer - mesonLayer - ]; - mkMesonExecutable = mkPackageBuilder [ - miscGoodPractice - bsdNoLinkAsNeeded - localSourceLayer - mesonLayer - mesonBuildLayer - ]; - mkMesonLibrary = mkPackageBuilder [ - miscGoodPractice - bsdNoLinkAsNeeded - localSourceLayer - mesonLayer - mesonBuildLayer - mesonLibraryLayer - ]; + libgit2 = pkgs.libgit2.overrideAttrs ( + attrs: + { + cmakeFlags = attrs.cmakeFlags or [ ] ++ [ "-DUSE_SSH=exec" ]; + } + # libgit2: Nixpkgs 24.11 has < 1.9.0, which needs our patches + // lib.optionalAttrs (!lib.versionAtLeast pkgs.libgit2.version "1.9.0") { + nativeBuildInputs = + attrs.nativeBuildInputs or [ ] + # gitMinimal does not build on Windows. See packbuilder patch. + ++ lib.optionals (!stdenv.hostPlatform.isWindows) [ + # Needed for `git apply`; see `prePatch` + pkgs.buildPackages.gitMinimal + ]; + # Only `git apply` can handle git binary patches + prePatch = + attrs.prePatch or "" + + lib.optionalString (!stdenv.hostPlatform.isWindows) '' + patch() { + git apply + } + ''; + patches = + attrs.patches or [ ] + ++ [ + ./patches/libgit2-mempack-thin-packfile.patch + ] + # gitMinimal does not build on Windows, but fortunately this patch only + # impacts interruptibility + ++ lib.optionals (!stdenv.hostPlatform.isWindows) [ + # binary patch; see `prePatch` + ./patches/libgit2-packbuilder-callback-interruptible.patch + ]; + } + ); } diff --git a/src/libcmd/package.nix b/src/libcmd/package.nix index d155d9f1e..d459d1c20 100644 --- a/src/libcmd/package.nix +++ b/src/libcmd/package.nix @@ -64,14 +64,6 @@ mkMesonLibrary (finalAttrs: { nlohmann_json ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ (lib.mesonEnable "markdown" enableMarkdown) (lib.mesonOption "readline-flavor" readlineFlavor) diff --git a/src/libexpr-c/package.nix b/src/libexpr-c/package.nix index ad1ea371c..694fbc1fe 100644 --- a/src/libexpr-c/package.nix +++ b/src/libexpr-c/package.nix @@ -36,14 +36,6 @@ mkMesonLibrary (finalAttrs: { nix-expr ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libexpr-test-support/package.nix b/src/libexpr-test-support/package.nix index 5628d606a..44b0ff386 100644 --- a/src/libexpr-test-support/package.nix +++ b/src/libexpr-test-support/package.nix @@ -40,14 +40,6 @@ mkMesonLibrary (finalAttrs: { rapidcheck ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libexpr-tests/package.nix b/src/libexpr-tests/package.nix index bb5acb7c8..51d52e935 100644 --- a/src/libexpr-tests/package.nix +++ b/src/libexpr-tests/package.nix @@ -46,14 +46,6 @@ mkMesonExecutable (finalAttrs: { gtest ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libexpr/eval-settings.cc b/src/libexpr/eval-settings.cc index 4cbcb39b9..ade0abf9a 100644 --- a/src/libexpr/eval-settings.cc +++ b/src/libexpr/eval-settings.cc @@ -57,7 +57,7 @@ Strings EvalSettings::getDefaultNixPath() { Strings res; auto add = [&](const Path & p, const std::string & s = std::string()) { - if (pathAccessible(p)) { + if (std::filesystem::exists(p)) { if (s.empty()) { res.push_back(p); } else { diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc index dee764429..8aef85dc5 100644 --- a/src/libexpr/eval.cc +++ b/src/libexpr/eval.cc @@ -3070,8 +3070,11 @@ std::optional EvalState::resolveLookupPathPath(const LookupPath::Pat auto i = lookupPathResolved.find(value); if (i != lookupPathResolved.end()) return i->second; - auto finish = [&](SourcePath res) { - debug("resolved search path element '%s' to '%s'", value, res); + auto finish = [&](std::optional res) { + if (res) + debug("resolved search path element '%s' to '%s'", value, *res); + else + debug("failed to resolve search path element '%s'", value); lookupPathResolved.emplace(value, res); return res; }; @@ -3123,8 +3126,7 @@ std::optional EvalState::resolveLookupPathPath(const LookupPath::Pat } } - debug("failed to resolve search path element '%s'", value); - return std::nullopt; + return finish(std::nullopt); } diff --git a/src/libexpr/package.nix b/src/libexpr/package.nix index afd01c384..533dae9f2 100644 --- a/src/libexpr/package.nix +++ b/src/libexpr/package.nix @@ -77,14 +77,6 @@ mkMesonLibrary (finalAttrs: { nlohmann_json ] ++ lib.optional enableGC boehmgc; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ (lib.mesonEnable "gc" enableGC) ]; diff --git a/src/libfetchers-tests/package.nix b/src/libfetchers-tests/package.nix index f2680e9b3..1e379fc5a 100644 --- a/src/libfetchers-tests/package.nix +++ b/src/libfetchers-tests/package.nix @@ -44,14 +44,6 @@ mkMesonExecutable (finalAttrs: { gtest ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libfetchers/package.nix b/src/libfetchers/package.nix index b0aecd049..3f52e9878 100644 --- a/src/libfetchers/package.nix +++ b/src/libfetchers/package.nix @@ -41,14 +41,6 @@ mkMesonLibrary (finalAttrs: { nlohmann_json ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - meta = { platforms = lib.platforms.unix ++ lib.platforms.windows; }; diff --git a/src/libflake-c/package.nix b/src/libflake-c/package.nix index f0615a427..114950852 100644 --- a/src/libflake-c/package.nix +++ b/src/libflake-c/package.nix @@ -38,14 +38,6 @@ mkMesonLibrary (finalAttrs: { nix-flake ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libflake-tests/package.nix b/src/libflake-tests/package.nix index ea936f23c..db507fc3a 100644 --- a/src/libflake-tests/package.nix +++ b/src/libflake-tests/package.nix @@ -46,14 +46,6 @@ mkMesonExecutable (finalAttrs: { gtest ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libflake/package.nix b/src/libflake/package.nix index ebd38e140..5240ce5e3 100644 --- a/src/libflake/package.nix +++ b/src/libflake/package.nix @@ -40,14 +40,6 @@ mkMesonLibrary (finalAttrs: { nlohmann_json ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - meta = { platforms = lib.platforms.unix ++ lib.platforms.windows; }; diff --git a/src/libmain-c/package.nix b/src/libmain-c/package.nix index cf710e03b..f019a917d 100644 --- a/src/libmain-c/package.nix +++ b/src/libmain-c/package.nix @@ -40,14 +40,6 @@ mkMesonLibrary (finalAttrs: { nix-main ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libmain/package.nix b/src/libmain/package.nix index 046b505df..c03697c48 100644 --- a/src/libmain/package.nix +++ b/src/libmain/package.nix @@ -37,14 +37,6 @@ mkMesonLibrary (finalAttrs: { openssl ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - meta = { platforms = lib.platforms.unix ++ lib.platforms.windows; }; diff --git a/src/libmain/shared.cc b/src/libmain/shared.cc index 60bf14a4c..f61754bf1 100644 --- a/src/libmain/shared.cc +++ b/src/libmain/shared.cc @@ -315,20 +315,6 @@ void printVersion(const std::string & programName) throw Exit(); } - -void showManPage(const std::string & name) -{ - restoreProcessContext(); - setEnv("MANPATH", settings.nixManDir.c_str()); - execlp("man", "man", name.c_str(), nullptr); - if (errno == ENOENT) { - // Not SysError because we don't want to suffix the errno, aka No such file or directory. - throw Error("The '%1%' command was not found, but it is needed for '%2%' and some other '%3%' commands' help text. Perhaps you could install the '%1%' command?", "man", name.c_str(), "nix-*"); - } - throw SysError("command 'man %1%' failed", name.c_str()); -} - - int handleExceptions(const std::string & programName, std::function fun) { ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this diff --git a/src/libmain/shared.hh b/src/libmain/shared.hh index 712b404d3..a6a18ceb0 100644 --- a/src/libmain/shared.hh +++ b/src/libmain/shared.hh @@ -70,11 +70,6 @@ struct LegacyArgs : public MixCommonArgs, public RootArgs }; -/** - * Show the manual page for the specified program. - */ -void showManPage(const std::string & name); - /** * The constructor of this class starts a pager if standard output is a * terminal and $PAGER is set. Standard output is redirected to the diff --git a/src/libstore-c/package.nix b/src/libstore-c/package.nix index 89abeaab8..fde17c78e 100644 --- a/src/libstore-c/package.nix +++ b/src/libstore-c/package.nix @@ -36,14 +36,6 @@ mkMesonLibrary (finalAttrs: { nix-store ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libstore-test-support/package.nix b/src/libstore-test-support/package.nix index 7cc29795c..ccac25ee1 100644 --- a/src/libstore-test-support/package.nix +++ b/src/libstore-test-support/package.nix @@ -40,14 +40,6 @@ mkMesonLibrary (finalAttrs: { rapidcheck ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libstore-tests/package.nix b/src/libstore-tests/package.nix index 670386c4a..b39ee7fa7 100644 --- a/src/libstore-tests/package.nix +++ b/src/libstore-tests/package.nix @@ -52,14 +52,6 @@ mkMesonExecutable (finalAttrs: { nix-store-test-support ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libstore/filetransfer.cc b/src/libstore/filetransfer.cc index 8439cc39c..932e1d756 100644 --- a/src/libstore/filetransfer.cc +++ b/src/libstore/filetransfer.cc @@ -300,6 +300,14 @@ struct curlFileTransfer : public FileTransfer return ((TransferItem *) userp)->readCallback(buffer, size, nitems); } + #if !defined(_WIN32) && LIBCURL_VERSION_NUM >= 0x071000 + static int cloexec_callback(void *, curl_socket_t curlfd, curlsocktype purpose) { + unix::closeOnExec(curlfd); + vomit("cloexec set for fd %i", curlfd); + return CURL_SOCKOPT_OK; + } + #endif + void init() { if (!req) req = curl_easy_init(); @@ -359,6 +367,10 @@ struct curlFileTransfer : public FileTransfer curl_easy_setopt(req, CURLOPT_SSL_VERIFYHOST, 0); } + #if !defined(_WIN32) && LIBCURL_VERSION_NUM >= 0x071000 + curl_easy_setopt(req, CURLOPT_SOCKOPTFUNCTION, cloexec_callback); + #endif + curl_easy_setopt(req, CURLOPT_CONNECTTIMEOUT, fileTransferSettings.connectTimeout.get()); curl_easy_setopt(req, CURLOPT_LOW_SPEED_LIMIT, 1L); diff --git a/src/libstore/globals.cc b/src/libstore/globals.cc index abe6bab2c..f4abbe43f 100644 --- a/src/libstore/globals.cc +++ b/src/libstore/globals.cc @@ -65,7 +65,6 @@ Settings::Settings() , nixStateDir(canonPath(getEnvNonEmpty("NIX_STATE_DIR").value_or(NIX_STATE_DIR))) , nixConfDir(canonPath(getEnvNonEmpty("NIX_CONF_DIR").value_or(NIX_CONF_DIR))) , nixUserConfFiles(getUserConfigFiles()) - , nixManDir(canonPath(NIX_MAN_DIR)) , nixDaemonSocketFile(canonPath(getEnvNonEmpty("NIX_DAEMON_SOCKET_PATH").value_or(nixStateDir + DEFAULT_SOCKET_PATH))) { #ifndef _WIN32 @@ -243,7 +242,7 @@ Path Settings::getDefaultSSLCertFile() return ""; } -const std::string nixVersion = PACKAGE_VERSION; +std::string nixVersion = PACKAGE_VERSION; const std::string determinateNixVersion = DETERMINATE_NIX_VERSION; diff --git a/src/libstore/globals.hh b/src/libstore/globals.hh index 6f71cf87b..30a2f775e 100644 --- a/src/libstore/globals.hh +++ b/src/libstore/globals.hh @@ -84,11 +84,6 @@ public: */ std::vector nixUserConfFiles; - /** - * The directory where the man pages are stored. - */ - Path nixManDir; - /** * File name of the socket the daemon listens to. */ @@ -1253,7 +1248,15 @@ void loadConfFile(AbstractConfig & config); // Used by the Settings constructor std::vector getUserConfigFiles(); -extern const std::string nixVersion; +/** + * The version of Nix itself. + * + * This is not `const`, so that the Nix CLI can provide a more detailed version + * number including the git revision, without having to "re-compile" the entire + * set of Nix libraries to include that version, even when those libraries are + * not affected by the change. + */ +extern std::string nixVersion; extern const std::string determinateNixVersion; diff --git a/src/libstore/legacy-ssh-store.cc b/src/libstore/legacy-ssh-store.cc index eac360a4f..480f41059 100644 --- a/src/libstore/legacy-ssh-store.cc +++ b/src/libstore/legacy-ssh-store.cc @@ -69,7 +69,10 @@ ref LegacySSHStore::openConnection() command.push_back("--store"); command.push_back(remoteStore.get()); } - conn->sshConn = master.startCommand(std::move(command)); + conn->sshConn = master.startCommand(std::move(command), std::list{extraSshArgs}); + if (connPipeSize) { + conn->sshConn->trySetBufferSize(*connPipeSize); + } conn->to = FdSink(conn->sshConn->in.get()); conn->from = FdSource(conn->sshConn->out.get()); @@ -100,19 +103,31 @@ std::string LegacySSHStore::getUri() return *uriSchemes().begin() + "://" + host; } +std::map LegacySSHStore::queryPathInfosUncached( + const StorePathSet & paths) +{ + auto conn(connections->get()); + + /* No longer support missing NAR hash */ + assert(GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4); + + debug("querying remote host '%s' for info on '%s'", host, concatStringsSep(", ", printStorePathSet(paths))); + + auto infos = conn->queryPathInfos(*this, paths); + + for (const auto & [_, info] : infos) { + if (info.narHash == Hash::dummy) + throw Error("NAR hash is now mandatory"); + } + + return infos; +} void LegacySSHStore::queryPathInfoUncached(const StorePath & path, Callback> callback) noexcept { try { - auto conn(connections->get()); - - /* No longer support missing NAR hash */ - assert(GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4); - - debug("querying remote host '%s' for info on '%s'", host, printStorePath(path)); - - auto infos = conn->queryPathInfos(*this, {path}); + auto infos = queryPathInfosUncached({path}); switch (infos.size()) { case 0: @@ -120,9 +135,6 @@ void LegacySSHStore::queryPathInfoUncached(const StorePath & path, case 1: { auto & [path2, info] = *infos.begin(); - if (info.narHash == Hash::dummy) - throw Error("NAR hash is now mandatory"); - assert(path == path2); return callback(std::make_shared( std::move(path), @@ -193,13 +205,19 @@ void LegacySSHStore::addToStore(const ValidPathInfo & info, Source & source, void LegacySSHStore::narFromPath(const StorePath & path, Sink & sink) { - auto conn(connections->get()); - conn->narFromPath(*this, path, [&](auto & source) { + narFromPath(path, [&](auto & source) { copyNAR(source, sink); }); } +void LegacySSHStore::narFromPath(const StorePath & path, std::function fun) +{ + auto conn(connections->get()); + conn->narFromPath(*this, path, fun); +} + + static ServeProto::BuildOptions buildSettings() { return { @@ -223,6 +241,19 @@ BuildResult LegacySSHStore::buildDerivation(const StorePath & drvPath, const Bas return conn->getBuildDerivationResponse(*this); } +std::function LegacySSHStore::buildDerivationAsync( + const StorePath & drvPath, const BasicDerivation & drv, + const ServeProto::BuildOptions & options) +{ + // Until we have C++23 std::move_only_function + auto conn = std::make_shared::Handle>(connections->get()); + (*conn)->putBuildDerivationRequest(*this, drvPath, drv, options); + + return [this,conn]() -> BuildResult { + return (*conn)->getBuildDerivationResponse(*this); + }; +} + void LegacySSHStore::buildPaths(const std::vector & drvPaths, BuildMode buildMode, std::shared_ptr evalStore) { @@ -294,6 +325,32 @@ StorePathSet LegacySSHStore::queryValidPaths(const StorePathSet & paths, } +StorePathSet LegacySSHStore::queryValidPaths(const StorePathSet & paths, + bool lock, SubstituteFlag maybeSubstitute) +{ + auto conn(connections->get()); + return conn->queryValidPaths(*this, + lock, paths, maybeSubstitute); +} + + +void LegacySSHStore::addMultipleToStoreLegacy(Store & srcStore, const StorePathSet & paths) +{ + auto conn(connections->get()); + conn->to << ServeProto::Command::ImportPaths; + try { + srcStore.exportPaths(paths, conn->to); + } catch (...) { + conn->good = false; + throw; + } + conn->to.flush(); + + if (readInt(conn->from) != 1) + throw Error("remote machine failed to import closure"); +} + + void LegacySSHStore::connect() { auto conn(connections->get()); @@ -307,6 +364,28 @@ unsigned int LegacySSHStore::getProtocol() } +pid_t LegacySSHStore::getConnectionPid() +{ + auto conn(connections->get()); +#ifndef _WIN32 + return conn->sshConn->sshPid; +#else + // TODO: Implement + return 0; +#endif +} + + +LegacySSHStore::ConnectionStats LegacySSHStore::getConnectionStats() +{ + auto conn(connections->get()); + return { + .bytesReceived = conn->from.read, + .bytesSent = conn->to.written, + }; +} + + /** * The legacy ssh protocol doesn't support checking for trusted-user. * Try using ssh-ng:// instead if you want to know. diff --git a/src/libstore/legacy-ssh-store.hh b/src/libstore/legacy-ssh-store.hh index b541455b4..92aa4ae56 100644 --- a/src/libstore/legacy-ssh-store.hh +++ b/src/libstore/legacy-ssh-store.hh @@ -6,6 +6,7 @@ #include "ssh.hh" #include "callback.hh" #include "pool.hh" +#include "serve-protocol.hh" namespace nix { @@ -24,6 +25,16 @@ struct LegacySSHStoreConfig : virtual CommonSSHStoreConfig const Setting maxConnections{this, 1, "max-connections", "Maximum number of concurrent SSH connections."}; + /** + * Hack for hydra + */ + Strings extraSshArgs = {}; + + /** + * Exposed for hydra + */ + std::optional connPipeSize; + const std::string name() override { return "SSH Store"; } static std::set uriSchemes() { return {"ssh"}; } @@ -60,11 +71,24 @@ struct LegacySSHStore : public virtual LegacySSHStoreConfig, public virtual Stor void queryPathInfoUncached(const StorePath & path, Callback> callback) noexcept override; + std::map queryPathInfosUncached( + const StorePathSet & paths); + void addToStore(const ValidPathInfo & info, Source & source, RepairFlag repair, CheckSigsFlag checkSigs) override; void narFromPath(const StorePath & path, Sink & sink) override; + /** + * Hands over the connection temporarily as source to the given + * function. The function must not consume beyond the NAR; it can + * not just blindly try to always read more bytes until it is + * cut-off. + * + * This is exposed for sake of Hydra. + */ + void narFromPath(const StorePath & path, std::function fun); + std::optional queryPathFromHashPart(const std::string & hashPart) override { unsupported("queryPathFromHashPart"); } @@ -93,6 +117,16 @@ public: BuildResult buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildMode buildMode) override; + /** + * Note, the returned function must only be called once, or we'll + * try to read from the connection twice. + * + * @todo Use C++23 `std::move_only_function`. + */ + std::function buildDerivationAsync( + const StorePath & drvPath, const BasicDerivation & drv, + const ServeProto::BuildOptions & options); + void buildPaths(const std::vector & drvPaths, BuildMode buildMode, std::shared_ptr evalStore) override; void ensurePath(const StorePath & path) override @@ -119,10 +153,36 @@ public: StorePathSet queryValidPaths(const StorePathSet & paths, SubstituteFlag maybeSubstitute = NoSubstitute) override; + /** + * Custom variation that atomically creates temp locks on the remote + * side. + * + * This exists to prevent a race where the remote host + * garbage-collects paths that are already there. Optionally, ask + * the remote host to substitute missing paths. + */ + StorePathSet queryValidPaths(const StorePathSet & paths, + bool lock, + SubstituteFlag maybeSubstitute = NoSubstitute); + + /** + * Just exists because this is exactly what Hydra was doing, and we + * don't yet want an algorithmic change. + */ + void addMultipleToStoreLegacy(Store & srcStore, const StorePathSet & paths); + void connect() override; unsigned int getProtocol() override; + struct ConnectionStats { + size_t bytesReceived, bytesSent; + }; + + ConnectionStats getConnectionStats(); + + pid_t getConnectionPid(); + /** * The legacy ssh protocol doesn't support checking for trusted-user. * Try using ssh-ng:// instead if you want to know. diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc index f708bd1b0..9a7a941b6 100644 --- a/src/libstore/local-store.cc +++ b/src/libstore/local-store.cc @@ -136,7 +136,12 @@ LocalStore::LocalStore( for (auto & perUserDir : {profilesDir + "/per-user", gcRootsDir + "/per-user"}) { createDirs(perUserDir); if (!readOnly) { - if (chmod(perUserDir.c_str(), 0755) == -1) + auto st = lstat(perUserDir); + + // Skip chmod call if the directory already has the correct permissions (0755). + // This is to avoid failing when the executing user lacks permissions to change the directory's permissions + // even if it would be no-op. + if ((st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) != 0755 && chmod(perUserDir.c_str(), 0755) == -1) throw SysError("could not set permissions on '%s' to 755", perUserDir); } } diff --git a/src/libstore/package.nix b/src/libstore/package.nix index 543694438..a7d9a0ca1 100644 --- a/src/libstore/package.nix +++ b/src/libstore/package.nix @@ -71,14 +71,6 @@ mkMesonLibrary (finalAttrs: { nlohmann_json ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ (lib.mesonEnable "seccomp-sandboxing" stdenv.hostPlatform.isLinux) diff --git a/src/libstore/ssh.cc b/src/libstore/ssh.cc index 116a480ba..f47cfbbec 100644 --- a/src/libstore/ssh.cc +++ b/src/libstore/ssh.cc @@ -240,4 +240,19 @@ Path SSHMaster::startMaster() #endif +void SSHMaster::Connection::trySetBufferSize(size_t size) +{ +#ifdef F_SETPIPE_SZ + /* This `fcntl` method of doing this takes a positive `int`. Check + and convert accordingly. + + The function overall still takes `size_t` because this is more + portable for a platform-agnostic interface. */ + assert(size <= INT_MAX); + int pipesize = size; + fcntl(in.get(), F_SETPIPE_SZ, pipesize); + fcntl(out.get(), F_SETPIPE_SZ, pipesize); +#endif +} + } diff --git a/src/libstore/ssh.hh b/src/libstore/ssh.hh index 85be704ec..eb05df011 100644 --- a/src/libstore/ssh.hh +++ b/src/libstore/ssh.hh @@ -54,6 +54,18 @@ public: Pid sshPid; #endif AutoCloseFD out, in; + + /** + * Try to set the buffer size in both directions to the + * designated amount, if possible. If not possible, does + * nothing. + * + * Current implementation is to use `fcntl` with `F_SETPIPE_SZ`, + * which is Linux-only. For this implementation, `size` must + * convertable to an `int`. In other words, it must be within + * `[0, INT_MAX]`. + */ + void trySetBufferSize(size_t size); }; /** diff --git a/src/libstore/store-api.cc b/src/libstore/store-api.cc index 236622eae..fc3fbcc0f 100644 --- a/src/libstore/store-api.cc +++ b/src/libstore/store-api.cc @@ -230,18 +230,22 @@ void Store::addMultipleToStore( { std::atomic nrDone{0}; std::atomic nrFailed{0}; - std::atomic bytesExpected{0}; std::atomic nrRunning{0}; using PathWithInfo = std::pair>; + uint64_t bytesExpected = 0; + std::map infosMap; StorePathSet storePathsToAdd; for (auto & thingToAdd : pathsToCopy) { + bytesExpected += thingToAdd.first.narSize; infosMap.insert_or_assign(thingToAdd.first.path, &thingToAdd); storePathsToAdd.insert(thingToAdd.first.path); } + act.setExpected(actCopyPath, bytesExpected); + auto showProgress = [&, nrTotal = pathsToCopy.size()]() { act.progress(nrDone, nrTotal, nrRunning, nrFailed); }; @@ -259,9 +263,6 @@ void Store::addMultipleToStore( return StorePathSet(); } - bytesExpected += info.narSize; - act.setExpected(actCopyPath, bytesExpected); - return info.references; }, diff --git a/src/libutil-c/package.nix b/src/libutil-c/package.nix index 72f57d6f9..f26f57775 100644 --- a/src/libutil-c/package.nix +++ b/src/libutil-c/package.nix @@ -34,14 +34,6 @@ mkMesonLibrary (finalAttrs: { nix-util ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libutil-test-support/package.nix b/src/libutil-test-support/package.nix index 33cd5217d..fafd47c86 100644 --- a/src/libutil-test-support/package.nix +++ b/src/libutil-test-support/package.nix @@ -38,14 +38,6 @@ mkMesonLibrary (finalAttrs: { rapidcheck ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libutil-tests/package.nix b/src/libutil-tests/package.nix index d89c54453..c06de6894 100644 --- a/src/libutil-tests/package.nix +++ b/src/libutil-tests/package.nix @@ -45,14 +45,6 @@ mkMesonExecutable (finalAttrs: { gtest ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ ]; diff --git a/src/libutil/package.nix b/src/libutil/package.nix index 586119a6e..47dcb54a2 100644 --- a/src/libutil/package.nix +++ b/src/libutil/package.nix @@ -52,17 +52,6 @@ mkMesonLibrary (finalAttrs: { nlohmann_json ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - # - # TODO: change release process to add `pre` in `.version`, remove it - # before tagging, and restore after. - '' - chmod u+w ./.version - echo ${version} > ../../.version - ''; - mesonFlags = [ (lib.mesonEnable "cpuid" stdenv.hostPlatform.isx86_64) ]; diff --git a/src/nix-build/nix-build.cc b/src/nix-build/nix-build.cc index de01e1afc..5410f0cab 100644 --- a/src/nix-build/nix-build.cc +++ b/src/nix-build/nix-build.cc @@ -27,6 +27,7 @@ #include "users.hh" #include "network-proxy.hh" #include "compatibility-settings.hh" +#include "man-pages.hh" using namespace nix; using namespace std::string_literals; diff --git a/src/nix-channel/nix-channel.cc b/src/nix-channel/nix-channel.cc index 56d1d7abb..ee61db994 100644 --- a/src/nix-channel/nix-channel.cc +++ b/src/nix-channel/nix-channel.cc @@ -8,6 +8,7 @@ #include "users.hh" #include "tarball.hh" #include "self-exe.hh" +#include "man-pages.hh" #include #include diff --git a/src/nix-collect-garbage/nix-collect-garbage.cc b/src/nix-collect-garbage/nix-collect-garbage.cc index 20d5161df..a060a01fd 100644 --- a/src/nix-collect-garbage/nix-collect-garbage.cc +++ b/src/nix-collect-garbage/nix-collect-garbage.cc @@ -7,6 +7,7 @@ #include "shared.hh" #include "globals.hh" #include "legacy.hh" +#include "man-pages.hh" #include #include diff --git a/src/nix-copy-closure/nix-copy-closure.cc b/src/nix-copy-closure/nix-copy-closure.cc index b64af758f..15bff0a0a 100644 --- a/src/nix-copy-closure/nix-copy-closure.cc +++ b/src/nix-copy-closure/nix-copy-closure.cc @@ -2,6 +2,7 @@ #include "realisation.hh" #include "store-api.hh" #include "legacy.hh" +#include "man-pages.hh" using namespace nix; diff --git a/src/nix-env/nix-env.cc b/src/nix-env/nix-env.cc index c99c1088e..aa1edb4c8 100644 --- a/src/nix-env/nix-env.cc +++ b/src/nix-env/nix-env.cc @@ -17,6 +17,7 @@ #include "legacy.hh" #include "eval-settings.hh" // for defexpr #include "terminal.hh" +#include "man-pages.hh" #include #include diff --git a/src/nix-instantiate/nix-instantiate.cc b/src/nix-instantiate/nix-instantiate.cc index 09d354832..0cf926369 100644 --- a/src/nix-instantiate/nix-instantiate.cc +++ b/src/nix-instantiate/nix-instantiate.cc @@ -12,6 +12,7 @@ #include "local-fs-store.hh" #include "common-eval-args.hh" #include "legacy.hh" +#include "man-pages.hh" #include #include diff --git a/src/nix-store/nix-store.cc b/src/nix-store/nix-store.cc index 99bb2c726..3fb69a29d 100644 --- a/src/nix-store/nix-store.cc +++ b/src/nix-store/nix-store.cc @@ -12,6 +12,7 @@ #include "legacy.hh" #include "posix-source-accessor.hh" #include "path-with-outputs.hh" +#include "man-pages.hh" #ifndef _WIN32 // TODO implement on Windows or provide allowed-to-noop interface # include "local-store.hh" diff --git a/src/nix/flake.cc b/src/nix/flake.cc index 84848d18c..5391406df 100644 --- a/src/nix/flake.cc +++ b/src/nix/flake.cc @@ -1088,12 +1088,14 @@ struct CmdFlakeArchive : FlakeCommand, MixJSON, MixDryRun nlohmann::json jsonObj2 = json ? json::object() : nlohmann::json(nullptr); for (auto & [inputName, input] : node.inputs) { if (auto inputNode = std::get_if<0>(&input)) { + if ((*inputNode)->lockedRef.input.isRelative()) + continue; auto storePath = dryRun ? (*inputNode)->lockedRef.input.computeStorePath(*store) : (*inputNode)->lockedRef.input.fetchToStore(store).first; if (json) { - auto& jsonObj3 = jsonObj2[inputName]; + auto & jsonObj3 = jsonObj2[inputName]; jsonObj3["path"] = store->printStorePath(storePath); sources.insert(std::move(storePath)); jsonObj3["inputs"] = traverse(**inputNode); diff --git a/src/nix/hash.cc b/src/nix/hash.cc index eac421d12..91bba47f4 100644 --- a/src/nix/hash.cc +++ b/src/nix/hash.cc @@ -8,6 +8,7 @@ #include "git.hh" #include "posix-source-accessor.hh" #include "misc-store-flags.hh" +#include "man-pages.hh" using namespace nix; diff --git a/src/nix/main.cc b/src/nix/main.cc index 4c30794ba..f8f9d03a4 100644 --- a/src/nix/main.cc +++ b/src/nix/main.cc @@ -553,6 +553,9 @@ void mainWrapped(int argc, char * * argv) int main(int argc, char * * argv) { + // The CLI has a more detailed version than the libraries; see nixVersion. + nix::nixVersion = NIX_CLI_VERSION; + // Increase the default stack size for the evaluator and for // libstdc++'s std::regex. nix::setStackSize(64 * 1024 * 1024); diff --git a/src/nix/man-pages.cc b/src/nix/man-pages.cc new file mode 100644 index 000000000..e9e89bb62 --- /dev/null +++ b/src/nix/man-pages.cc @@ -0,0 +1,29 @@ +#include "man-pages.hh" +#include "file-system.hh" +#include "current-process.hh" +#include "environment-variables.hh" + +namespace nix { + +std::filesystem::path getNixManDir() +{ + return canonPath(NIX_MAN_DIR); +} + +void showManPage(const std::string & name) +{ + restoreProcessContext(); + setEnv("MANPATH", (getNixManDir().string() + ":").c_str()); + execlp("man", "man", name.c_str(), nullptr); + if (errno == ENOENT) { + // Not SysError because we don't want to suffix the errno, aka No such file or directory. + throw Error( + "The '%1%' command was not found, but it is needed for '%2%' and some other '%3%' commands' help text. Perhaps you could install the '%1%' command?", + "man", + name.c_str(), + "nix-*"); + } + throw SysError("command 'man %1%' failed", name.c_str()); +} + +} diff --git a/src/nix/man-pages.hh b/src/nix/man-pages.hh new file mode 100644 index 000000000..9ba035af8 --- /dev/null +++ b/src/nix/man-pages.hh @@ -0,0 +1,28 @@ +#pragma once +///@file + +#include +#include + +namespace nix { + +/** + * @brief Get path to the nix manual dir. + * + * Nix relies on the man pages being available at a NIX_MAN_DIR for + * displaying help messaged for legacy cli. + * + * NIX_MAN_DIR is a compile-time parameter, so man pages are unlikely to work + * for cases when the nix executable is installed out-of-store or as a static binary. + * + */ +std::filesystem::path getNixManDir(); + +/** + * Show the manual page for the specified program. + * + * @param name Name of the man item. + */ +void showManPage(const std::string & name); + +} diff --git a/src/nix/meson.build b/src/nix/meson.build index 2698cc873..1ad3d5b5a 100644 --- a/src/nix/meson.build +++ b/src/nix/meson.build @@ -35,6 +35,9 @@ subdir('nix-meson-build-support/windows-version') configdata = configuration_data() +# The CLI has a more detailed version string than the libraries; see `nixVersion` +configdata.set_quoted('NIX_CLI_VERSION', meson.project_version()) + fs = import('fs') bindir = get_option('bindir') @@ -90,6 +93,7 @@ nix_sources = [config_h] + files( 'ls.cc', 'main.cc', 'make-content-addressed.cc', + 'man-pages.cc', 'nar.cc', 'optimise-store.cc', 'path-from-hash-part.cc', @@ -182,6 +186,16 @@ if host_machine.system() != 'windows' ] endif +fs = import('fs') +prefix = get_option('prefix') + +mandir = get_option('mandir') +mandir = fs.is_absolute(mandir) ? mandir : prefix / mandir + +cpp_args= [ + '-DNIX_MAN_DIR="@0@"'.format(mandir) +] + include_dirs = [include_directories('.')] this_exe = executable( @@ -189,6 +203,7 @@ this_exe = executable( sources, dependencies : deps_private_subproject + deps_private + deps_other, include_directories : include_dirs, + cpp_args : cpp_args, link_args: linker_export_flags, install : true, ) diff --git a/src/nix/package.nix b/src/nix/package.nix index 6e59adc38..40a280437 100644 --- a/src/nix/package.nix +++ b/src/nix/package.nix @@ -91,14 +91,6 @@ mkMesonExecutable (finalAttrs: { nix-cmd ]; - preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../../.version - ''; - mesonFlags = [ ]; diff --git a/src/nix/prefetch.cc b/src/nix/prefetch.cc index db7d9e4ef..84c0224e2 100644 --- a/src/nix/prefetch.cc +++ b/src/nix/prefetch.cc @@ -12,6 +12,7 @@ #include "posix-source-accessor.hh" #include "misc-store-flags.hh" #include "terminal.hh" +#include "man-pages.hh" #include diff --git a/src/nix/unix/daemon.cc b/src/nix/unix/daemon.cc index 746963a01..b4c7c10ed 100644 --- a/src/nix/unix/daemon.cc +++ b/src/nix/unix/daemon.cc @@ -15,6 +15,7 @@ #include "finally.hh" #include "legacy.hh" #include "daemon.hh" +#include "man-pages.hh" #include #include diff --git a/src/perl/lib/Nix/Store.xs b/src/perl/lib/Nix/Store.xs index 172c3500d..cfc3ac034 100644 --- a/src/perl/lib/Nix/Store.xs +++ b/src/perl/lib/Nix/Store.xs @@ -194,7 +194,7 @@ StoreWrapper::computeFSClosure(int flipDirection, int includeOutputs, ...) PPCODE: try { StorePathSet paths; - for (int n = 2; n < items; ++n) + for (int n = 3; n < items; ++n) THIS->store->computeFSClosure(THIS->store->parseStorePath(SvPV_nolen(ST(n))), paths, flipDirection, includeOutputs); for (auto & i : paths) XPUSHs(sv_2mortal(newSVpv(THIS->store->printStorePath(i).c_str(), 0))); @@ -208,7 +208,7 @@ StoreWrapper::topoSortPaths(...) PPCODE: try { StorePathSet paths; - for (int n = 0; n < items; ++n) paths.insert(THIS->store->parseStorePath(SvPV_nolen(ST(n)))); + for (int n = 1; n < items; ++n) paths.insert(THIS->store->parseStorePath(SvPV_nolen(ST(n)))); auto sorted = THIS->store->topoSortPaths(paths); for (auto & i : sorted) XPUSHs(sv_2mortal(newSVpv(THIS->store->printStorePath(i).c_str(), 0))); @@ -234,7 +234,7 @@ StoreWrapper::exportPaths(int fd, ...) PPCODE: try { StorePathSet paths; - for (int n = 1; n < items; ++n) paths.insert(THIS->store->parseStorePath(SvPV_nolen(ST(n)))); + for (int n = 2; n < items; ++n) paths.insert(THIS->store->parseStorePath(SvPV_nolen(ST(n)))); FdSink sink(fd); THIS->store->exportPaths(paths, sink); } catch (Error & e) { diff --git a/tests/functional/common/functions.sh b/tests/functional/common/functions.sh index fd5d5e619..fd5938576 100644 --- a/tests/functional/common/functions.sh +++ b/tests/functional/common/functions.sh @@ -67,7 +67,7 @@ startDaemon() { die "startDaemon: not supported when testing on NixOS. Is it really needed? If so add conditionals; e.g. if ! isTestOnNixOS; then ..." fi - # Don’t start the daemon twice, as this would just make it loop indefinitely + # Don't start the daemon twice, as this would just make it loop indefinitely. if [[ "${_NIX_TEST_DAEMON_PID-}" != '' ]]; then return fi @@ -77,15 +77,19 @@ startDaemon() { PATH=$DAEMON_PATH nix --extra-experimental-features 'nix-command' daemon & _NIX_TEST_DAEMON_PID=$! export _NIX_TEST_DAEMON_PID - for ((i = 0; i < 300; i++)); do + for ((i = 0; i < 60; i++)); do if [[ -S $NIX_DAEMON_SOCKET_PATH ]]; then DAEMON_STARTED=1 break; fi + if ! kill -0 "$_NIX_TEST_DAEMON_PID"; then + echo "daemon died unexpectedly" >&2 + exit 1 + fi sleep 0.1 done if [[ -z ${DAEMON_STARTED+x} ]]; then - fail "Didn’t manage to start the daemon" + fail "Didn't manage to start the daemon" fi trap "killDaemon" EXIT # Save for if daemon is killed @@ -98,7 +102,7 @@ killDaemon() { die "killDaemon: not supported when testing on NixOS. Is it really needed? If so add conditionals; e.g. if ! isTestOnNixOS; then ..." fi - # Don’t fail trying to stop a non-existant daemon twice + # Don't fail trying to stop a non-existant daemon twice. if [[ "${_NIX_TEST_DAEMON_PID-}" == '' ]]; then return fi @@ -220,7 +224,7 @@ assertStderr() { needLocalStore() { if [[ "$NIX_REMOTE" == "daemon" ]]; then - skipTest "Can’t run through the daemon ($1)" + skipTest "Can't run through the daemon ($1)" fi } diff --git a/tests/functional/flakes/relative-paths.sh b/tests/functional/flakes/relative-paths.sh index 9b93da9c1..ac4b07eb2 100644 --- a/tests/functional/flakes/relative-paths.sh +++ b/tests/functional/flakes/relative-paths.sh @@ -76,6 +76,9 @@ if ! isTestOnNixOS; then fi (! grep narHash "$subflake2/flake.lock") +# Test `nix flake archive` with relative path flakes. +nix flake archive --json "$rootFlake" + # Test circular relative path flakes. FIXME: doesn't work at the moment. if false; then diff --git a/tests/functional/misc.sh b/tests/functional/misc.sh index 7d63756b7..cb4d4139f 100755 --- a/tests/functional/misc.sh +++ b/tests/functional/misc.sh @@ -11,7 +11,7 @@ source common.sh #nix-hash --help | grepQuiet base32 # Can we ask for the version number? -nix-env --version | grep "$version" +nix-env --version | grep -F "${_NIX_TEST_CLIENT_VERSION:-$version}" nix_env=$(type -P nix-env) (PATH=""; ! $nix_env --help 2>&1 ) | grepQuiet -F "The 'man' command was not found, but it is needed for 'nix-env' and some other 'nix-*' commands' help text. Perhaps you could install the 'man' command?" diff --git a/tests/functional/package.nix b/tests/functional/package.nix index 74c034196..a84ad1791 100644 --- a/tests/functional/package.nix +++ b/tests/functional/package.nix @@ -75,16 +75,10 @@ mkMesonDerivation ( ]; preConfigure = - # "Inline" .version so it's not a symlink, and includes the suffix. - # Do the meson utils, without modification. - '' - chmod u+w ./.version - echo ${version} > ../../../.version - '' # TEMP hack for Meson before make is gone, where # `src/nix-functional-tests` is during the transition a symlink and # not the actual directory directory. - + '' + '' cd $(readlink -e $PWD) echo $PWD | grep tests/functional ''; @@ -105,6 +99,8 @@ mkMesonDerivation ( } // lib.optionalAttrs (test-daemon != null) { + # TODO rename to _NIX_TEST_DAEMON_PACKAGE NIX_DAEMON_PACKAGE = test-daemon; + _NIX_TEST_CLIENT_VERSION = nix-cli.version; } )