Description: Collected Debian patches for xdg-utils
Author: Nicholas Guriev <guriev-ns@ya.ru>

The xdg-utils package is maintained in Git rather than maintaining
patches as separate files, and separating the patches doesn't seem to
be worth the effort.  They are therefore all included in this single
Debian patch.

For full commit history and separated commits, see the packaging Git
repository.

---

--- a/autotests/Makefile.in
+++ b/autotests/Makefile.in
@@ -17,8 +17,9 @@ autotest: test
 remove-failed-tests:
 	rm -f failed-tests
 
+export SHELL
 $(T): remove-failed-tests
-	@sh $@
+	@$(SHELL) $@
 
 clean: remove-failed-tests
 	rm -fr lab
--- a/autotests/t-xdg-open.sh
+++ b/autotests/t-xdg-open.sh
@@ -133,13 +133,6 @@ mock_desktop_file mosaic %u
 mock_default_app x-scheme-handler/http mosaic
 test_open_url generic mosaic
 
-test_that_it always uses \$BROWSER if set in generic mode
-BROWSER=cyberdog
-mock_desktop_file mosaic %u
-mock_default_app x-scheme-handler/http mosaic
-mock mosaic
-test_open_url generic cyberdog
-
 test_that_it works with multi-word \$BROWSER commands
 BROWSER="cyberdog --url %s"
 test_open_url generic cyberdog --url
@@ -150,6 +143,15 @@ mock cyberdog
 BROWSER="cyberdog --url %s"
 run generic xdg-open 'http://www.freedesktop.org/; echo BUSTED'
 assert_run cyberdog --url 'http://www.freedesktop.org/; echo BUSTED'
+unmock cyberdog
+
+test_that_it is not vulnerable to argument injection in URLs when using \
+             \$BROWSER in generic mode
+mock cyberdog
+BROWSER="cyberdog --url %s"
+run generic xdg-open 'http://www.freedesktop.org/   --evil-option'
+assert_run cyberdog --url 'http://www.freedesktop.org/   --evil-option'
+unmock cyberdog
 
 test_that_it opens files in generic mode
 test_generic_open_file test.txt
--- a/autotests/test-lib.sh
+++ b/autotests/test-lib.sh
@@ -140,6 +140,17 @@ Exec=$*
 EOF
 }
 
+mock_terminal_app() {
+    mock "$1"
+    cat > "$XDG_DATA_DIR/applications/$1.desktop" <<EOF
+[Desktop Entry]
+Type=Application
+Name=$1
+Exec=$*
+Terminal=true
+EOF
+}
+
 mock_default_app() {
     local mimetype="$1" app="$2"
     local mimeapps=$XDG_CONFIG_HOME/mimeapps.list
@@ -183,20 +194,23 @@ run() {
     local de="$1"
     shift
 
-    local cmd="$1"
-    shift
-
     : > $COMMANDS_RUN
 
     set_de_ $de
 
     local trace=
+    if [ "$DETACH" = 0 ]; then
+        trace="perl ./ttyon"
+    elif [ "$DETACH" = 1 ]; then
+        trace="perl ./ttyoff"
+    fi
+    trace="$trace ${SHELL:-/bin/sh}"
     if [ "$TRACE" = 1 ]; then
-        trace="sh -x"
+        trace="$trace -x"
     fi
 
     if [ "$TRACE" = 1 ] || [ "$TRACE_RUN" = 1 ]; then
-        echo "RUN [$de] $cmd $*" >&2
+        echo "RUN [$de] $*" >&2
     fi
 
     env -i \
@@ -213,7 +227,8 @@ run() {
         XDG_CONFIG_DIRS=$XDG_CONFIG_DIRS \
         DISPLAY=x \
         BROWSER="$BROWSER" \
-        $trace ../scripts/$cmd "$@" ||:
+        TERMINAL="$TERMINAL" \
+        $trace -c 'exec "$@"' - "$@" ||:
 }
 
 echo "* Testing that $COMMAND_TESTED"
--- /dev/null
+++ b/autotests/ttyoff
@@ -0,0 +1,84 @@
+#!/usr/bin/perl
+
+# ttyoff - run command detached from terminal
+#
+# Copyright 2020, Nicholas Guriev <guriev-ns@ya.ru>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+# OTHER DEALINGS IN THE SOFTWARE.
+
+=head1 NAME
+
+ttyoff - run command detached from terminal
+
+=head1 SYNOPSIS
+
+B<ttyoff> [B<-a> I<NAME>] [B<-s>] [I<COMMAND>...]
+
+=head1 DESCRIPTION
+
+Simple script that detaches itself from the controlling terminal and executes
+passed command. The script is primarily intended for running automated tests.
+
+If no command is specified, current Shell is executed.
+
+Options:
+
+=over
+
+=item B<-a>
+
+Override the zeroth argument of the command.
+
+=item B<-s>
+
+Before proceeding, close standard streams (numbered 0, 1, and 2).
+
+=back
+
+=head1 AUTHOR
+
+Written by Nicholas Guriev on New Year's Eve 2021.
+
+=head1 SEE ALSO
+
+tty(4)
+
+=cut
+
+
+use strict;
+use warnings;
+
+use Getopt::Std;
+BEGIN { require "sys/ioctl.ph" }
+
+$Getopt::Std::STANDARD_HELP_VERSION = 1;
+our ($opt_a, $opt_s);
+getopts("a:s") or exit 1;
+
+if (open my $term, "+<", "/dev/tty") {
+  ioctl $term, TIOCNOTTY, 0 or die $!;
+}
+if ($opt_s) {
+  close $_ or die $! for (*STDIN, *STDOUT, *STDERR);
+}
+unless (@ARGV) {
+  push @ARGV, $ENV{SHELL} || "/bin/sh";
+}
+exec { $opt_a or $ARGV[0] } @ARGV or die $!;
--- /dev/null
+++ b/autotests/ttyon
@@ -0,0 +1,130 @@
+#!/usr/bin/perl
+
+# ttyon - run command controlled by fake terminal
+#
+# Copyright 2021, Nicholas Guriev <guriev-ns@ya.ru>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+# OTHER DEALINGS IN THE SOFTWARE.
+
+=head1 NAME
+
+ttyon - run command controlled by fake terminal
+
+=head1 SYNOPSIS
+
+B<ttyon> [B<-a> I<NAME>] [B<-fs>] [I<COMMAND>...]
+
+=head1 DESCRIPTION
+
+Simple script that tries to open a fake controlling terminal and executes
+passed command. The script is primarily intended for running automated tests.
+
+If no command is specified, current Shell is executed.
+
+Options:
+
+=over
+
+=item B<-a>
+
+Override the zeroth argument of the command.
+
+=item B<-f>
+
+Never avoid wasted forks.
+
+=item B<-s>
+
+Connect standard streams (numbered 0, 1, and 2) to the opened terminal.
+
+=back
+
+=head1 AUTHOR
+
+Written by Nicholas Guriev on New Year's holidays 2021.
+
+=head1 SEE ALSO
+
+pts(4), ioctl_tty(2)
+
+=cut
+
+
+use strict;
+use warnings;
+
+use Getopt::Std;
+use Fcntl;
+use POSIX ();
+BEGIN { require "sys/ioctl.ph" }
+
+sub do_switch {
+  my $child = fork;
+  die $! unless defined $child;
+  if ($child) {
+    waitpid $child, 0 or die $!;
+    kill $? & 127, $$ if $? & 127;
+    POSIX::_exit $? >> 8;  # Perl's cleaning causes unwanted SIGHUP.
+  }
+}
+
+# Some constants from ioctl.ph have incorrect value due to missing %sizeof hash.
+# Apply a workaround suggested by Celelibi at https://bugs.debian.org/190887#26
+our %sizeof = (int => length pack "i!", 0);
+
+$Getopt::Std::STANDARD_HELP_VERSION = 1;
+our ($opt_a, $opt_f, $opt_s);
+getopts("a:fs") or exit 1;
+
+my $term;
+if ($opt_f or not open $term, "+<", "/dev/tty") {
+  # Become a session leader.
+  if ($opt_f or POSIX::setsid() < 0) {
+    do_switch;
+    POSIX::setsid() > 0 or die $!;
+  }
+
+  # Open a new terminal pair trough a multiplexor and treat its descriptor as
+  # system file to not auto-close it by master process.
+  local $^F = 3;
+  open $term, "+<", "/dev/ptmx" or die $!;
+
+  # Equivalent of unlockpt(3) which is not provided by the POSIX package.
+  my $buf = pack "i!", 0;
+  ioctl $term, TIOCSPTLCK, $buf or die $!;
+
+  # Set the new terminal as controlling of us.
+  ioctl $term, TIOCSCTTY, 0 or die $!;
+}
+do_switch if $opt_f;
+
+if ($opt_s and $term) {
+  for my $stream (*STDIN, *STDOUT, *STDERR) {
+    # Reopen via an equivalent of ptsname(3).
+    close $stream or die $!;
+    my $fd = ioctl $term, TIOCGPTPEER, O_RDWR or die $!;
+    open $stream, "+<&=", $fd or die $!;
+  }
+}
+close $term or die $! if $opt_f;
+
+unless (@ARGV) {
+  push @ARGV, $ENV{SHELL} || "/bin/sh";
+}
+exec { $opt_a or $ARGV[0] } @ARGV or die $!;
--- a/scripts/xdg-mime.in
+++ b/scripts/xdg-mime.in
@@ -306,6 +306,7 @@ make_default_generic()
     DEBUG 2 "make_default_generic $1 $2"
     DEBUG 1 "Updating $out_file"
     [ -f "$out_file" ] || touch "$out_file"
+    [ -d "$xdg_config_home" ] || mkdir -p "$xdg_config_home"
     awk -v mimetype="$2" -v application="$1" '
     BEGIN {
         prefix=mimetype "="
--- a/scripts/xdg-open.in
+++ b/scripts/xdg-open.in
@@ -420,13 +420,9 @@ open_generic_xdg_x_scheme_handler()
     fi
 }
 
-has_single_argument()
-{
-  test $# = 1
-}
-
 open_envvar()
 {
+    local url="$1"
     local oldifs="$IFS"
     local browser
 
@@ -439,14 +435,18 @@ open_envvar()
         fi
 
         if echo "$browser" | grep -q %s; then
-            # Avoid argument injection.
+            # Use loop to insert URL for avoid argument injection.
             # See https://bugs.freedesktop.org/show_bug.cgi?id=103807
             # URIs don't have IFS characters spaces anyway.
             # shellcheck disable=SC2086,SC2091,SC2059
             # All the scary things here are intentional
-            has_single_argument $1 && $(printf "$browser" "$1")
+            shift $#
+            for arg in $browser; do
+                set -- "$@" "$(printf -- "$arg" "$url")"
+            done
+            "$@"
         else
-            $browser "$1"
+            $browser "$url"
         fi
 
         if [ $? -eq 0 ]; then
--- a/scripts/xdg-screensaver.in
+++ b/scripts/xdg-screensaver.in
@@ -461,8 +461,9 @@ my $x = X11::Protocol->new();
 my $named_window_id = hex($window_id);
 my $window_name;
 while (1) {
-  ($window_name) = $x->GetProperty($named_window_id, $x->atom("WM_NAME"),
-				   $x->atom("STRING"), 0, 1000, 0);
+  eval { ($window_name) = $x->GetProperty($named_window_id, $x->atom("WM_NAME"),
+				   $x->atom("STRING"), 0, 1000, 0); };
+  $window_name = "?" if $@;
   last if defined($window_name) && $window_name ne "";
   (undef, $named_window_id) = $x->QueryTree($named_window_id);
   if (!defined($named_window_id)) {
