Merge with 3.2: Issue #12841: Fix tarfile extraction of non-existent uids/gids.
diff --git a/Lib/tarfile.py b/Lib/tarfile.py
index 6bdbf36..2560562 100644
--- a/Lib/tarfile.py
+++ b/Lib/tarfile.py
@@ -2366,17 +2366,11 @@
             try:
                 g = grp.getgrnam(tarinfo.gname)[2]
             except KeyError:
-                try:
-                    g = grp.getgrgid(tarinfo.gid)[2]
-                except KeyError:
-                    g = os.getgid()
+                g = tarinfo.gid
             try:
                 u = pwd.getpwnam(tarinfo.uname)[2]
             except KeyError:
-                try:
-                    u = pwd.getpwuid(tarinfo.uid)[2]
-                except KeyError:
-                    u = os.getuid()
+                u = tarinfo.uid
             try:
                 if tarinfo.issym() and hasattr(os, "lchown"):
                     os.lchown(targetpath, u, g)
diff --git a/Misc/NEWS b/Misc/NEWS
index b15876b..16e0e40 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -271,6 +271,11 @@
 Library
 -------
 
+- Issue #12841: tarfile unnecessarily checked the existence of numerical user
+  and group ids on extraction. If one of them did not exist the respective id
+  of the current user (i.e. root) was used for the file and ownership
+  information was lost.
+
 - Issue #12888: Fix a bug in HTMLParser.unescape that prevented it to escape
   more than 128 entities.  Patch by Peter Otten.