From 90bb3d3a2bef9c2c56e730aaa45b279a07c73f7f Mon Sep 17 00:00:00 2001
From: Christoph Reiter <reiter.christoph@gmail.com>
Date: Tue, 28 Feb 2023 08:41:42 +0100
Subject: [PATCH 05/N] Remove everything related to sudo/fakeroot/file
 permissions

We don't have sudo or fakeroot in MSYS2 and file permissions
don't work the same.
---
 lib/libalpm/add.c                         |  2 +
 scripts/libmakepkg/executable/meson.build |  2 -
 scripts/makepkg.sh.in                     | 94 +++++++----------------
 scripts/pacman-key.sh.in                  |  7 +-
 src/pacman/check.c                        |  2 +
 src/pacman/pacman.c                       |  4 +
 test/pacman/pmtest.py                     | 15 ----
 7 files changed, 35 insertions(+), 91 deletions(-)

diff --git a/lib/libalpm/add.c b/lib/libalpm/add.c
index 6d245ba..e08ff84 100644
--- a/lib/libalpm/add.c
+++ b/lib/libalpm/add.c
@@ -266,6 +266,7 @@ static int extract_single_file(alpm_handle_t *handle, struct archive *archive,
 					"filesystem: %o  package: %o\n", filename, lsbuf.st_mode & mask,
 					entrymode & mask);
 		}
+#ifndef __MSYS__
 
 #if 0
 		/* Disable this warning until our user management in packages has improved.
@@ -283,6 +284,7 @@ static int extract_single_file(alpm_handle_t *handle, struct archive *archive,
 		}
 #endif
 
+#endif
 		_alpm_log(handle, ALPM_LOG_DEBUG, "extract: skipping dir extraction of %s\n",
 				filename);
 		archive_read_data_skip(archive);
diff --git a/scripts/libmakepkg/executable/meson.build b/scripts/libmakepkg/executable/meson.build
index 5be7227..f6474eb 100644
--- a/scripts/libmakepkg/executable/meson.build
+++ b/scripts/libmakepkg/executable/meson.build
@@ -4,13 +4,11 @@ sources = [
   'ccache.sh.in',
   'checksum.sh.in',
   'distcc.sh.in',
-  'fakeroot.sh.in',
   'debugedit.sh.in',
   'gpg.sh.in',
   'gzip.sh.in',
   'pacman.sh.in',
   'strip.sh.in',
-  'sudo.sh.in',
   'vcs.sh.in',
 ]
 
diff --git a/scripts/makepkg.sh.in b/scripts/makepkg.sh.in
index 6d65902..f49e902 100644
--- a/scripts/makepkg.sh.in
+++ b/scripts/makepkg.sh.in
@@ -26,7 +26,7 @@
 
 # makepkg uses quite a few external programs during its execution. You
 # need to have at least the following installed for makepkg to function:
-#   awk, bsdtar (libarchive), bzip2, coreutils, fakeroot, file, find (findutils),
+#   awk, bsdtar (libarchive), bzip2, coreutils, file, find (findutils),
 #   gettext, gpg, grep, gzip, sed, tput (ncurses), xz
 
 # gettext initialization
@@ -59,7 +59,6 @@ FORCE=0
 GENINTEG=0
 HOLDVER=0
 IGNOREARCH=0
-INFAKEROOT=0
 INSTALL=0
 LOGGING=0
 NEEDED=0
@@ -105,10 +104,9 @@ done
 trap_exit() {
 	local signal=$1; shift
 
-	if (( ! INFAKEROOT )); then
-		echo
-		error "$@"
-	fi
+	echo
+	error "$@"
+
 	[[ -n $srclinks ]] && rm -rf "$srclinks"
 
 	# unset the trap for this signal, and then call the default handler
@@ -123,11 +121,6 @@ trap_exit() {
 clean_up() {
 	local EXIT_CODE=$?
 
-	if (( INFAKEROOT )); then
-		# Don't clean up when leaving fakeroot, we're not done yet.
-		return 0
-	fi
-
 	if [[ -p $logpipe ]]; then
 		rm "$logpipe"
 	fi
@@ -182,11 +175,6 @@ clean_up() {
 	fi
 }
 
-enter_fakeroot() {
-	msg "$(gettext "Entering %s environment...")" "fakeroot"
-	fakeroot -- bash -$- "${BASH_SOURCE[0]}" -F "${ARGLIST[@]}" || exit $?
-}
-
 # Automatically update pkgver variable if a pkgver() function is provided
 # Re-sources the PKGBUILD afterwards to allow for other variables that use $pkgver
 update_pkgver() {
@@ -240,10 +228,6 @@ run_pacman() {
 			else
 				cmd=("${PACMAN_AUTH[@]}" "${cmd[@]}")
 			fi
-		elif type -p sudo >/dev/null; then
-			cmd=(sudo "${cmd[@]}")
-		else
-			cmd=(su root -c "$cmdescape")
 		fi
 		local lockfile="$(pacman-conf DBPath)/db.lck"
 		while [[ -f $lockfile ]]; do
@@ -491,7 +475,6 @@ write_pkginfo() {
 	generate_autodeps
 
 	printf "# Generated by makepkg %s\n" "$makepkg_version"
-	printf "# using %s\n" "$(fakeroot -v)"
 
 	write_kv_pair "pkgname" "$pkgname"
 	write_kv_pair "pkgbase" "$pkgbase"
@@ -947,12 +930,16 @@ if ! type -p gettext >/dev/null; then
 	gettext() {
 		printf "%s\n" "$@"
 	}
+else
+	gettext() {
+		/usr/bin/gettext "$@"
+	}
 fi
 
 ARGLIST=("$@")
 
 # Parse Command Line Options.
-OPT_SHORT="AcCdD:efFghiLmop:rRsSV"
+OPT_SHORT="AcCdD:efghiLmop:rRsSV"
 OPT_LONG=('allsource' 'check' 'clean' 'cleanbuild' 'config:' 'dir:' 'force' 'geninteg'
           'help' 'holdver' 'ignorearch' 'install' 'key:' 'log' 'noarchive' 'nobuild'
           'nocolor' 'nocheck' 'nodeps' 'noextract' 'noprepare' 'nosign' 'packagelist'
@@ -987,7 +974,6 @@ while true; do
 		-D|--dir)         shift; CHDIR=$1 ;;
 		-e|--noextract)   NOEXTRACT=1 ;;
 		-f|--force)       FORCE=1 ;;
-		-F)               INFAKEROOT=1 ;;
 		# generating integrity checks does not depend on architecture
 		-g|--geninteg)    BUILDPKG=0 GENINTEG=1 IGNOREARCH=1;;
 		--holdver)        HOLDVER=1 ;;
@@ -1032,7 +1018,7 @@ while [[ $1 ]]; do
 	shift
 done
 
-if (( ! INFAKEROOT )) &&  [[ -n $CHDIR ]]; then
+if [[ -n $CHDIR ]]; then
 	cd_safe "$CHDIR"
 fi
 
@@ -1109,19 +1095,6 @@ if (( LOGGING )) && ! ensure_writable_dir "LOGDEST" "$LOGDEST"; then
 	exit $E_FS_PERMISSIONS
 fi
 
-if (( ! INFAKEROOT )); then
-	if (( EUID == 0 )); then
-		error "$(gettext "Running %s as root is not allowed as it can cause permanent,\n\
-catastrophic damage to your system.")" "makepkg"
-		exit $E_ROOT
-	fi
-else
-	if [[ -z $FAKEROOTKEY ]]; then
-		error "$(gettext "Do not use the %s option. This option is only for internal use by %s.")" "'-F'" "makepkg"
-		exit $E_INVALID_OPTION
-	fi
-fi
-
 unset pkgname "${pkgbuild_schema_strings[@]}" "${pkgbuild_schema_arrays[@]}"
 unset "${known_hash_algos[@]/%/sums}"
 unset -f pkgver verify prepare build check package "${!package_@}"
@@ -1232,29 +1205,6 @@ if (( ! PKGVERFUNC )); then
 	check_build_status
 fi
 
-# Run the bare minimum in fakeroot
-if (( INFAKEROOT )); then
-	if (( SOURCEONLY )); then
-		create_srcpackage
-		msg "$(gettext "Leaving %s environment.")" "fakeroot"
-		exit $E_OK
-	fi
-
-	prepare_buildenv
-
-	chmod 755 "$pkgdirbase"
-	if (( ! SPLITPKG )); then
-		run_single_packaging
-	else
-		run_split_packaging
-	fi
-
-	create_debug_package
-
-	msg "$(gettext "Leaving %s environment.")" "fakeroot"
-	exit $E_OK
-fi
-
 # check we have the software required to process the PKGBUILD
 check_software || exit $E_MISSING_MAKEPKG_DEPS
 
@@ -1294,7 +1244,7 @@ if (( SOURCEONLY )); then
 	check_source_integrity all
 	cd_safe "$startdir"
 
-	enter_fakeroot
+	create_srcpackage
 
 	if [[ $SIGNPKG = 'y' ]]; then
 		msg "$(gettext "Signing package...")"
@@ -1401,17 +1351,25 @@ else
 		cd_safe "$startdir"
 	fi
 
-	enter_fakeroot
+	# if inhibiting archive creation, go no further
+	if (( NOARCHIVE )); then
+		msg "$(gettext "Package directory is ready.")"
+		exit $E_OK
+	fi
+	mkdir -p "$pkgdirbase"
+	chmod a-srwx "$pkgdirbase"
+	chmod 755 "$pkgdirbase"
+	if (( ! SPLITPKG )); then
+		run_single_packaging
+	else
+		run_split_packaging
+	fi
+
+	create_debug_package
 
 	create_package_signatures || exit $E_PRETTY_BAD_PRIVACY
 fi
 
-# if inhibiting archive creation, go no further
-if (( NOARCHIVE )); then
-	msg "$(gettext "Package directory is ready.")"
-	exit $E_OK
-fi
-
 msg "$(gettext "Finished making: %s")" "$pkgbase $basever ($(date +%c))"
 
 install_package && exit $E_OK || exit $E_INSTALL_FAILED
diff --git a/scripts/pacman-key.sh.in b/scripts/pacman-key.sh.in
index f68d076..405c095 100644
--- a/scripts/pacman-key.sh.in
+++ b/scripts/pacman-key.sh.in
@@ -266,7 +266,7 @@ check_keyring() {
 		exit 1
 	fi
 
-	if (( (EXPORT || FINGER || LIST || VERIFY) && EUID != 0 )); then
+	if (( EXPORT || FINGER || LIST || VERIFY )); then
 		if ! grep -q "^[[:space:]]*lock-never[[:space:]]*$" ${PACMAN_KEYRING_DIR}/gpg.conf &>/dev/null; then
 			error "$(gettext "You do not have sufficient permissions to run this command.")"
 			msg "$(gettext "Use '%s' to correct the keyring permissions.")" "pacman-key --init"
@@ -694,11 +694,6 @@ if ! type -p gpg >/dev/null; then
 	exit 1
 fi
 
-if (( (ADD || DELETE || EDITKEY || IMPORT || IMPORT_TRUSTDB || INIT || LSIGNKEY || POPULATE || RECEIVE || REFRESH || UPDATEDB) && EUID != 0 )); then
-	error "$(gettext "%s needs to be run as root for this operation.")" "pacman-key"
-	exit 1
-fi
-
 CONFIG=${CONFIG:-@sysconfdir@/pacman.conf}
 if [[ ! -r "${CONFIG}" ]]; then
 	error "$(gettext "%s configuration file '%s' not found.")" "pacman" "$CONFIG"
diff --git a/src/pacman/check.c b/src/pacman/check.c
index 6a39681..3d981c5 100644
--- a/src/pacman/check.c
+++ b/src/pacman/check.c
@@ -75,6 +75,7 @@ static int check_file_permissions(const char *pkgname, const char *filepath,
 	int errors = 0;
 	mode_t fsmode;
 
+#ifndef __MSYS__
 	/* uid */
 	if(st->st_uid != archive_entry_uid(entry)) {
 		errors++;
@@ -92,6 +93,7 @@ static int check_file_permissions(const char *pkgname, const char *filepath,
 					pkgname, filepath);
 		}
 	}
+#endif
 
 	/* mode */
 	fsmode = st->st_mode & (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
diff --git a/src/pacman/pacman.c b/src/pacman/pacman.c
index 6b64ffc..3a25442 100644
--- a/src/pacman/pacman.c
+++ b/src/pacman/pacman.c
@@ -1117,7 +1117,9 @@ static void cl_to_log(int argc, char *argv[])
 int main(int argc, char *argv[])
 {
 	int ret = 0;
+#ifndef __MSYS__
 	uid_t myuid = getuid();
+#endif
 
 	console_cursor_hide();
 	install_segv_handler();
@@ -1161,11 +1163,13 @@ int main(int argc, char *argv[])
 		cleanup(ret);
 	}
 
+#ifndef __MSYS__
 	/* check if we have sufficient permission for the requested operation */
 	if(myuid > 0 && needs_root()) {
 		pm_printf(ALPM_LOG_ERROR, _("you cannot perform this operation unless you are root.\n"));
 		cleanup(EXIT_FAILURE);
 	}
+#endif
 
 	/* we support reading targets from stdin if a cmdline parameter is '-' */
 	if(alpm_list_find_str(pm_targets, "-")) {
diff --git a/test/pacman/pmtest.py b/test/pacman/pmtest.py
index da2041b..47a7cf4 100644
--- a/test/pacman/pmtest.py
+++ b/test/pacman/pmtest.py
@@ -240,21 +240,6 @@ class pmtest(object):
         vprint("\tpacman %s" % self.args)
 
         cmd = []
-        if os.geteuid() != 0:
-            # fakechroot must be called before fakeroot due to potential
-            # potential interactions when wrapping the same C functions
-            fakechroot = util.which("fakechroot")
-            if not fakechroot:
-                tap.diag("WARNING: fakechroot not found!")
-            else:
-                cmd.append("fakechroot")
-
-            fakeroot = util.which("fakeroot")
-            if not fakeroot:
-                tap.diag("WARNING: fakeroot not found!")
-            else:
-                cmd.append("fakeroot")
-
         if pacman["gdb"]:
             cmd.extend(["libtool", "execute", "gdb", "--args"])
         if pacman["valgrind"]:
