From 6bd7d4fb8bd2dcfa7f6ec1b97563f29147fca4c1 Mon Sep 17 00:00:00 2001
From: Don Armstrong <don@donarmstrong.com>
Date: Mon, 15 May 2017 08:34:22 -0700
Subject: [PATCH] add fix for #862667

---
 debian/changelog                      |  9 +++++++++
 debian/patches/die_on_unlink_failures | 28 +++++++++++++++++++++++++++
 debian/patches/series                 |  1 +
 3 files changed, 38 insertions(+)
 create mode 100644 debian/patches/die_on_unlink_failures

diff --git a/debian/changelog b/debian/changelog
index faf13191..deeb54a5 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,12 @@
+perltidy (20160302-1) unstable; urgency=medium
+
+  * New upstream release
+  * Die if an existing perltidy.ERR cannot be removed to block overwriting
+    of arbitrary files by a symlink attack. (closes: #862667) Thanks to
+    Jakub Wilk for identifying this issue.
+
+ --
+
 perltidy (20140328-1) unstable; urgency=medium
 
   * New upstream release
diff --git a/debian/patches/die_on_unlink_failures b/debian/patches/die_on_unlink_failures
new file mode 100644
index 00000000..c950d7e8
--- /dev/null
+++ b/debian/patches/die_on_unlink_failures
@@ -0,0 +1,28 @@
+Description: die if perltidy.ERR and other temporary files cannot be unlinked
+Origin: vendor, https://bugs.debian.org/862667
+Author: Don Armstrong <don@debian.org>
+--- a/lib/Perl/Tidy.pm
++++ b/lib/Perl/Tidy.pm
+@@ -3692,7 +3692,9 @@
+     # now wish for luck...
+     my $msg = qx/perl $flags $quoted_stream_filename $error_redirection/;
+ 
+-    unlink $stream_filename if ($is_tmpfile);
++    unlink $stream_filename or
++        Perl::Tidy::Die("couldn't unlink stream ${stream_filename}: $!\n")
++            if ($is_tmpfile);
+     return $stream_filename, $msg;
+ }
+ 
+@@ -4128,7 +4130,10 @@
+ 
+     # remove any old error output file if we might write a new one
+     unless ( $fh_warnings || ref($warning_file) ) {
+-        if ( -e $warning_file ) { unlink($warning_file) }
++        if ( -e $warning_file ) {
++            unlink($warning_file) or
++                Perl::Tidy::Die("couldn't unlink warning file ${warning_file}: $!\n");
++        }
+     }
+ 
+     my $logfile_gap =
diff --git a/debian/patches/series b/debian/patches/series
index 9b1049a4..a54562cc 100644
--- a/debian/patches/series
+++ b/debian/patches/series
@@ -1 +1,2 @@
+die_on_unlink_failures
 document_bst_better
-- 
2.39.5