Debian Codegraph @

texk/tests/TeXLive/TLUtils.pm

raw
1 # TeXLive::TLUtils.pm - the inevitable utilities for TeX Live.
2 # Copyright 2007-2025 Norbert Preining, Reinhard Kotucha
3 # This file is licensed under the GNU General Public License version 2
4 # or any later version.
5
6 use strict; use warnings;
7
8 package TeXLive::TLUtils;
9
10 my $svnrev = '$Revision: 74083 $';
11 my $_modulerevision = ($svnrev =~ m/: ([0-9]+) /) ? $1 : "unknown";
12 sub module_revision { return $_modulerevision; }
13
14 =pod
15
16 =head1 NAME
17
18 C<TeXLive::TLUtils> - TeX Live infrastructure miscellany
19
20 =head1 SYNOPSIS
21
22 use TeXLive::TLUtils;
23
24 =head2 Platform detection
25
26 TeXLive::TLUtils::platform();
27 TeXLive::TLUtils::platform_name($canonical_host);
28 TeXLive::TLUtils::platform_desc($platform);
29 TeXLive::TLUtils::wndws();
30 TeXLive::TLUtils::unix();
31
32 =head2 System tools
33
34 TeXLive::TLUtils::getenv($string);
35 TeXLive::TLUtils::which($string);
36 TeXLive::TLUtils::initialize_global_tmpdir();
37 TeXLive::TLUtils::tl_tmpdir();
38 TeXLive::TLUtils::tl_tmpfile();
39 TeXLive::TLUtils::xchdir($dir);
40 TeXLive::TLUtils::wsystem($msg,@args);
41 TeXLive::TLUtils::xsystem(@args);
42 TeXLive::TLUtils::run_cmd($cmd [, @envvars ]);
43 TeXLive::TLUtils::run_cmd_with_log($cmd, $logfn);
44 TeXLive::TLUtils::system_pipe($prog, $infile, $outfile, $removeIn, @args);
45 TeXLive::TLUtils::diskfree($path);
46 TeXLive::TLUtils::get_user_home();
47 TeXLive::TLUtils::expand_tilde($str);
48
49 =head2 File utilities
50
51 TeXLive::TLUtils::dirname($path);
52 TeXLive::TLUtils::basename($path);
53 TeXLive::TLUtils::dirname_and_basename($path);
54 TeXLive::TLUtils::tl_abs_path($path);
55 TeXLive::TLUtils::dir_writable($path);
56 TeXLive::TLUtils::dir_creatable($path);
57 TeXLive::TLUtils::mkdirhier($path);
58 TeXLive::TLUtils::rmtree($root, $verbose, $safe);
59 TeXLive::TLUtils::copy($file, $target_dir);
60 TeXLive::TLUtils::touch(@files);
61 TeXLive::TLUtils::collapse_dirs(@files);
62 TeXLive::TLUtils::all_dirs_and_removed_dirs(@files);
63 TeXLive::TLUtils::dirs_of_files(@files);
64 TeXLive::TLUtils::removed_dirs(@files);
65 TeXLive::TLUtils::download_file($path, $destination);
66 TeXLive::TLUtils::setup_programs($bindir, $platform);
67 TeXLive::TLUtils::tlcmp($file, $file);
68 TeXLive::TLUtils::nulldev();
69 TeXLive::TLUtils::get_full_line($fh);
70
71 =head2 Installer functions
72
73 TeXLive::TLUtils::make_var_skeleton($path);
74 TeXLive::TLUtils::make_local_skeleton($path);
75 TeXLive::TLUtils::create_fmtutil($tlpdb,$dest);
76 TeXLive::TLUtils::create_updmap($tlpdb,$dest);
77 TeXLive::TLUtils::create_language_dat($tlpdb,$dest,$localconf);
78 TeXLive::TLUtils::create_language_def($tlpdb,$dest,$localconf);
79 TeXLive::TLUtils::create_language_lua($tlpdb,$dest,$localconf);
80 TeXLive::TLUtils::time_estimate($totalsize, $donesize, $starttime)
81 TeXLive::TLUtils::install_packages($from_tlpdb,$media,$to_tlpdb,$what,$opt_src, $opt_doc, $retry, $continue);
82 TeXLive::TLUtils::do_postaction($how, $tlpobj, $do_fileassocs, $do_menu, $do_desktop, $do_script);
83 TeXLive::TLUtils::update_context_cache($plat_bindir);
84 TeXLive::TLUtils::announce_execute_actions($how, @executes, $what);
85 TeXLive::TLUtils::add_symlinks($root, $arch, $sys_bin, $sys_man, $sys_info);
86 TeXLive::TLUtils::remove_symlinks($root, $arch, $sys_bin, $sys_man, $sys_info);
87 TeXLive::TLUtils::w32_add_to_path($bindir, $multiuser);
88 TeXLive::TLUtils::w32_remove_from_path($bindir, $multiuser);
89 TeXLive::TLUtils::setup_persistent_downloads();
90
91 =head2 Logging and debugging
92
93 TeXLive::TLUtils::info($str1, ...); # output unless -q
94 TeXLive::TLUtils::debug($str1, ...); # output if -v
95 TeXLive::TLUtils::ddebug($str1, ...); # output if -vv
96 TeXLive::TLUtils::dddebug($str1, ...); # output if -vvv
97 TeXLive::TLUtils::log($str1, ...); # only to log file
98 TeXLive::TLUtils::tlwarn($str1, ...); # warn on stderr and log
99 TeXLive::TLUtils::tldie($str1, ...); # tlwarn and die
100 TeXLive::TLUtils::debug_hash_str($label, HASH); # stringified HASH
101 TeXLive::TLUtils::debug_hash($label, HASH); # warn stringified HASH
102 TeXLive::TLUtils::backtrace(); # return call stack as string
103 TeXLive::TLUtils::process_logging_options($texdir); # handle -q -v* -logfile
104
105 =head2 Miscellaneous
106
107 TeXLive::TLUtils::sort_uniq(@list);
108 TeXLive::TLUtils::push_uniq(\@list, @items);
109 TeXLive::TLUtils::member($item, @list);
110 TeXLive::TLUtils::merge_into(\%to, \%from);
111 TeXLive::TLUtils::texdir_check($texdir);
112 TeXLive::TLUtils::compare_tlpobjs($tlpA, $tlpB);
113 TeXLive::TLUtils::compare_tlpdbs($tlpdbA, $tlpdbB);
114 TeXLive::TLUtils::report_tlpdb_differences(\%ret);
115 TeXLive::TLUtils::tlnet_disabled_packages($root);
116 TeXLive::TLUtils::mktexupd();
117 TeXLive::TLUtils::setup_sys_user_mode($prg,$optsref,$tmfc,$tmfsc,$tmfv,$tmfsv);
118 TeXLive::TLUtils::prepend_own_path();
119 TeXLive::TLUtils::repository_to_array($str);
120
121 =head2 Windows and paths
122
123 TeXLive::TLUtils::quotify_path_with_spaces($path);
124 TeXLive::TLUtils::conv_to_w32_path($path);
125 TeXLive::TLUtils::native_slashify($internal_path);
126 TeXLive::TLUtils::forward_slashify($path_from_user);
127
128 =head2 CTAN
129
130 TeXLive::TLUtils::give_ctan_mirror();
131 TeXLive::TLUtils::give_ctan_mirror_base();
132
133 =head2 JSON
134
135 TeXLive::TLUtils::encode_json($ref);
136 TeXLive::TLUtils::True();
137 TeXLive::TLUtils::False();
138
139 =head1 DESCRIPTION
140
141 =cut
142
143 # avoid -warnings.
144 our $PERL_SINGLE_QUOTE; # we steal code from Text::ParseWords
145
146 # We use myriad global and package-global variables, unfortunately.
147 # To avoid "used only once" warnings, we must use the variable names again.
148 #
149 # This ugly repetition in the BEGIN block works with all Perl versions;
150 # cleaner/fancier ways of handling this don't.
151 BEGIN {
152 $::LOGFILE = $::LOGFILE;
153 $::LOGFILENAME = $::LOGFILENAME;
154 @::LOGLINES = @::LOGLINES;
155 @::debug_hook = @::debug_hook;
156 @::ddebug_hook = @::ddebug_hook;
157 @::dddebug_hook = @::dddebug_hook;
158 @::info_hook = @::info_hook;
159 @::install_packages_hook = @::install_packages_hook;
160 @::installation_failed_packages = @::installation_failed_packages;
161 @::warn_hook = @::warn_hook;
162 $::checksum_method = $::checksum_method;
163 $::gui_mode = $::gui_mode;
164 $::machinereadable = $::machinereadable;
165 $::no_execute_actions = $::no_execute_actions;
166 $::regenerate_all_formats = $::regenerate_all_formats;
167 $::context_cache_update_needed = $::context_cache_update_needed;
168 #
169 $JSON::false = $JSON::false;
170 $JSON::true = $JSON::true;
171 #
172 $TeXLive::TLDownload::net_lib_avail = $TeXLive::TLDownload::net_lib_avail;
173 }
174
175 ## A cleaner way is to use the "package PKGNAME BLOCK" syntax:
176 ## when providing a block to the package command, the scope is
177 ## limited to that block, so the current real package ends up unaffected.
178 ## Example in first reply to: https://perlmonks.org/?node_id=11139324
179 ## (Other solutions are also given there, but they don't work well in
180 ## our context here, although we use them elsewhere.)
181 ##
182 ## Unfortunately the package BLOCK syntax was invented for perl 5.14.0,
183 ## ca.2011, and OpenCSW on Solaris 10 only provides an older Perl. If we
184 ## ever drop Solaris 10 support, we can replace the above with this.
185 ##
186 #package main {
187 # our ($LOGFILE, $LOGFILENAME, @LOGLINES,
188 # @debug_hook, @ddebug_hook, @dddebug_hook, @info_hook,
189 # @install_packages_hook, @warn_hook,
190 # $checksum_method, $gui_mode, $machinereadable,
191 # $no_execute_actions, $regenerate_all_formats); }
192 #package JSON { our ($false, $true); }
193 #package TeXLive::TLDownload { our $net_lib_avail; }
194
195 BEGIN {
196 use Exporter ();
197 use vars qw(@ISA @EXPORT_OK @EXPORT);
198 @ISA = qw(Exporter);
199 @EXPORT_OK = qw(
200 &platform
201 &platform_name
202 &platform_desc
203 &unix
204 &getenv
205 &which
206 &initialize_global_tmpdir
207 &dirname
208 &basename
209 &dirname_and_basename
210 &tl_abs_path
211 &dir_writable
212 &dir_creatable
213 &mkdirhier
214 &rmtree
215 &copy
216 &touch
217 &collapse_dirs
218 &all_dirs_and_removed_dirs
219 &dirs_of_files
220 &removed_dirs
221 &install_package
222 &install_packages
223 &make_var_skeleton
224 &make_local_skeleton
225 &create_fmtutil
226 &create_updmap
227 &create_language_dat
228 &create_language_def
229 &create_language_lua
230 &parse_AddFormat_line
231 &parse_AddHyphen_line
232 &sort_uniq
233 &push_uniq
234 &texdir_check
235 &member
236 &quotewords
237 &quotify_path_with_spaces
238 &conv_to_w32_path
239 &native_slashify
240 &forward_slashify
241 &untar
242 &unpack
243 &merge_into
244 &give_ctan_mirror
245 &give_ctan_mirror_base
246 &create_mirror_list
247 &extract_mirror_entry
248 &system_ok
249 &wsystem
250 &xsystem
251 &run_cmd
252 &run_cmd_with_log
253 &system_pipe
254 &diskfree
255 &get_user_home
256 &expand_tilde
257 &announce_execute_actions
258 &add_symlinks
259 &remove_symlinks
260 &w32_add_to_path
261 &w32_remove_from_path
262 &tlcmp
263 &time_estimate
264 &compare_tlpobjs
265 &compare_tlpdbs
266 &report_tlpdb_differences
267 &setup_persistent_downloads
268 &mktexupd
269 &setup_sys_user_mode
270 &prepend_own_path
271 &nulldev
272 &get_full_line
273 &sort_archs
274 &repository_to_array
275 &encode_json
276 &True
277 &False
278 &SshURIRegex
279 );
280 @EXPORT = qw(setup_programs download_file process_logging_options
281 tldie tlwarn info log debug ddebug dddebug debug
282 debug_hash_str debug_hash
283 wndws xchdir xsystem run_cmd system_pipe sort_archs);
284 }
285
286 use Cwd;
287 use Getopt::Long;
288 use File::Temp;
289
290 use TeXLive::TLConfig;
291
292 $::opt_verbosity = 0; # see process_logging_options
293
294 our $SshURIRegex = '^((ssh|scp)://([^@]*)@([^/]*)/|([^@]*)@([^:]*):).*$';
295
296 =head2 Platform detection
297
298 =over 4
299
300 =item C<platform>
301
302 If C<$^O =~ /MSWin/i> is true we know that we're on
303 Windows and we set the global variable C<$::_platform_> to C<windows>.
304 Otherwise we call C<platform_name> with the output of C<config.guess>
305 as argument.
306
307 The result is stored in a global variable C<$::_platform_>, and
308 subsequent calls just return that value.
309
310 As of 2021, C<config.guess> unfortunately requires a shell that
311 understands the C<$(...)> construct. This means that on old-enough
312 systems, such as Solaris, we have to look for a shell. We use the value
313 of the C<CONFIG_SHELL> environment variable if it is set, else
314 C</bin/ksh> if it exists, else C</bin/bash> if it exists, else give up.
315 Happily, C<config.guess> later reverted this change, but we keep our
316 shell-finding code anyway to defend against future mistakes of the same ilk.
317
318 =cut
319
320 sub platform {
321 if (! defined $::_platform_) {
322 if ($^O =~ /^MSWin/i) {
323 # print STDERR "\$^O is $^O\n";
324 $::_platform_ = "windows";
325 } else {
326 my $config_guess = "$::installerdir/tlpkg/installer/config.guess";
327
328 # For example, if the disc or reader has hardware problems.
329 die "$0: config.guess script does not exist, goodbye: $config_guess"
330 if ! -r $config_guess;
331
332 # We cannot rely on #! in config.guess but have to call /bin/sh
333 # explicitly because sometimes the 'noexec' flag is set in
334 # /etc/fstab for ISO9660 file systems.
335 #
336 # In addition, config.guess was (unnecessarily) changed in 2020 by
337 # to use $(...) instead of `...`, although $(...) is not supported
338 # by Solaris /bin/sh (and others). The maintainers have declined
339 # to revert the change, so now every caller of config.guess must
340 # laboriously find a usable shell. Sigh.
341 #
342 my $config_shell = $ENV{"CONFIG_SHELL"} || "/bin/sh";
343 #
344 # check if $(...) is supported:
345 my $paren_cmdout = `'$config_shell' -c 'echo \$(echo foo)' 2>/dev/null`;
346 #warn "paren test out: `$paren_cmdout'.\n";
347 #
348 # The echo command might output a newline (maybe CRLF?) even if
349 # the $(...) fails, so don't just check for non-empty output.
350 # Maybe checking exit status would be better, but maybe not.
351 #
352 if (length ($paren_cmdout) <= 2) {
353 # if CONFIG_SHELL is set to something bad, give up.
354 if ($ENV{"CONFIG_SHELL"}) {
355 die <<END_BAD_CONFIG_SHELL;
356 $0: the CONFIG_SHELL environment variable is set to $ENV{CONFIG_SHELL}
357 but this cannot execute \$(...) shell constructs,
358 which is required. Set CONFIG_SHELL to something that works.
359 END_BAD_CONFIG_SHELL
360
361 } elsif (-x "/bin/ksh") {
362 $config_shell = "/bin/ksh";
363
364 } elsif (-x "/bin/bash") {
365 $config_shell = "/bin/bash";
366
367 } else {
368 die <<END_NO_PAREN_CMDS_SHELL
369 $0: can't find shell to execute $config_guess
370 (which gratuitously requires support for \$(...) command substitution).
371 Tried $config_shell, /bin/ksh, bin/bash.
372 Set the environment variable CONFIG_SHELL to specify explicitly.
373 END_NO_PAREN_CMDS_SHELL
374 }
375 }
376 #warn "executing config.guess with $config_shell\n";
377 chomp (my $guessed_platform = `'$config_shell' '$config_guess'`);
378
379 # If we didn't get anything usable, give up.
380 die "$0: could not run $config_guess, cannot proceed, sorry"
381 if ! $guessed_platform;
382
383 $::_platform_ = platform_name($guessed_platform);
384 }
385 }
386 return $::_platform_;
387 }
388
389
390 =item C<platform_name($canonical_host)>
391
392 Convert the C<$canonical_host> argument, a system description as
393 returned by C<config.guess>, into a TeX Live platform name, that is, a
394 name used as a subdirectory of our C<bin/> dir. Our names have the
395 form CPU-OS, for example, C<x86_64-linux>.
396
397 We need this because what's returned from C<config.,guess> does not
398 match our historical names, e.g., C<config.guess> returns C<linux-gnu>
399 but we need C<linux>.
400
401 The C<CPU> part of our name is always taken from the argument, with
402 various transformation.
403
404 For the C<OS> part, if the environment variable C<TEXLIVE_OS_NAME> is
405 set, it is used as-is. Otherwise we do our best to figure it out.
406
407 This function still handles old systems which are no longer supported,
408 just in case.
409
410 =cut
411
412 sub platform_name {
413 my ($orig_platform) = @_;
414 my $guessed_platform = $orig_platform;
415
416 # try to parse out some bsd variants that use amd64.
417 # We throw away everything after the "bsd" to elide version numbers,
418 # as in amd64-unknown-midnightbsd1.2.
419 $guessed_platform =~ s/^x86_64-(.*-k?)(free|net)bsd/amd64-$1$2bsd/;
420 my $CPU; # CPU type as reported by config.guess.
421 my $OS; # O/S type as reported by config.guess.
422 ($CPU = $guessed_platform) =~ s/(.*?)-.*/$1/;
423
424 $CPU =~ s/^alpha(.*)/alpha/; # alphaev whatever
425 $CPU =~ s/mips64el/mipsel/; # don't distinguish mips64 and 32 el
426 $CPU =~ s/powerpc64/powerpc/; # don't distinguish ppc64
427 $CPU =~ s/sparc64/sparc/; # don't distinguish sparc64
428
429 # armv6l-unknown-linux-gnueabihf -> armhf-linux (RPi)
430 # armv7l-unknown-linux-gnueabi -> armel-linux (Android)
431 if ($CPU =~ /^arm/) {
432 $CPU = $guessed_platform =~ /hf$/ ? "armhf" : "armel";
433 }
434
435 if ($ENV{"TEXLIVE_OS_NAME"}) {
436 $OS = $ENV{"TEXLIVE_OS_NAME"};
437 } else {
438 my @OSs = qw(aix cygwin darwin dragonfly freebsd hpux irix
439 kfreebsd linux midnightbsd netbsd openbsd solaris);
440 for my $os (@OSs) {
441 # Match word boundary at the beginning of the os name so that
442 # freebsd and kfreebsd are distinguished.
443 # Do not match word boundary at the end of the os so that
444 # solaris2 is matched.
445 $OS = $os if $guessed_platform =~ /\b$os/;
446 }
447 }
448
449 if (! $OS) {
450 warn "$0: could not guess OS from config.guess string: $orig_platform";
451 $OS = "unknownOS";
452 }
453
454 if ($OS eq "linux") {
455 # deal with the special case of musl based distributions
456 # config.guess returns
457 # x86_64-pc-linux-musl
458 # i386-pc-linux-musl
459 $OS = "linuxmusl" if $guessed_platform =~ /\blinux-musl/;
460 }
461
462 if ($OS eq "darwin") {
463 # We have two versions of Mac binary sets.
464 # 10.x and newer -> universal-darwin [MacTeX]
465 # 10.6/Snow Leopard through 10.x -> x86_64-darwinlegacy, if 64-bit.
466 # x changes every year. As of TL 2021 (Big Sur) Apple started with 11.x.
467 #
468 # (BTW, uname -r numbers are larger by 4 than the Mac minor version.
469 # We don't use uname numbers here.)
470 #
471 # this changes each year, per above:
472 my $mactex_darwin = 14; # lowest minor rev supported by universal-darwin.
473 #
474 # Most robust approach is apparently to check sw_vers (os version,
475 # returns "10.x" values), and sysctl (processor hardware).
476 chomp (my $sw_vers = `sw_vers -productVersion`);
477 my ($os_major,$os_minor) = split (/\./, $sw_vers);
478 if ($os_major < 10) {
479 warn "$0: only MacOSX is supported, not $OS $os_major.$os_minor "
480 . " (from sw_vers -productVersion: $sw_vers)\n";
481 return "unknownmac-unknownmac";
482 }
483 # have to refine after all 10.x become "legacy".
484 if ($os_major >= 11 || $os_minor >= $mactex_darwin) {
485 $CPU = "universal";
486 $OS = "darwin";
487 } elsif ($os_major == 10 && 6 <= $os_minor && $os_minor < $mactex_darwin){
488 # in between, x86 hardware only. On 10.6 only, must check if 64-bit,
489 # since if later than that, always 64-bit.
490 my $is64 = $os_minor == 6
491 ? `/usr/sbin/sysctl -n hw.cpu64bit_capable` >= 1
492 : 1;
493 if ($is64) {
494 $CPU = "x86_64";
495 $OS = "darwinlegacy";
496 } # if not 64-bit, default is ok (i386-darwin).
497 } else {
498 ; # older version, default is ok (i386-darwin, powerpc-darwin).
499 }
500
501 } elsif ($CPU =~ /^i.86$/) {
502 $CPU = "i386"; # 586, 686, whatever
503 }
504
505 if (! defined $OS) {
506 ($OS = $guessed_platform) =~ s/.*-(.*)/$1/;
507 }
508
509 return "$CPU-$OS";
510 }
511
512 =item C<platform_desc($platform)>
513
514 Return a string which describes a particular platform identifier, e.g.,
515 given C<i386-linux> we return C<Intel x86 with GNU/Linux>.
516
517 =cut
518
519 sub platform_desc {
520 my ($platform) = @_;
521
522 my %platform_name = (
523 'aarch64-linux' => 'GNU/Linux on ARM64',
524 'alpha-linux' => 'GNU/Linux on DEC Alpha',
525 'amd64-freebsd' => 'FreeBSD on x86_64',
526 'amd64-kfreebsd' => 'GNU/kFreeBSD on x86_64',
527 'amd64-midnightbsd'=> 'MidnightBSD on x86_64',
528 'amd64-netbsd' => 'NetBSD on x86_64',
529 'armel-linux' => 'GNU/Linux on ARM',
530 'armhf-linux' => 'GNU/Linux on RPi(32-bit) and ARMv7',
531 'hppa-hpux' => 'HP-UX',
532 'i386-cygwin' => 'Cygwin on Intel x86',
533 'i386-darwin' => 'MacOSX legacy (10.5-10.6) on Intel x86',
534 'i386-freebsd' => 'FreeBSD on Intel x86',
535 'i386-kfreebsd' => 'GNU/kFreeBSD on Intel x86',
536 'i386-linux' => 'GNU/Linux on Intel x86',
537 'i386-linuxmusl' => 'GNU/Linux on Intel x86 with musl',
538 'i386-netbsd' => 'NetBSD on Intel x86',
539 'i386-openbsd' => 'OpenBSD on Intel x86',
540 'i386-solaris' => 'Solaris on Intel x86',
541 'mips-irix' => 'SGI IRIX',
542 'mipsel-linux' => 'GNU/Linux on MIPSel',
543 'powerpc-aix' => 'AIX on PowerPC',
544 'powerpc-darwin' => 'MacOSX legacy (10.5) on PowerPC',
545 'powerpc-linux' => 'GNU/Linux on PowerPC',
546 'sparc-linux' => 'GNU/Linux on Sparc',
547 'sparc-solaris' => 'Solaris on Sparc',
548 'universal-darwin' => 'MacOSX current (10.14-) on ARM/x86_64',
549 'win32' => 'Windows (32-bit)',
550 'windows' => 'Windows (64-bit)',
551 'x86_64-cygwin' => 'Cygwin on x86_64',
552 'x86_64-darwinlegacy' => 'MacOSX legacy (10.6-) on x86_64',
553 'x86_64-dragonfly' => 'DragonFlyBSD on x86_64',
554 'x86_64-linux' => 'GNU/Linux on x86_64',
555 'x86_64-linuxmusl' => 'GNU/Linux on x86_64 with musl',
556 'x86_64-solaris' => 'Solaris on x86_64',
557 );
558
559 # the inconsistency between amd64-freebsd and x86_64-linux is
560 # unfortunate (it's the same hardware), but the os people say those
561 # are the conventional names on the respective os's, so we follow suit.
562
563 if (exists $platform_name{$platform}) {
564 return "$platform_name{$platform}";
565 } else {
566 my ($CPU,$OS) = split ('-', $platform);
567 $OS = "" if ! defined $OS; # e.g., -force-platform foo
568 return "$CPU with " . ucfirst "$OS";
569 }
570 }
571
572
573 =item C<wndws>
574
575 Return C<1> if platform is Windows and C<0> otherwise. The test is
576 currently based on the value of Perl's C<$^O> variable.
577
578 =cut
579
580 sub wndws {
581 if ($^O =~ /^MSWin/i) {
582 return 1;
583 } else {
584 return 0;
585 }
586 # the following needs config.guess, which is quite bad ...
587 # return (&platform eq "windows")? 1:0;
588 }
589
590
591 =item C<unix>
592
593 Return C<1> if platform is UNIX and C<0> otherwise.
594
595 =cut
596
597 sub unix {
598 return (&platform eq "windows")? 0:1;
599 }
600
601
602 =back
603
604 =head2 System Tools
605
606 =over 4
607
608 =item C<getenv($string)>
609
610 Get an environment variable. It is assumed that the environment
611 variable contains a path. On Windows all backslashes are replaced by
612 forward slashes as required by Perl. If this behavior is not desired,
613 use C<$ENV{"$variable"}> instead. C<0> is returned if the
614 environment variable is not set.
615
616 =cut
617
618 sub getenv {
619 my $envvar=shift;
620 my $var=$ENV{"$envvar"};
621 return 0 unless (defined $var);
622 if (&wndws) {
623 $var=~s!\\!/!g; # change \ -> / (required by Perl)
624 }
625 return "$var";
626 }
627
628
629 =item C<which($string)>
630
631 C<which> does the same as the UNIX command C<which(1)>, but it is
632 supposed to work on Windows too. On Windows we have to try all the
633 extensions given in the C<PATHEXT> environment variable. We also try
634 without appending an extension because if C<$string> comes from an
635 environment variable, an extension might already be present.
636
637 =cut
638
639 sub which {
640 my ($prog) = @_;
641 my @PATH;
642 my $PATH = getenv('PATH');
643
644 if (&wndws) {
645 my @PATHEXT = split (';', getenv('PATHEXT'));
646 push (@PATHEXT, ''); # in case argument contains an extension
647 @PATH = split (';', $PATH);
648 for my $dir (@PATH) {
649 for my $ext (@PATHEXT) {
650 if (-f "$dir/$prog$ext") {
651 return "$dir/$prog$ext";
652 }
653 }
654 }
655
656 } else { # not windows
657 @PATH = split (':', $PATH);
658 for my $dir (@PATH) {
659 if (-x "$dir/$prog") {
660 return "$dir/$prog";
661 }
662 }
663 }
664 return 0;
665 }
666
667 =item C<initialize_global_tmpdir();>
668
669 Initializes a directory for all temporary files. This uses C<File::Temp>
670 and thus honors various env variables like C<TMPDIR>, C<TMP>, and C<TEMP>.
671
672 =cut
673
674 sub initialize_global_tmpdir {
675 $::tl_tmpdir = File::Temp::tempdir(CLEANUP => 1);
676 ddebug("TLUtils::initialize_global_tmpdir: creating global tempdir $::tl_tmpdir\n");
677 return ($::tl_tmpdir);
678 }
679
680 =item C<tl_tmpdir>
681
682 Create a temporary directory which is removed when the program
683 is terminated.
684
685 =cut
686
687 sub tl_tmpdir {
688 initialize_global_tmpdir() if (!defined($::tl_tmpdir));
689 my $tmp = File::Temp::tempdir(DIR => $::tl_tmpdir, CLEANUP => 1);
690 ddebug("TLUtils::tl_tmpdir: creating tempdir $tmp\n");
691 return ($tmp);
692 }
693
694 =item C<tl_tmpfile>
695
696 Create a temporary file which is removed when the program
697 is terminated. Returns file handle and file name.
698 Arguments are passed on to C<File::Temp::tempfile>.
699
700 =cut
701
702 sub tl_tmpfile {
703 initialize_global_tmpdir() if (!defined($::tl_tmpdir));
704 my ($fh, $fn) = File::Temp::tempfile(@_, DIR => $::tl_tmpdir, UNLINK => 1);
705 ddebug("TLUtils::tl_tempfile: creating tempfile $fn\n");
706 return ($fh, $fn);
707 }
708
709
710 =item C<xchdir($dir)>
711
712 C<chdir($dir)> or die.
713
714 =cut
715
716 sub xchdir {
717 my ($dir) = @_;
718 chdir($dir) || die "$0: chdir($dir) failed: $!";
719 ddebug("xchdir($dir) ok\n");
720 }
721
722 =item C<system_ok($cmdline)>
723
724 Run C<system($cmdline)> and return true if return status was zero, false
725 if status was nonzero. Throw away stdout and stderr.
726
727 =cut
728
729 sub system_ok {
730 my $nulldev = nulldev();
731 my ($cmdline) = @_;
732 `$cmdline >$nulldev 2>&1`;
733 return $? == 0;
734 }
735
736 =item C<wsystem($msg, @args)>
737
738 Call C<info> about what is being done starting with C<$msg>, then run
739 C<system(@args)>; C<tlwarn> if unsuccessful and return the exit status.
740
741 =cut
742
743 sub wsystem {
744 my ($msg,@args) = @_;
745 info("$msg @args ...\n");
746 my $retval = system(@args);
747 if ($retval != 0) {
748 $retval /= 256 if $retval > 0;
749 tlwarn("$0: command failed (status $retval): @args: $!\n");
750 }
751 return $retval;
752 }
753
754
755 =item C<xsystem(@args)>
756
757 Call C<ddebug> about what is being done, then run C<system(@args)>, and
758 die if unsuccessful.
759
760 =cut
761
762 sub xsystem {
763 my (@args) = @_;
764 ddebug("running system(@args)\n");
765 my $retval = system(@args);
766 if ($retval != 0) {
767 $retval /= 256 if $retval > 0;
768 my $pwd = cwd ();
769 die "$0: system(@args) failed in $pwd, status $retval";
770 }
771 return $retval;
772 }
773
774 =item C<run_cmd($cmd, @envvars)>
775
776 Run shell command C<$cmd> and captures its standard output (not standard
777 error). Returns a list with CMD's output as the first element and its
778 return value (exit code) as second.
779
780 If given, C<@envvars> is a list of environment variable name / value
781 pairs set in C<%ENV> for the call and reset to their original value (or
782 unset if not defined initially).
783
784 =cut
785
786 sub run_cmd {
787 my $cmd = shift;
788 my %envvars = @_;
789 my %envvarsSetState;
790 my %envvarsValue;
791 for my $k (keys %envvars) {
792 $envvarsSetState{$k} = exists $ENV{$k};
793 $envvarsValue{$k} = $ENV{$k};
794 $ENV{$k} = $envvars{$k};
795 }
796 my $output = `$cmd`;
797 for my $k (keys %envvars) {
798 if ($envvarsSetState{$k}) {
799 $ENV{$k} = $envvarsValue{$k};
800 } else {
801 delete $ENV{$k};
802 }
803 }
804
805 $output = "" if ! defined ($output); # don't return undef
806
807 my $retval = $?;
808 if ($retval != 0) {
809 $retval /= 256 if $retval > 0;
810 }
811 return ($output,$retval);
812 }
813
814 =item C<run_cmd_with_log($cmd, $logfn)>
815
816 Run shell command C<$cmd> and captures both standard output and standard
817 error (as one string), passing them to C<$logfn>. The return value is
818 the exit status of C<$cmd>. Environment variable overrides cannot be
819 passed. (This is used for running special post-installation commands in
820 install-tl and tlmgr.)
821
822 The C<info> function is called to report what is happening.
823
824 =cut
825
826 sub run_cmd_with_log {
827 my ($cmd,$logfn) = @_;
828
829 info ("running $cmd ...");
830 my ($out,$ret) = TeXLive::TLUtils::run_cmd ("$cmd 2>&1");
831 if ($ret == 0) {
832 info ("done\n");
833 } else {
834 info ("failed\n");
835 tlwarn ("$0: $cmd failed (status $ret): $!\n");
836 $ret = 1;
837 }
838 &$logfn ($out); # log the output
839
840 return $ret;
841 } # run_cmd_with_log
842
843
844 =item C<system_pipe($prog, $infile, $outfile, $removeIn, @extraargs)>
845
846 Runs C<$prog> with C<@extraargs> redirecting stdin from C<$infile>,
847 stdout to C<$outfile>. Removes C<$infile> if C<$removeIn> is true.
848
849 =cut
850
851 sub system_pipe {
852 my ($prog, $infile, $outfile, $removeIn, @extraargs) = @_;
853
854 my $progQuote = quotify_path_with_spaces($prog);
855 if (wndws()) {
856 $infile =~ s!/!\\!g;
857 $outfile =~ s!/!\\!g;
858 }
859 my $infileQuote = "\"$infile\"";
860 my $outfileQuote = "\"$outfile\"";
861 debug("TLUtils::system_pipe: calling $progQuote @extraargs < $infileQuote > $outfileQuote\n");
862 my $retval = system("$progQuote @extraargs < $infileQuote > $outfileQuote");
863 if ($retval != 0) {
864 $retval /= 256 if $retval > 0;
865 debug("TLUtils::system_pipe: system exit code = $retval\n");
866 return 0;
867 } else {
868 if ($removeIn) {
869 debug("TLUtils::system_pipe: removing $infile\n");
870 unlink($infile);
871 }
872 return 1;
873 }
874 }
875
876 =item C<diskfree($path)>
877
878 If a POSIX compliant C<df> program is found, returns the number of Mb
879 free at C<$path>, otherwise C<-1>. If C<$path> does not exist, check
880 upwards for two levels for an existing parent, and if found, use it for
881 computing the disk space.
882
883 =cut
884
885 sub diskfree {
886 my $td = shift;
887 my ($output, $retval);
888 if (wndws()) {
889 # the powershell one-liner only works from win8 on.
890 my @winver = Win32::GetOSVersion();
891 if ($winver[1]<=6 && $winver[2]<=1) {
892 return -1;
893 }
894 my $avl;
895 if ($td =~ /^[a-zA-Z]:/) {
896 my $drv = substr($td,0,1);
897 # ea ignore: error action ignore: no output at all
898 my $cmd = "powershell -nologo -noninteractive -noprofile -command " .
899 "\"get-psdrive -name $drv -ea ignore |select-object free |format-wide\"";
900 ($output, $retval) = run_cmd($cmd);
901 # ignore exit code, just parse the output, which should
902 # consist of empty lines and a number surrounded by spaces
903 my @lines = split(/\r*\n/, $output);
904 foreach (@lines) {
905 chomp $_;
906 if ($_ !~ /^\s*$/) {
907 $_ =~ s/^\s*//;
908 $_ =~ s/\s*$//;
909 $avl = $_;
910 last;
911 }
912 }
913 if ($avl !~ /^[0-9]+$/) {
914 return (-1);
915 } else {
916 return (int($avl/(1024*1024)));
917 }
918 } else {
919 # maybe UNC drive; do not try to handle this
920 return -1;
921 }
922 }
923 # now windows case has been taken care of
924 return (-1) if (! $::progs{"df"});
925 # drop final /
926 $td =~ s!/$!!;
927 if (! -e $td) {
928 my $ptd = dirname($td);
929 if (-e $ptd) {
930 $td = $ptd;
931 } else {
932 my $pptd = dirname($ptd);
933 if (-e $pptd) {
934 $td = $pptd;
935 }
936 }
937 }
938 $td .= "/" if ($td !~ m!/$!);
939 return (-1) if (! -e $td);
940 debug("checking diskfree() in $td\n");
941 ($output, $retval) = run_cmd("df -Pk \"$td\"");
942 # With -k (mandated by POSIX), we should always get 1024-blocks.
943 # Otherwise, the POSIXLY_CORRECT envvar for GNU df would need to
944 # be set, to force 512-blocks; and the BLOCKSIZE envvar would need
945 # to be unset to avoid overriding.
946 if ($retval == 0) {
947 # Output format should be this:
948 # Filesystem 1024-blocks Used Available Capacity Mounted on
949 # /dev/sdb3 209611780 67718736 141893044 33% /
950 my ($h,$l) = split(/\n/, $output);
951 my ($fs, $nrb, $used, $avail, @rest) = split(' ', $l);
952 debug("diskfree: df -Pk output: $output");
953 debug("diskfree: used=$used (1024-block), avail=$avail (1024-block)\n");
954 # $avail is in 1024-byte blocks, so we divide by 1024 to obtain Mb.
955 return (int($avail / 1024));
956 } else {
957 # error in running df -P for whatever reason, just skip the check.
958 return (-1);
959 }
960 }
961
962 =item C<get_user_home()>
963
964 Returns the current user's home directory (C<$HOME> on Unix,
965 C<$USERPROFILE> on Windows, and C<~> if none of the two are
966 set. Save in package variable C<$user_home_dir> after computing.
967
968 =cut
969
970 # only search for home directory once, and save expansion here
971 my $user_home_dir;
972
973 sub get_user_home {
974 return $user_home_dir if ($user_home_dir);
975 $user_home_dir = getenv (wndws() ? 'USERPROFILE' : 'HOME') || '~';
976 return $user_home_dir;
977 }
978
979 =item C<expand_tilde($str)>
980
981 Expands initial C<~> with the user's home directory in C<$str> if
982 available, else leave C<~> in place.
983
984 =cut
985
986 sub expand_tilde {
987 my $str = shift;
988 my $h = get_user_home();
989 $str =~ s/^~/$h/;
990 return $str;
991 }
992
993 =back
994
995 =head2 File utilities
996
997 =over 4
998
999 =item C<dirname_and_basename($path)>
1000
1001 Return both C<dirname> and C<basename>. Example:
1002
1003 ($dirpart,$filepart) = dirname_and_basename ($path);
1004
1005 =cut
1006
1007 sub dirname_and_basename {
1008 my $path=shift;
1009 my ($share, $base) = ("", "");
1010 if (wndws()) {
1011 $path=~s!\\!/!g;
1012 }
1013 # do not try to make sense of paths ending with /..
1014 return (undef, undef) if $path =~ m!/\.\.$!;
1015 if ($path=~m!/!) { # dirname("foo/bar/baz") -> "foo/bar"
1016 # eliminate `/.' path components
1017 while ($path =~ s!/\./!/!) {};
1018 # UNC path? => first split in $share = //xxx/yy and $path = /zzzz
1019 if (wndws() and $path =~ m!^(//[^/]+/[^/]+)(.*)$!) {
1020 ($share, $path) = ($1, $2);
1021 if ($path =~ m!^/?$!) {
1022 $path = $share;
1023 $base = "";
1024 } elsif ($path =~ m!(/.*)/(.*)!) {
1025 $path = $share.$1;
1026 $base = $2;
1027 } else {
1028 $base = $path;
1029 $path = $share;
1030 }
1031 return ($path, $base);
1032 }
1033 # not a UNC path
1034 $path=~m!(.*)/(.*)!; # works because of greedy matching
1035 return ((($1 eq '') ? '/' : $1), $2);
1036 } else { # dirname("ignore") -> "."
1037 return (".", $path);
1038 }
1039 }
1040
1041
1042 =item C<dirname($path)>
1043
1044 Return C<$path> with its trailing C</component> removed.
1045
1046 =cut
1047
1048 sub dirname {
1049 my $path = shift;
1050 my ($dirname, $basename) = dirname_and_basename($path);
1051 return $dirname;
1052 }
1053
1054
1055 =item C<basename($path)>
1056
1057 Return C<$path> with any leading directory components removed.
1058
1059 =cut
1060
1061 sub basename {
1062 my $path = shift;
1063 my ($dirname, $basename) = dirname_and_basename($path);
1064 return $basename;
1065 }
1066
1067
1068 =item C<tl_abs_path($path)>
1069
1070 # Other than Cwd::abs_path, tl_abs_path also works if the argument does not
1071 # yet exist as long as the path does not contain '..' components.
1072
1073 =cut
1074
1075 sub tl_abs_path {
1076 my $path = shift;
1077 if (wndws()) {
1078 $path=~s!\\!/!g;
1079 }
1080 if (-e $path) {
1081 $path = Cwd::abs_path($path);
1082 } elsif ($path eq '.') {
1083 $path = Cwd::getcwd();
1084 } else{
1085 # collapse /./ components
1086 $path =~ s!/\./!/!g;
1087 # no support for .. path components or for windows long-path syntax
1088 # (//?/ path prefix)
1089 die "Unsupported path syntax" if $path =~ m!/\.\./! || $path =~ m!/\.\.$!
1090 || $path =~ m!^\.\.!;
1091 die "Unsupported path syntax" if wndws() && $path =~ m!^//\?/!;
1092 if ($path !~ m!^(.:)?/!) { # relative path
1093 if (wndws() && $path =~ /^.:/) { # drive letter
1094 my $dcwd;
1095 # starts with drive letter: current dir on drive
1096 $dcwd = Cwd::getdcwd ($1);
1097 $dcwd .= '/' unless $dcwd =~ m!/$!;
1098 return $dcwd.$path;
1099 } else { # relative path without drive letter
1100 my $cwd = Cwd::getcwd();
1101 $cwd .= '/' unless $cwd =~ m!/$!;
1102 return $cwd . $path;
1103 }
1104 } # else absolute path
1105 }
1106 $path =~ s!/$!! unless $path =~ m!^(.:)?/$!;
1107 return $path;
1108 }
1109
1110
1111 =item C<dir_creatable($path)>
1112
1113 Tests whether its argument is a directory where we can create a directory.
1114
1115 =cut
1116
1117 sub dir_slash {
1118 my $d = shift;
1119 $d = "$d/" unless $d =~ m!/!;
1120 return $d;
1121 }
1122
1123 # test whether subdirectories can be created in the argument
1124 sub dir_creatable {
1125 my $path=shift;
1126 #print STDERR "testing $path\n";
1127 $path =~ s!\\!/!g if wndws;
1128 return 0 unless -d $path;
1129 $path .= '/' unless $path =~ m!/$!;
1130 #print STDERR "testing $path\n";
1131 my $d;
1132 for my $i (1..100) {
1133 $d = "";
1134 # find a non-existent dirname
1135 $d = $path . int(rand(1000000));
1136 last unless -e $d;
1137 }
1138 if (!$d) {
1139 tlwarn("Cannot find available testdir name\n");
1140 return 0;
1141 }
1142 #print STDERR "creating $d\n";
1143 return 0 unless mkdir $d;
1144 return 0 unless -d $d;
1145 rmdir $d;
1146 return 1;
1147 }
1148
1149
1150 =item C<dir_writable($path)>
1151
1152 Tests whether its argument is writable by trying to write to
1153 it. This function is necessary because the built-in C<-w> test just
1154 looks at mode and uid/gid, which on Windows always returns true and
1155 even on Unix is not always good enough for directories mounted from
1156 a fileserver.
1157
1158 =cut
1159
1160 # The Unix test gives the wrong answer when used under Windows Vista
1161 # with one of the `virtualized' directories such as Program Files:
1162 # lacking administrative permissions, it would write successfully to
1163 # the virtualized Program Files rather than fail to write to the
1164 # real Program Files. Ugh.
1165
1166 sub dir_writable {
1167 my ($path) = @_;
1168 return 0 unless -d $path;
1169 $path =~ s!\\!/!g if wndws;
1170 $path .= '/' unless $path =~ m!/$!;
1171 my $i = 0;
1172 my $f;
1173 for my $i (1..100) {
1174 $f = "";
1175 # find a non-existent filename
1176 $f = $path . int(rand(1000000));
1177 last unless -e $f;
1178 }
1179 if (!$f) {
1180 tlwarn("Cannot find available testfile name\n");
1181 return 0;
1182 }
1183 return 0 if ! open (TEST, ">$f");
1184 my $written = 0;
1185 $written = (print TEST "\n");
1186 close (TEST);
1187 unlink ($f);
1188 return $written;
1189 }
1190
1191
1192 =item C<mkdirhier($path, [$mode])>
1193
1194 The function C<mkdirhier> does the same as the UNIX command C<mkdir -p>.
1195 It behaves differently depending on the context in which it is called:
1196 If called in void context it will die on failure. If called in
1197 scalar context, it will return 1/0 on sucess/failure. If called in
1198 list context, it returns 1/0 as first element and an error message
1199 as second, if an error occurred (and no second element in case of
1200 success). The optional parameter sets the permission bits.
1201
1202 =cut
1203
1204 sub mkdirhier {
1205 my ($tree,$mode) = @_;
1206 my $ret = 1;
1207 my $reterror;
1208
1209 if (-d "$tree") {
1210 $ret = 1;
1211 } else {
1212 my $subdir = "";
1213 # windows is special as usual: we need to separate //servername/ part
1214 # from the UNC path, since (! -d //servername/) tests true
1215 $subdir = $& if ( wndws() && ($tree =~ s!^//[^/]+/!!) );
1216
1217 my @dirs = split (/[\/\\]/, $tree);
1218 for my $dir (@dirs) {
1219 $subdir .= "$dir/";
1220 if (! -d $subdir) {
1221 if (defined $mode) {
1222 if (! mkdir ($subdir, $mode)) {
1223 $ret = 0;
1224 $reterror = "mkdir($subdir,$mode) failed: $!";
1225 last;
1226 }
1227 } else {
1228 if (! mkdir ($subdir)) {
1229 $ret = 0;
1230 $reterror = "mkdir($subdir) failed for tree $tree: $!";
1231 last;
1232 }
1233 }
1234 }
1235 }
1236 }
1237 if ($ret) {
1238 return(1); # nothing bad here returning 1 in any case, will
1239 # be ignored in void context, and give 1 in list context
1240 } else {
1241 if (wantarray) {
1242 return(0, $reterror);
1243 } elsif (defined wantarray) {
1244 return(0);
1245 } else {
1246 die "$0: $reterror";
1247 }
1248 }
1249 }
1250
1251
1252 =item C<rmtree($root, $verbose, $safe)>
1253
1254 The C<rmtree> function provides a convenient way to delete a
1255 subtree from the directory structure, much like the Unix command C<rm -r>.
1256 C<rmtree> takes three arguments:
1257
1258 =over 4
1259
1260 =item *
1261
1262 the root of the subtree to delete, or a reference to
1263 a list of roots. All of the files and directories
1264 below each root, as well as the roots themselves,
1265 will be deleted.
1266
1267 =item *
1268
1269 a boolean value, which if TRUE will cause C<rmtree> to
1270 print a message each time it examines a file, giving the
1271 name of the file, and indicating whether it's using C<rmdir>
1272 or C<unlink> to remove it, or that it's skipping it.
1273 (defaults to FALSE)
1274
1275 =item *
1276
1277 a boolean value, which if TRUE will cause C<rmtree> to
1278 skip any files to which you do not have delete access
1279 (if running under VMS) or write access (if running
1280 under another OS). This will change in the future when
1281 a criterion for 'delete permission' under OSs other
1282 than VMS is settled. (defaults to FALSE)
1283
1284 =back
1285
1286 It returns the number of files successfully deleted. Symlinks are
1287 simply deleted and not followed.
1288
1289 B<NOTE:> There are race conditions internal to the implementation of
1290 C<rmtree> making it unsafe to use on directory trees which may be
1291 altered or moved while C<rmtree> is running, and in particular on any
1292 directory trees with any path components or subdirectories potentially
1293 writable by untrusted users.
1294
1295 Additionally, if the third parameter is not TRUE and C<rmtree> is
1296 interrupted, it may leave files and directories with permissions altered
1297 to allow deletion (and older versions of this module would even set
1298 files and directories to world-read/writable!)
1299
1300 Note also that the occurrence of errors in C<rmtree> can be determined I<only>
1301 by trapping diagnostic messages using C<$SIG{__WARN__}>; it is not apparent
1302 from the return value.
1303
1304 =cut
1305
1306 #taken from File/Path.pm
1307 #
1308 my $Is_VMS = $^O eq 'VMS';
1309 my $Is_MacOS = $^O eq 'MacOS';
1310
1311 # These OSes complain if you want to remove a file that you have no
1312 # write permission to:
1313 my $force_writeable = ($^O eq 'os2' || $^O eq 'dos' || $^O eq 'MSWin32' ||
1314 $^O eq 'amigaos' || $^O eq 'MacOS' || $^O eq 'epoc');
1315
1316 sub rmtree {
1317 my($roots, $verbose, $safe) = @_;
1318 my(@files);
1319 my($count) = 0;
1320 $verbose ||= 0;
1321 $safe ||= 0;
1322
1323 if ( defined($roots) && length($roots) ) {
1324 $roots = [$roots] unless ref $roots;
1325 } else {
1326 warn "No root path(s) specified";
1327 return 0;
1328 }
1329
1330 my($root);
1331 foreach $root (@{$roots}) {
1332 if ($Is_MacOS) {
1333 $root = ":$root" if $root !~ /:/;
1334 $root =~ s#([^:])\z#$1:#;
1335 } else {
1336 $root =~ s#/\z##;
1337 }
1338 (undef, undef, my $rp) = lstat $root or next;
1339 $rp &= 07777; # don't forget setuid, setgid, sticky bits
1340 if ( -d _ ) {
1341 # notabene: 0700 is for making readable in the first place,
1342 # it's also intended to change it to writable in case we have
1343 # to recurse in which case we are better than rm -rf for
1344 # subtrees with strange permissions
1345 chmod($rp | 0700, ($Is_VMS ? VMS::Filespec::fileify($root) : $root))
1346 or warn "Can't make directory $root read+writeable: $!"
1347 unless $safe;
1348
1349 if (opendir my $d, $root) {
1350 no strict 'refs';
1351 if (!defined ${"\cTAINT"} or ${"\cTAINT"}) {
1352 # Blindly untaint dir names
1353 @files = map { /^(.*)$/s ; $1 } readdir $d;
1354 } else {
1355 @files = readdir $d;
1356 }
1357 closedir $d;
1358 } else {
1359 warn "Can't read $root: $!";
1360 @files = ();
1361 }
1362 # Deleting large numbers of files from VMS Files-11 filesystems
1363 # is faster if done in reverse ASCIIbetical order
1364 @files = reverse @files if $Is_VMS;
1365 ($root = VMS::Filespec::unixify($root)) =~ s#\.dir\z## if $Is_VMS;
1366 if ($Is_MacOS) {
1367 @files = map("$root$_", @files);
1368 } else {
1369 @files = map("$root/$_", grep $_!~/^\.{1,2}\z/s,@files);
1370 }
1371 $count += rmtree(\@files,$verbose,$safe);
1372 if ($safe &&
1373 ($Is_VMS ? !&VMS::Filespec::candelete($root) : !-w $root)) {
1374 print "skipped $root\n" if $verbose;
1375 next;
1376 }
1377 chmod $rp | 0700, $root
1378 or warn "Can't make directory $root writeable: $!"
1379 if $force_writeable;
1380 print "rmdir $root\n" if $verbose;
1381 if (rmdir $root) {
1382 ++$count;
1383 } else {
1384 warn "Can't remove directory $root: $!";
1385 chmod($rp, ($Is_VMS ? VMS::Filespec::fileify($root) : $root))
1386 or warn("and can't restore permissions to "
1387 . sprintf("0%o",$rp) . "\n");
1388 }
1389 } else {
1390 if ($safe &&
1391 ($Is_VMS ? !&VMS::Filespec::candelete($root)
1392 : !(-l $root || -w $root)))
1393 {
1394 print "skipped $root\n" if $verbose;
1395 next;
1396 }
1397 chmod $rp | 0600, $root
1398 or warn "Can't make file $root writeable: $!"
1399 if $force_writeable;
1400 print "unlink $root\n" if $verbose;
1401 # delete all versions under VMS
1402 for (;;) {
1403 unless (unlink $root) {
1404 warn "Can't unlink file $root: $!";
1405 if ($force_writeable) {
1406 chmod $rp, $root
1407 or warn("and can't restore permissions to "
1408 . sprintf("0%o",$rp) . "\n");
1409 }
1410 last;
1411 }
1412 ++$count;
1413 last unless $Is_VMS && lstat $root;
1414 }
1415 }
1416 }
1417 $count;
1418 }
1419
1420
1421 =item C<copy($file, $target_dir)>
1422
1423 =item C<copy("-f", $file, $destfile)>
1424
1425 =item C<copy("-L", $file, $destfile)>
1426
1427 Copy file C<$file> to directory C<$target_dir>, or to the C<$destfile>
1428 if the first argument is C<"-f">. No external programs are involved.
1429 Since we need C<sysopen()>, the Perl module C<Fcntl.pm> is required. The
1430 time stamps are preserved and symlinks are created on Unix systems. On
1431 Windows, C<(-l $file)> will never return 'C<true>' and so symlinks will
1432 be (uselessly) copied as regular files.
1433
1434 If the first argument is C<"-L"> and C<$file> is a symlink, the link is
1435 dereferenced before the copying is done. (If both C<"-f"> and C<"-L">
1436 are desired, they must be given in that order, although the codebase
1437 currently has no need to do this.)
1438
1439 C<copy> invokes C<mkdirhier> if target directories do not exist. Files
1440 start with mode C<0777> if they are executable and C<0666> otherwise,
1441 with the set bits in I<umask> cleared in each case.
1442
1443 C<$file> can begin with a C<file:/> prefix.
1444
1445 If C<$file> is not readable, we return without copying anything. (This
1446 can happen when the database and files are not in perfect sync.) On the
1447 other file, if the destination is not writable, or the writing fails,
1448 that is a fatal error.
1449
1450 =cut
1451
1452 sub copy {
1453 #too verbose ddebug("TLUtils::copy(", join (",", @_), "\n");
1454 my $infile = shift;
1455 my $filemode = 0;
1456 my $dereference = 0;
1457 if ($infile eq "-f") { # second argument is a file
1458 $filemode = 1;
1459 $infile = shift;
1460 }
1461 if ($infile eq "-L") {
1462 $dereference = 1;
1463 $infile = shift;
1464 }
1465 my $destdir=shift;
1466
1467 # while we're trying to figure out the versioned containers.
1468 #debug("copy($infile, $destdir, filemode=$filemode)\n");
1469 #debug("copy: backtrace:\n", backtrace(), "copy: end backtrace\n");
1470
1471 my $outfile;
1472 my @stat;
1473 my $mode;
1474 my $buffer;
1475 my $offset;
1476 my $filename;
1477 my $dirmode = 0755;
1478 my $blocksize = $TeXLive::TLConfig::BlockSize;
1479
1480 $infile =~ s!^file://*!/!i; # remove file:/ url prefix
1481 $filename = basename "$infile";
1482 if ($filemode) {
1483 # given a destination file
1484 $outfile = $destdir;
1485 $destdir = dirname($outfile);
1486 } else {
1487 $outfile = "$destdir/$filename";
1488 }
1489
1490 if (! -d $destdir) {
1491 my ($ret,$err) = mkdirhier ($destdir);
1492 die "mkdirhier($destdir) failed: $err\n" if ! $ret;
1493 }
1494
1495 # if we should dereference, change $infile to refer to the link target.
1496 if (-l $infile && $dereference) {
1497 my $linktarget = readlink($infile);
1498 # The symlink target should always be relative, and we need to
1499 # prepend the directory containing the link in that case.
1500 # (Although it should never happen, if the symlink target happens
1501 # to already be absolute, do not prepend.)
1502 if ($linktarget !~ m,^/,) {
1503 $infile = Cwd::abs_path(dirname($infile)) . "/$linktarget";
1504 }
1505 ddebug("TLUtils::copy: dereferencing symlink $infile -> $linktarget");
1506 }
1507
1508 if (-l $infile) {
1509 my $linktarget = readlink($infile);
1510 my $dest = "$destdir/$filename";
1511 ddebug("TLUtils::copy: doing symlink($linktarget,$dest)"
1512 . " [from readlink($infile)]\n");
1513 symlink($linktarget, $dest) || die "symlink($linktarget,$dest) failed: $!";
1514 } else {
1515 if (! open (IN, $infile)) {
1516 warn "open($infile) failed, not copying: $!";
1517 return;
1518 }
1519 binmode IN;
1520
1521 $mode = (-x $infile) ? oct("0777") : oct("0666");
1522 $mode &= ~umask;
1523
1524 open (OUT, ">$outfile") || die "open(>$outfile) failed: $!";
1525 binmode OUT;
1526
1527 chmod ($mode, $outfile) || warn "chmod($mode,$outfile) failed: $!";
1528
1529 while (my $read = sysread (IN, $buffer, $blocksize)) {
1530 die "read($infile) failed: $!" unless defined $read;
1531 $offset = 0;
1532 while ($read) {
1533 my $written = syswrite (OUT, $buffer, $read, $offset);
1534 die "write($outfile) failed: $!" unless defined $written;
1535 $read -= $written;
1536 $offset += $written;
1537 }
1538 }
1539 close (OUT) || warn "close($outfile) failed: $!";
1540 close (IN) || warn "close($infile) failed: $!";;
1541 @stat = lstat ($infile);
1542 die "lstat($infile) failed: $!" if ! @stat;
1543 utime ($stat[8], $stat[9], $outfile);
1544 }
1545 }
1546
1547
1548 =item C<touch(@files)>
1549
1550 Update modification and access time of C<@files>. Non-existent files
1551 are created.
1552
1553 =cut
1554
1555 sub touch {
1556 my @files=@_;
1557
1558 foreach my $file (@_) {
1559 if (-e $file) {
1560 utime time, time, $file;
1561 } else {
1562 if (open( TMP, ">$file")) {
1563 close(TMP);
1564 } else {
1565 warn "Can't create file $file: $!\n";
1566 }
1567 }
1568 }
1569 }
1570
1571
1572 =item C<collapse_dirs(@files)>
1573
1574 Return a (more or less) minimal list of directories and files, given an
1575 original list of files C<@files>. That is, if every file within a given
1576 directory is included in C<@files>, replace all of those files with the
1577 absolute directory name in the return list. Any files which have
1578 sibling files not included are retained and made absolute.
1579
1580 We try to walk up the tree so that the highest-level directory
1581 containing only directories or files that are in C<@files> is returned.
1582 (This logic may not be perfect, though.)
1583
1584 This is not just a string function; we check for other directory entries
1585 existing on disk within the directories of C<@files>. Therefore, if the
1586 entries are relative pathnames, the current directory must be set by the
1587 caller so that file tests work.
1588
1589 As mentioned above, the returned list is absolute paths to directories
1590 and files.
1591
1592 For example, suppose the input list is
1593
1594 dir1/subdir1/file1
1595 dir1/subdir2/file2
1596 dir1/file3
1597
1598 If there are no other entries under C<dir1/>, the result will be
1599 C</absolute/path/to/dir1>.
1600
1601 =cut
1602
1603 sub collapse_dirs {
1604 my (@files) = @_;
1605 my @ret = ();
1606 my %by_dir;
1607
1608 # construct hash of all directories mentioned, values are lists of the
1609 # files in that directory.
1610 for my $f (@files) {
1611 my $abs_f = Cwd::abs_path ($f);
1612 die ("oops, no abs_path($f) from " . `pwd`) unless $abs_f;
1613 (my $d = $abs_f) =~ s,/[^/]*$,,;
1614 my @a = exists $by_dir{$d} ? @{$by_dir{$d}} : ();
1615 push (@a, $abs_f);
1616 $by_dir{$d} = \@a;
1617 }
1618
1619 # for each of our directories, see if we are given everything in
1620 # the directory. if so, return the directory; else return the
1621 # individual files.
1622 for my $d (sort keys %by_dir) {
1623 opendir (DIR, $d) || die "opendir($d) failed: $!";
1624 my @dirents = readdir (DIR);
1625 closedir (DIR) || warn "closedir($d) failed: $!";
1626
1627 # initialize test hash with all the files we saw in this dir.
1628 # (These idioms are due to "Finding Elements in One Array and Not
1629 # Another" in the Perl Cookbook.)
1630 my %seen;
1631 my @rmfiles = @{$by_dir{$d}};
1632 @seen{@rmfiles} = ();
1633
1634 # see if everything is the same.
1635 my $ok_to_collapse = 1;
1636 for my $dirent (@dirents) {
1637 next if $dirent =~ /^\.(\.|svn)?$/; # ignore . .. .svn
1638
1639 my $item = "$d/$dirent"; # prepend directory for comparison
1640 if (! exists $seen{$item}) {
1641 ddebug(" no collapse of $d because of: $dirent\n");
1642 $ok_to_collapse = 0;
1643 last; # no need to keep looking after the first.
1644 }
1645 }
1646
1647 push (@ret, $ok_to_collapse ? $d : @{$by_dir{$d}});
1648 }
1649
1650 if (@ret != @files) {
1651 @ret = &collapse_dirs (@ret);
1652 }
1653 return @ret;
1654 }
1655
1656 =item C<dirs_of_files(@files)>
1657
1658 Returns all the directories in which at least one of the given
1659 files reside.
1660 =cut
1661
1662 sub dirs_of_files {
1663 my (@files) = @_;
1664 my %by_dir;
1665
1666 # construct hash of all directories mentioned, values are lists of the
1667 # files/dirs in that directory.
1668 for my $f (@files) {
1669 # what should we do with not existing entries????
1670 next if (! -r "$f");
1671 my $abs_f = Cwd::abs_path ($f);
1672 # the following is necessary because on windows,
1673 # abs_path("tl-portable")
1674 # returns
1675 # c:\tl test\...
1676 # and not forward slashes, while, if there is already a forward /
1677 # in the path, also the rest is done with forward slashes.
1678 $abs_f =~ s!\\!/!g if wndws();
1679 if (!$abs_f) {
1680 warn ("oops, no abs_path($f) from " . `pwd`);
1681 next;
1682 }
1683 (my $d = $abs_f) =~ s,/[^/]*$,,;
1684 my @a = exists $by_dir{$d} ? @{$by_dir{$d}} : ();
1685 push (@a, $abs_f);
1686 $by_dir{$d} = \@a;
1687 }
1688
1689 return %by_dir;
1690 }
1691
1692 =item C<all_dirs_and_removed_dirs(@files)>
1693
1694 Returns all the directories for files and those from which all
1695 content will be removed.
1696
1697 =cut
1698
1699 sub all_dirs_and_removed_dirs {
1700 my (@files) = @_;
1701 my %removed_dirs;
1702 my %by_dir = dirs_of_files(@files);
1703
1704 # for each of our directories, see if we are removing everything in
1705 # the directory. if so, return the directory; else return the
1706 # individual files.
1707 for my $d (reverse sort keys %by_dir) {
1708 opendir (DIR, $d) || die "opendir($d) failed: $!";
1709 my @dirents = readdir (DIR);
1710 closedir (DIR) || warn "closedir($d) failed: $!";
1711
1712 # initialize test hash with all the files we saw in this dir.
1713 # (These idioms are due to "Finding Elements in One Array and Not
1714 # Another" in the Perl Cookbook.)
1715 my %seen;
1716 my @rmfiles = @{$by_dir{$d}};
1717 @seen{@rmfiles} = ();
1718
1719 # see if everything is the same.
1720 my $cleandir = 1;
1721 for my $dirent (@dirents) {
1722 next if $dirent =~ /^\.(\.|svn)?$/; # ignore . .. .svn
1723 my $item = "$d/$dirent"; # prepend directory for comparison
1724 if (
1725 ((-d $item) && (defined($removed_dirs{$item})))
1726 ||
1727 (exists $seen{$item})
1728 ) {
1729 # do nothing
1730 } else {
1731 $cleandir = 0;
1732 last;
1733 }
1734 }
1735 if ($cleandir) {
1736 $removed_dirs{$d} = 1;
1737 }
1738 }
1739 return (%by_dir, %removed_dirs);
1740 }
1741
1742 =item C<removed_dirs(@files)>
1743
1744 Returns all the directories from which all content will be removed.
1745
1746 Here is the idea:
1747
1748 =over 4
1749
1750 =item create a hashes by_dir listing all files that should be removed
1751 by directory, i.e., key = dir, value is list of files
1752
1753 =item for each of the dirs (keys of by_dir and ordered deepest first)
1754 check that all actually contained files are removed
1755 and all the contained dirs are in the removal list. If this is the
1756 case put that directory into the removal list
1757
1758 =item return this removal list
1759
1760 =back
1761 =cut
1762
1763 sub removed_dirs {
1764 my (@files) = @_;
1765 my (%by_dir, %removed_dirs) = all_dirs_and_removed_dirs(@files);
1766 return keys %removed_dirs;
1767 }
1768
1769
1770 =item C<time_estimate($totalsize, $donesize, $starttime)>
1771
1772 Returns the current running time and the estimated total time
1773 based on the total size, the already done size, and the start time.
1774
1775 =cut
1776
1777 sub time_estimate {
1778 my ($totalsize, $donesize, $starttime) = @_;
1779 if ($donesize <= 0) {
1780 return ("??:??", "??:??");
1781 }
1782 my $curtime = time();
1783 my $passedtime = $curtime - $starttime;
1784 my $esttotalsecs = int ( ( $passedtime * $totalsize ) / $donesize );
1785 #
1786 # we change the display to show that passed time instead of the
1787 # estimated remaining time. We keep the old code and naming and
1788 # only initialize the $remsecs to the $passedtime instead.
1789 # my $remsecs = $esttotalsecs - $passedtime;
1790 my $remsecs = $passedtime;
1791 my $min = int($remsecs/60);
1792 my $hour;
1793 if ($min >= 60) {
1794 $hour = int($min/60);
1795 $min %= 60;
1796 }
1797 my $sec = $remsecs % 60;
1798 my $remtime = sprintf("%02d:%02d", $min, $sec);
1799 if ($hour) {
1800 $remtime = sprintf("%02d:$remtime", $hour);
1801 }
1802 my $tmin = int($esttotalsecs/60);
1803 my $thour;
1804 if ($tmin >= 60) {
1805 $thour = int($tmin/60);
1806 $tmin %= 60;
1807 }
1808 my $tsec = $esttotalsecs % 60;
1809 my $tottime = sprintf("%02d:%02d", $tmin, $tsec);
1810 if ($thour) {
1811 $tottime = sprintf("%02d:$tottime", $thour);
1812 }
1813 return($remtime, $tottime);
1814 }
1815
1816
1817 =item C<install_packages($from_tlpdb, $media, $to_tlpdb, $what, $opt_src, $opt_doc, $retry, $continue)>
1818
1819 Installs the list of packages found in C<@$what> (a ref to a list) into
1820 the TLPDB given by C<$to_tlpdb>. Information on files are taken from
1821 the TLPDB C<$from_tlpdb>.
1822
1823 C<$opt_src> and C<$opt_doc> specify whether srcfiles and docfiles should
1824 be installed (currently implemented only for installation from
1825 uncompressed media).
1826
1827 If C<$retry> is trueish, retry failed packages a second time.
1828
1829 If C<$continue> is trueish, installation failure of non-critical packages
1830 will be ignored (success is returned).
1831
1832 Returns 1 on success and 0 on error.
1833
1834 =cut
1835
1836 sub install_packages {
1837 my ($fromtlpdb,$media,$totlpdb,$what,
1838 $opt_src,$opt_doc,$opt_retry,$opt_continue) = @_;
1839 my $container_src_split = $fromtlpdb->config_src_container;
1840 my $container_doc_split = $fromtlpdb->config_doc_container;
1841 my $root = $fromtlpdb->root;
1842 my @packs = @$what;
1843 my $totalnr = $#packs + 1;
1844 my $td = length("$totalnr");
1845 my $n = 0;
1846 my %tlpobjs;
1847 my $totalsize = 0;
1848 my $donesize = 0;
1849 my %tlpsizes;
1850 debug("TLUtils::install_packages: fromtlpdb.root=$root, media=$media,"
1851 . " totlpdb.root=" . $totlpdb->root
1852 . " what=$what ($totalnr), opt_src=$opt_src, opt_doc=$opt_doc\n");
1853
1854 foreach my $p (@packs) {
1855 $tlpobjs{$p} = $fromtlpdb->get_package($p);
1856 if (!defined($tlpobjs{$p})) {
1857 die "STRANGE: $p not to be found in ", $fromtlpdb->root;
1858 }
1859 if ($media ne 'local_uncompressed') {
1860 # we use the container size as the measuring unit since probably
1861 # downloading will be the limiting factor
1862 $tlpsizes{$p} = $tlpobjs{$p}->containersize;
1863 $tlpsizes{$p} += $tlpobjs{$p}->srccontainersize if $opt_src;
1864 $tlpsizes{$p} += $tlpobjs{$p}->doccontainersize if $opt_doc;
1865 } else {
1866 # we have to add the respective sizes, that is checking for
1867 # installation of src and doc file
1868 $tlpsizes{$p} = $tlpobjs{$p}->runsize;
1869 $tlpsizes{$p} += $tlpobjs{$p}->srcsize if $opt_src;
1870 $tlpsizes{$p} += $tlpobjs{$p}->docsize if $opt_doc;
1871 my %foo = %{$tlpobjs{$p}->binsize};
1872 for my $k (keys %foo) { $tlpsizes{$p} += $foo{$k}; }
1873 # all the packages sizes are in blocks, so transfer that to bytes
1874 $tlpsizes{$p} *= $TeXLive::TLConfig::BlockSize;
1875 }
1876 $totalsize += $tlpsizes{$p};
1877 }
1878 my $starttime = time();
1879 my @packs_again; # packages that we failed to download and should retry later
1880 foreach my $package (@packs) {
1881 my $tlpobj = $tlpobjs{$package};
1882 my $reloc = $tlpobj->relocated;
1883 $n++;
1884 my ($estrem, $esttot) = time_estimate($totalsize, $donesize, $starttime);
1885 my $infostr = sprintf("Installing [%0${td}d/$totalnr, "
1886 . "time/total: $estrem/$esttot]: $package [%dk]",
1887 $n, int($tlpsizes{$package}/1024) + 1);
1888 info("$infostr\n");
1889 foreach my $h (@::install_packages_hook) {
1890 &$h($n,$totalnr);
1891 }
1892 # push $package to @packs_again if download failed
1893 # (and not installing from disk).
1894 if (!$fromtlpdb->install_package($package, $totlpdb)) {
1895 tlwarn("TLUtils::install_packages: Failed to install $package\n");
1896 if ($opt_retry) {
1897 tlwarn(" $package will be retried later.\n");
1898 push @packs_again, $package;
1899 } else {
1900 # return false as soon as one package failed, since we won't
1901 # be trying again.
1902 return 0;
1903 }
1904 } else {
1905 $donesize += $tlpsizes{$package};
1906 }
1907 }
1908 # try to download packages in @packs_again again
1909 foreach my $package (@packs_again) {
1910 my $infostr = sprintf("Retrying to install: $package [%dk]",
1911 int($tlpsizes{$package}/1024) + 1);
1912 info("$infostr\n");
1913 # return false if download failed again
1914 if (!$fromtlpdb->install_package($package, $totlpdb)) {
1915 if ($opt_continue) {
1916 push @::installation_failed_packages, $package;
1917 tlwarn("Failed to install $package, but continuing anyway!\n");
1918 } else {
1919 return 0;
1920 }
1921 }
1922 $donesize += $tlpsizes{$package};
1923 }
1924 my $totaltime = time() - $starttime;
1925 my $tothour = int ($totaltime/3600);
1926 my $totmin = (int ($totaltime/60)) % 60;
1927 my $totsec = $totaltime % 60;
1928 my $hrstr = ($tothour > 0 ? "$tothour:" : "");
1929 info(sprintf("Time used for installing the packages: $hrstr%02d:%02d\n",
1930 $totmin, $totsec));
1931 $totlpdb->save;
1932 return 1;
1933 }
1934
1935 =item C<do_postaction($how, $tlpobj, $do_fileassocs, $do_menu, $do_desktop, $do_script)>
1936
1937 Evaluates the C<postaction> fields in the C<$tlpobj>. The first parameter
1938 can be either C<install> or C<remove>. The second gives the TLPOBJ whos
1939 postactions should be evaluated, and the last four arguments specify
1940 what type of postactions should (or shouldn't) be evaluated.
1941
1942 Returns 1 on success, and 0 on failure.
1943
1944 =cut
1945
1946 sub do_postaction {
1947 my ($how, $tlpobj, $do_fileassocs, $do_menu, $do_desktop, $do_script) = @_;
1948 my $ret = 1;
1949 if (!defined($tlpobj)) {
1950 tlwarn("do_postaction: didn't get a tlpobj\n");
1951 return 0;
1952 }
1953 debug("running postaction=$how for " . $tlpobj->name . "\n")
1954 if $tlpobj->postactions;
1955 for my $pa ($tlpobj->postactions) {
1956 if ($pa =~ m/^\s*shortcut\s+(.*)\s*$/) {
1957 $ret &&= _do_postaction_shortcut($how, $tlpobj, $do_menu, $do_desktop, $1);
1958 } elsif ($pa =~ m/\s*filetype\s+(.*)\s*$/) {
1959 next unless $do_fileassocs;
1960 $ret &&= _do_postaction_filetype($how, $tlpobj, $1);
1961 } elsif ($pa =~ m/\s*fileassoc\s+(.*)\s*$/) {
1962 $ret &&= _do_postaction_fileassoc($how, $do_fileassocs, $tlpobj, $1);
1963 next;
1964 } elsif ($pa =~ m/\s*progid\s+(.*)\s*$/) {
1965 next unless $do_fileassocs;
1966 $ret &&= _do_postaction_progid($how, $tlpobj, $1);
1967 } elsif ($pa =~ m/\s*script\s+(.*)\s*$/) {
1968 next unless $do_script;
1969 $ret &&= _do_postaction_script($how, $tlpobj, $1);
1970 } else {
1971 tlwarn("do_postaction: don't know how to do $pa\n");
1972 $ret = 0;
1973 }
1974 }
1975 # nothing to do
1976 return $ret;
1977 }
1978
1979 sub _do_postaction_fileassoc {
1980 my ($how, $mode, $tlpobj, $pa) = @_;
1981 return 1 unless wndws();
1982 my ($errors, %keyval) =
1983 parse_into_keywords($pa, qw/extension filetype/);
1984
1985 if ($errors) {
1986 tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
1987 return 0;
1988 }
1989
1990 # name can be an arbitrary string
1991 if (!defined($keyval{'extension'})) {
1992 tlwarn("extension of fileassoc postaction not given\n");
1993 return 0;
1994 }
1995 my $extension = $keyval{'extension'};
1996
1997 # cmd can be an arbitrary string
1998 if (!defined($keyval{'filetype'})) {
1999 tlwarn("filetype of fileassoc postaction not given\n");
2000 return 0;
2001 }
2002 my $filetype = $keyval{'filetype'}.'.'.$ReleaseYear;
2003
2004 &log("postaction $how fileassoc for " . $tlpobj->name .
2005 ": $extension, $filetype\n");
2006 if ($how eq "install") {
2007 TeXLive::TLWinGoo::register_extension($mode, $extension, $filetype);
2008 } elsif ($how eq "remove") {
2009 TeXLive::TLWinGoo::unregister_extension($mode, $extension, $filetype);
2010 } else {
2011 tlwarn("Unknown mode $how\n");
2012 return 0;
2013 }
2014 return 1;
2015 }
2016
2017 sub _do_postaction_filetype {
2018 my ($how, $tlpobj, $pa) = @_;
2019 return 1 unless wndws();
2020 my ($errors, %keyval) =
2021 parse_into_keywords($pa, qw/name cmd/);
2022
2023 if ($errors) {
2024 tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
2025 return 0;
2026 }
2027
2028 # name can be an arbitrary string
2029 if (!defined($keyval{'name'})) {
2030 tlwarn("name of filetype postaction not given\n");
2031 return 0;
2032 }
2033 my $name = $keyval{'name'}.'.'.$ReleaseYear;
2034
2035 # cmd can be an arbitrary string
2036 if (!defined($keyval{'cmd'})) {
2037 tlwarn("cmd of filetype postaction not given\n");
2038 return 0;
2039 }
2040 my $cmd = $keyval{'cmd'};
2041
2042 my $texdir = `kpsewhich -var-value=TEXMFROOT`;
2043 chomp($texdir);
2044 my $texdir_bsl = conv_to_w32_path($texdir);
2045 $cmd =~ s!^("?)TEXDIR/!$1$texdir/!g;
2046
2047 &log("postaction $how filetype for " . $tlpobj->name .
2048 ": $name, $cmd\n");
2049 if ($how eq "install") {
2050 TeXLive::TLWinGoo::register_file_type($name, $cmd);
2051 } elsif ($how eq "remove") {
2052 TeXLive::TLWinGoo::unregister_file_type($name);
2053 } else {
2054 tlwarn("Unknown mode $how\n");
2055 return 0;
2056 }
2057 return 1;
2058 }
2059
2060 # alternate filetype (= progid) for an extension;
2061 # associated program shows up in `open with' menu
2062 sub _do_postaction_progid {
2063 my ($how, $tlpobj, $pa) = @_;
2064 return 1 unless wndws();
2065 my ($errors, %keyval) =
2066 parse_into_keywords($pa, qw/extension filetype/);
2067
2068 if ($errors) {
2069 tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
2070 return 0;
2071 }
2072
2073 if (!defined($keyval{'extension'})) {
2074 tlwarn("extension of progid postaction not given\n");
2075 return 0;
2076 }
2077 my $extension = $keyval{'extension'};
2078
2079 if (!defined($keyval{'filetype'})) {
2080 tlwarn("filetype of progid postaction not given\n");
2081 return 0;
2082 }
2083 my $filetype = $keyval{'filetype'}.'.'.$ReleaseYear;
2084
2085 &log("postaction $how progid for " . $tlpobj->name .
2086 ": $extension, $filetype\n");
2087 if ($how eq "install") {
2088 TeXLive::TLWinGoo::add_to_progids($extension, $filetype);
2089 } elsif ($how eq "remove") {
2090 TeXLive::TLWinGoo::remove_from_progids($extension, $filetype);
2091 } else {
2092 tlwarn("Unknown mode $how\n");
2093 return 0;
2094 }
2095 return 1;
2096 }
2097
2098 sub _do_postaction_script {
2099 my ($how, $tlpobj, $pa) = @_;
2100 my ($errors, %keyval) =
2101 parse_into_keywords($pa, qw/file filew32/);
2102
2103 if ($errors) {
2104 tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
2105 return 0;
2106 }
2107
2108 # file can be an arbitrary string
2109 if (!defined($keyval{'file'})) {
2110 tlwarn("filename of script not given\n");
2111 return 0;
2112 }
2113 my $file = $keyval{'file'};
2114 if (wndws() && defined($keyval{'filew32'})) {
2115 $file = $keyval{'filew32'};
2116 }
2117 my $texdir = `kpsewhich -var-value=TEXMFROOT`;
2118 chomp($texdir);
2119 my @syscmd;
2120 if ($file =~ m/\.pl$/i) {
2121 # we got a perl script, call it via perl
2122 push @syscmd, "perl", "$texdir/$file";
2123 } elsif ($file =~ m/\.texlua$/i) {
2124 # we got a texlua script, call it via texlua
2125 push @syscmd, "texlua", "$texdir/$file";
2126 } else {
2127 # we got anything else, call it directly and hope it is excutable
2128 push @syscmd, "$texdir/$file";
2129 }
2130 &log("postaction $how script for " . $tlpobj->name . ": @syscmd\n");
2131 push @syscmd, $how, $texdir;
2132 my $ret = system (@syscmd);
2133 if ($ret != 0) {
2134 $ret /= 256 if $ret > 0;
2135 my $pwd = cwd ();
2136 warn "$0: calling post action script $file did not succeed in $pwd, status $ret";
2137 return 0;
2138 }
2139 return 1;
2140 }
2141
2142 sub _do_postaction_shortcut {
2143 my ($how, $tlpobj, $do_menu, $do_desktop, $pa) = @_;
2144 return 1 unless wndws();
2145 my ($errors, %keyval) =
2146 parse_into_keywords($pa, qw/type name icon cmd args hide/);
2147
2148 if ($errors) {
2149 tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
2150 return 0;
2151 }
2152
2153 # type can be either menu or desktop
2154 if (!defined($keyval{'type'})) {
2155 tlwarn("type of shortcut postaction not given\n");
2156 return 0;
2157 }
2158 my $type = $keyval{'type'};
2159 if (($type ne "menu") && ($type ne "desktop")) {
2160 tlwarn("type of shortcut postaction $type is unknown (menu, desktop)\n");
2161 return 0;
2162 }
2163
2164 if (($type eq "menu") && !$do_menu) {
2165 return 1;
2166 }
2167 if (($type eq "desktop") && !$do_desktop) {
2168 return 1;
2169 }
2170
2171 # name can be an arbitrary string
2172 if (!defined($keyval{'name'})) {
2173 tlwarn("name of shortcut postaction not given\n");
2174 return 0;
2175 }
2176 my $name = $keyval{'name'};
2177
2178 # icon, cmd, args is optional
2179 my $icon = (defined($keyval{'icon'}) ? $keyval{'icon'} : '');
2180 my $cmd = (defined($keyval{'cmd'}) ? $keyval{'cmd'} : '');
2181 my $args = (defined($keyval{'args'}) ? $keyval{'args'} : '');
2182
2183 # hide can be only 0 or 1, and defaults to 1
2184 my $hide = (defined($keyval{'hide'}) ? $keyval{'hide'} : 1);
2185 if (($hide ne "0") && ($hide ne "1")) {
2186 tlwarn("hide of shortcut postaction $hide is unknown (0, 1)\n");
2187 return 0;
2188 }
2189
2190 &log("postaction $how shortcut for " . $tlpobj->name . "\n");
2191 if ($how eq "install") {
2192 my $texdir = `kpsewhich -var-value=TEXMFROOT`;
2193 chomp($texdir);
2194 my $texdir_bsl = conv_to_w32_path($texdir);
2195 $icon =~ s!^TEXDIR/!$texdir/!;
2196 $cmd =~ s!^TEXDIR/!$texdir/!;
2197 # $cmd can be an URL, in which case we do NOT want to convert it to
2198 # w32 paths!
2199 if ($cmd !~ m!^\s*(https?://|ftp://)!) {
2200 if (!(-e $cmd) or !(-r $cmd)) {
2201 tlwarn("Target of shortcut action does not exist: $cmd\n")
2202 if $cmd =~ /\.(exe|bat|cmd)$/i;
2203 # if not an executable, just omit shortcut silently: no error
2204 return 1;
2205 }
2206 $cmd = conv_to_w32_path($cmd);
2207 }
2208 if ($type eq "menu" ) {
2209 TeXLive::TLWinGoo::add_menu_shortcut(
2210 $TeXLive::TLConfig::WindowsMainMenuName,
2211 $name, $icon, $cmd, $args, $hide);
2212 } elsif ($type eq "desktop") {
2213 TeXLive::TLWinGoo::add_desktop_shortcut(
2214 $name, $icon, $cmd, $args, $hide);
2215 } else {
2216 tlwarn("Unknown type of shortcut: $type\n");
2217 return 0;
2218 }
2219 } elsif ($how eq "remove") {
2220 if ($type eq "menu") {
2221 TeXLive::TLWinGoo::remove_menu_shortcut(
2222 $TeXLive::TLConfig::WindowsMainMenuName, $name);
2223 } elsif ($type eq "desktop") {
2224 TeXLive::TLWinGoo::remove_desktop_shortcut($name);
2225 } else {
2226 tlwarn("Unknown type of shortcut: $type\n");
2227 return 0;
2228 }
2229 } else {
2230 tlwarn("Unknown mode $how\n");
2231 return 0;
2232 }
2233 return 1;
2234 }
2235
2236 =item C<parse_into_keywords>
2237
2238 =cut
2239
2240 sub parse_into_keywords {
2241 my ($str, @keys) = @_;
2242 my @words = quotewords('\s+', 0, $str);
2243 my %ret;
2244 my $error = 0;
2245 while (@words) {
2246 $_ = shift @words;
2247 if (/^([^=]+)=(.*)$/) {
2248 $ret{$1} = $2;
2249 } else {
2250 tlwarn("parser found a invalid word in parsing keys: $_\n");
2251 $error++;
2252 $ret{$_} = "";
2253 }
2254 }
2255 for my $k (keys %ret) {
2256 if (!member($k, @keys)) {
2257 $error++;
2258 tlwarn("parser found invalid keyword: $k\n");
2259 }
2260 }
2261 return($error, %ret);
2262 }
2263
2264 =item C<update_context_cache($bindir,$progext,$run_postinst_cmd)>
2265
2266 Run the ConTeXt cache generation commands, using C<$bindir> and
2267 C<$progext> to check if commands can be run. Use the function reference
2268 C<$run_postinst_cmd> to actually run the commands. The return status is
2269 zero if all succeeded, nonzero otherwise. If the main ConTeXt program
2270 (C<luametatex>) cannot be run at all, the return status is zero.
2271
2272 Functions C<info> and C<debug> are called with status reports.
2273
2274 =cut
2275
2276 sub update_context_cache {
2277 my ($bindir,$progext,$run_postinst_cmd) = @_;
2278
2279 my $errcount = 0;
2280
2281 # The story here is that in 2023, the provided lmtx binary for
2282 # x86_64-linux was too new to run on the system where we build TL.
2283 # (luametatex: /lib64/libm.so.6: version `GLIBC_2.23' not found)
2284 # So we have to try running the binary to see if it works, not just
2285 # test for its existence. And since it exits nonzero given no args, we
2286 # have to specify --version. Hope it keeps working like that ...
2287 #
2288 # If lmtx is not runnable, don't consider that an error, since nothing
2289 # can be done about it.
2290 my $lmtx = "$bindir/luametatex$progext";
2291 if (TeXLive::TLUtils::system_ok("$lmtx --version")) {
2292 info("setting up ConTeXt caches: ");
2293 $errcount += &$run_postinst_cmd("mtxrun --generate");
2294 #
2295 # If mtxrun failed, don't bother trying more.
2296 if ($errcount == 0) {
2297 $errcount += &$run_postinst_cmd("context --luatex --generate");
2298 #
2299 # This is for finding fonts by font name (the --generate suffices
2300 # for file name). Although ConTeXt does some automatic cache
2301 # regeneration, Hans advises that this manual reload can help, and
2302 # should be no harm.
2303 # https://wiki.contextgarden.net/Use_the_fonts_you_want
2304 # https://wiki.contextgarden.net/Mtxrun#base and #fonts
2305 $errcount += &$run_postinst_cmd("mtxrun --script fonts --reload");
2306 #
2307 # If context succeeded too, try luajittex. Missing on some platforms.
2308 # Although we build luajittex normally, instead of importing the
2309 # binary, so testing for file existence should suffice, we may as
2310 # well test execution since it's just as easy.
2311 #
2312 if ($errcount == 0) {
2313 my $luajittex = "$bindir/luajittex$progext";
2314 if (TeXLive::TLUtils::system_ok("$luajittex --version")) {
2315 $errcount += &$run_postinst_cmd("context --luajittex --generate");
2316 } else {
2317 debug("skipped luajittex cache setup, can't run $luajittex\n");
2318 }
2319 }
2320 }
2321 }
2322 return $errcount;
2323 }
2324
2325 =item C<announce_execute_actions($how, [$tlpobj[, $what]])>
2326
2327 Announces (records) that the actions, usually given in C<$tlpobj> (but
2328 can be omitted for global actions), should be executed after all
2329 packages have been unpacked. The optional C<$what> depends on the
2330 action, e.g., a parse_AddFormat_line reference for formats; not sure if
2331 it's used for anything else.
2332
2333 This is called for every package that gets installed.
2334
2335 =cut
2336
2337 sub announce_execute_actions {
2338 my ($type,$tlp,$what) = @_;
2339 # return immediately if execute actions are suppressed
2340 return if $::no_execute_actions;
2341
2342 # since we're called for every package with "enable",
2343 # it's not helpful to report that again.
2344 if ($type ne "enable") {
2345 my $forpkg = $tlp ? ("for " . $tlp->name) : "no package";
2346 debug("announce_execute_actions: given $type ($forpkg)\n");
2347 }
2348 if (defined($type) && ($type eq "regenerate-formats")) {
2349 $::regenerate_all_formats = 1;
2350 return;
2351 }
2352 if (defined($type) && ($type eq "files-changed")) {
2353 $::files_changed = 1;
2354 return;
2355 }
2356 if (defined($type) && ($type eq "context-cache")) {
2357 $::context_cache_update_needed = 1;
2358 return;
2359 }
2360 if (defined($type) && ($type eq "rebuild-format")) {
2361 # rebuild-format must feed in a hashref of a parse_AddFormat_line data
2362 # the $tlp argument is not used
2363 $::execute_actions{'enable'}{'formats'}{$what->{'name'}} = $what;
2364 return;
2365 }
2366 if (!defined($type) || (($type ne "enable") && ($type ne "disable"))) {
2367 die "announce_execute_actions: enable or disable, not type $type";
2368 }
2369 if ($tlp->runfiles || $tlp->srcfiles || $tlp->docfiles) {
2370 $::files_changed = 1;
2371 }
2372 #
2373 $what = "map format hyphen" if (!defined($what)); # do all by default
2374 foreach my $e ($tlp->executes) {
2375 if ($e =~ m/^add((Mixed|Kanji)?Map)\s+([^\s]+)\s*$/) {
2376 # save the refs as we have another =~ grep in the following lines
2377 my $a = $1;
2378 my $b = $3;
2379 $::execute_actions{$type}{'maps'}{$b} = $a if ($what =~ m/map/);
2380
2381 } elsif ($e =~ m/^AddFormat\s+(.*)\s*$/) {
2382 my %r = TeXLive::TLUtils::parse_AddFormat_line("$1");
2383 if (defined($r{"error"})) {
2384 tlwarn ("$r{'error'} in parsing $e for return hash\n");
2385 } else {
2386 $::execute_actions{$type}{'formats'}{$r{'name'}} = \%r
2387 if ($what =~ m/format/);
2388 }
2389
2390 } elsif ($e =~ m/^AddHyphen\s+(.*)\s*$/) {
2391 my %r = TeXLive::TLUtils::parse_AddHyphen_line("$1");
2392 if (defined($r{"error"})) {
2393 tlwarn ("$r{'error'} in parsing $e for return hash\n");
2394 } else {
2395 $::execute_actions{$type}{'hyphens'}{$r{'name'}} = \%r
2396 if ($what =~ m/hyphen/);
2397 }
2398
2399 } else {
2400 tlwarn("Unknown execute $e in ", $tlp->name, "\n");
2401 }
2402 }
2403 }
2404
2405
2406 =pod
2407
2408 =item C<add_symlinks($root, $arch, $sys_bin, $sys_man, $sys_info)>
2409
2410 =item C<remove_symlinks($root, $arch, $sys_bin, $sys_man, $sys_info)>
2411
2412 These two functions try to create/remove symlinks for binaries, man pages,
2413 and info files as specified by the options $sys_bin, $sys_man, $sys_info.
2414
2415 The functions return 1 on success and 0 on error.
2416 On Windows it returns undefined.
2417
2418 =cut
2419
2420 sub add_link_dir_dir {
2421 my ($from,$to) = @_;
2422 my ($ret, $err) = mkdirhier ($to);
2423 if (!$ret) {
2424 tlwarn("$err\n");
2425 return 0;
2426 }
2427 if (-w $to) {
2428 debug ("TLUtils::add_link_dir_dir: linking from $from to $to\n");
2429 chomp (my @files = `ls "$from"`);
2430 my $ret = 1;
2431 for my $f (@files) {
2432 # don't make a system-dir link to our special "man" link.
2433 if ($f eq "man") {
2434 debug ("not linking `man' into $to.\n");
2435 next;
2436 }
2437 #
2438 # attempt to remove an existing symlink, but nothing else.
2439 unlink ("$to/$f") if -l "$to/$f";
2440 #
2441 # if the destination still exists, skip it.
2442 if (-e "$to/$f") {
2443 tlwarn ("add_link_dir_dir: $to/$f exists; not making symlink.\n");
2444 next;
2445 }
2446 #
2447 # try to make the link.
2448 if (symlink ("$from/$f", "$to/$f") == 0) {
2449 tlwarn ("add_link_dir_dir: symlink of $f from $from to $to failed: $!\n");
2450 $ret = 0;
2451 }
2452 }
2453 return $ret;
2454 } else {
2455 tlwarn ("add_link_dir_dir: destination $to not writable, "
2456 . "no links from $from.\n");
2457 return 0;
2458 }
2459 }
2460
2461 sub remove_link_dir_dir {
2462 my ($from, $to) = @_;
2463 if ((-d "$to") && (-w "$to")) {
2464 debug("TLUtils::remove_link_dir_dir: removing links from $from to $to\n");
2465 chomp (my @files = `ls "$from"`);
2466 my $ret = 1;
2467 foreach my $f (@files) {
2468 next if (! -r "$to/$f");
2469 if ($f eq "man") {
2470 debug("TLUtils::remove_link_dir_dir: not considering man in $to, it should not be from us!\n");
2471 next;
2472 }
2473 if ((-l "$to/$f") &&
2474 (readlink("$to/$f") =~ m;^$from/;)) {
2475 $ret = 0 unless unlink("$to/$f");
2476 } else {
2477 $ret = 0;
2478 tlwarn ("TLUtils::remove_link_dir_dir: not removing $to/$f, not a link or wrong destination!\n");
2479 }
2480 }
2481 # try to remove the destination directory, it might be empty and
2482 # we might have write permissions, ignore errors
2483 # `rmdir "$to" 2>/dev/null`;
2484 return $ret;
2485 } else {
2486 tlwarn ("TLUtils::remove_link_dir_dir: destination $to not writable, no removal of links done!\n");
2487 return 0;
2488 }
2489 }
2490
2491 sub add_remove_symlinks {
2492 my ($mode, $Master, $arch, $sys_bin, $sys_man, $sys_info) = @_;
2493 my $errors = 0;
2494 my $plat_bindir = "$Master/bin/$arch";
2495
2496 # nothing to do with symlinks on Windows, of course.
2497 return if wndws();
2498
2499 my $info_dir = "$Master/texmf-dist/doc/info";
2500 if ($mode eq "add") {
2501 $errors++ unless add_link_dir_dir($plat_bindir, $sys_bin); # bin
2502 if (-d $info_dir) {
2503 $errors++ unless add_link_dir_dir($info_dir, $sys_info);
2504 }
2505 } elsif ($mode eq "remove") {
2506 $errors++ unless remove_link_dir_dir($plat_bindir, $sys_bin); # bin
2507 if (-d $info_dir) {
2508 $errors++ unless remove_link_dir_dir($info_dir, $sys_info);
2509 }
2510 } else {
2511 die ("should not happen, unknown mode $mode in add_remove_symlinks!");
2512 }
2513
2514 # man
2515 my $top_man_dir = "$Master/texmf-dist/doc/man";
2516 debug("TLUtils::add_remove_symlinks: $mode symlinks for man pages to $sys_man from $top_man_dir\n");
2517 if (! -d $top_man_dir) {
2518 ; # better to be silent?
2519 #info("skipping add of man symlinks, no source directory $top_man_dir\n");
2520 } else {
2521 my $man_doable = 1;
2522 if ($mode eq "add") {
2523 my ($ret, $err) = mkdirhier $sys_man;
2524 if (!$ret) {
2525 $man_doable = 0;
2526 tlwarn("$err\n");
2527 $errors++;
2528 }
2529 }
2530 if ($man_doable) {
2531 if (-w $sys_man) {
2532 my $foo = `(cd "$top_man_dir" && echo *)`;
2533 my @mans = split (' ', $foo);
2534 chomp (@mans);
2535 foreach my $m (@mans) {
2536 my $mandir = "$top_man_dir/$m";
2537 next unless -d $mandir;
2538 if ($mode eq "add") {
2539 $errors++ unless add_link_dir_dir($mandir, "$sys_man/$m");
2540 } else {
2541 $errors++ unless remove_link_dir_dir($mandir, "$sys_man/$m");
2542 }
2543 }
2544 #`rmdir "$sys_man" 2>/dev/null` if ($mode eq "remove");
2545 } else {
2546 tlwarn("TLUtils::add_remove_symlinks: man symlink destination ($sys_man) not writable, "
2547 . "cannot $mode symlinks.\n");
2548 $errors++;
2549 }
2550 }
2551 }
2552
2553 # we collected errors in $errors, so return the negation of it
2554 if ($errors) {
2555 info("TLUtils::add_remove_symlinks: $mode of symlinks had $errors error(s), see messages above.\n");
2556 return $F_ERROR;
2557 } else {
2558 return $F_OK;
2559 }
2560 }
2561
2562 sub add_symlinks { return (add_remove_symlinks("add", @_)); }
2563 sub remove_symlinks { return (add_remove_symlinks("remove", @_)); }
2564
2565 =pod
2566
2567 =item C<w32_add_to_path($bindir, $multiuser)>
2568 =item C<w32_remove_from_path($bindir, $multiuser)>
2569
2570 These two functions try to add/remove the binary directory $bindir
2571 on Windows to the registry PATH variable.
2572
2573 If running as admin user and $multiuser is set, the system path will
2574 be adjusted, otherwise the user path.
2575
2576 After calling these functions TeXLive::TLWinGoo::broadcast_env() should
2577 be called to make the changes immediately visible.
2578
2579 =cut
2580
2581 sub w32_add_to_path {
2582 my ($bindir, $multiuser) = @_;
2583 return if (!wndws());
2584
2585 my $path = TeXLive::TLWinGoo::get_system_env() -> {'/Path'};
2586 $path =~ s/[\s\x00]+$//;
2587 &log("Old system path: $path\n");
2588 $path = TeXLive::TLWinGoo::get_user_env() -> {'/Path'};
2589 if ($path) {
2590 $path =~ s/[\s\x00]+$//;
2591 &log("Old user path: $path\n");
2592 } else {
2593 &log("Old user path: none\n");
2594 }
2595 my $mode = 'user';
2596 if (TeXLive::TLWinGoo::admin() && $multiuser) {
2597 $mode = 'system';
2598 }
2599 debug("TLUtils:w32_add_to_path: calling adjust_reg_path_for_texlive add $bindir $mode\n");
2600 TeXLive::TLWinGoo::adjust_reg_path_for_texlive('add', $bindir, $mode);
2601 $path = TeXLive::TLWinGoo::get_system_env() -> {'/Path'};
2602 $path =~ s/[\s\x00]+$//;
2603 &log("New system path: $path\n");
2604 $path = TeXLive::TLWinGoo::get_user_env() -> {'/Path'};
2605 if ($path) {
2606 $path =~ s/[\s\x00]+$//;
2607 &log("New user path: $path\n");
2608 } else {
2609 &log("New user path: none\n");
2610 }
2611 }
2612
2613 sub w32_remove_from_path {
2614 my ($bindir, $multiuser) = @_;
2615 my $mode = 'user';
2616 if (TeXLive::TLWinGoo::admin() && $multiuser) {
2617 $mode = 'system';
2618 }
2619 debug("w32_remove_from_path: trying to remove $bindir in $mode\n");
2620 TeXLive::TLWinGoo::adjust_reg_path_for_texlive('remove', $bindir, $mode);
2621 }
2622
2623 =pod
2624
2625 =item C<check_file_and_remove($what, $checksum, $checksize>
2626
2627 Remove the file C<$what> if either the given C<$checksum> or
2628 C<$checksize> for C<$what> does not agree with our recomputation using
2629 C<TLCrypto::tlchecksum> and C<stat>, respectively. If a check argument
2630 is not given, that check is not performed. If the checksums agree, the
2631 size is not checked. The return status is random.
2632
2633 This unusual behavior (removing the given file) is because this is used
2634 for newly-downloaded files; see the calls in the C<unpack> routine
2635 (which is the only caller).
2636
2637 =cut
2638
2639 sub check_file_and_remove {
2640 my ($xzfile, $checksum, $checksize) = @_;
2641 my $fn_name = (caller(0))[3];
2642 debug("$fn_name $xzfile, $checksum, $checksize\n");
2643
2644 if (!$checksum && !$checksize) {
2645 tlwarn("$fn_name: neither checksum nor checksize " .
2646 "available for $xzfile, cannot check integrity\n");
2647 return;
2648 }
2649
2650 # The idea is that if one of the tests fail, we want to save a copy of
2651 # the input file for debugging. But we can't just omit removing the
2652 # file, since the caller depends on the removal. So we copy it to a
2653 # new temporary directory, which we want to persist, so can't use tl_tmpdir.
2654 my $check_file_tmpdir = undef;
2655
2656 # only run checksum tests if we can actually compute the checksum
2657 if ($checksum && ($checksum ne "-1") && $::checksum_method) {
2658 my $tlchecksum = TeXLive::TLCrypto::tlchecksum($xzfile);
2659 if ($tlchecksum ne $checksum) {
2660 tlwarn("$fn_name: checksums differ for $xzfile:\n");
2661 tlwarn("$fn_name: tlchecksum=$tlchecksum, arg=$checksum\n");
2662 tlwarn("$fn_name: backtrace:\n" . backtrace());
2663 # on Windows passing a pattern creates the tmpdir in PWD
2664 # which means that it will be tried to be created on the DVD
2665 # $check_file_tmpdir = File::Temp::tempdir("tlcheckfileXXXXXXXX");
2666 $check_file_tmpdir = File::Temp::tempdir();
2667 tlwarn("$fn_name: removing $xzfile, "
2668 . "but saving copy in $check_file_tmpdir\n");
2669 copy($xzfile, $check_file_tmpdir);
2670 unlink($xzfile);
2671 return;
2672 } else {
2673 debug("$fn_name: checksums for $xzfile agree\n");
2674 # if we have checked the checksum, we don't need to check the size, too
2675 return;
2676 }
2677 }
2678 if ($checksize && ($checksize ne "-1")) {
2679 my $filesize = (stat $xzfile)[7];
2680 if ($filesize != $checksize) {
2681 tlwarn("$fn_name: removing $xzfile, sizes differ:\n");
2682 tlwarn("$fn_name: tlfilesize=$filesize, arg=$checksize\n");
2683 if (!defined($check_file_tmpdir)) {
2684 # the tmpdir should always be undefined, since we shouldn't get
2685 # here if the checksums failed, but test anyway.
2686 $check_file_tmpdir = File::Temp::tempdir("tlcheckfileXXXXXXXX");
2687 tlwarn("$fn_name: saving copy in $check_file_tmpdir\n");
2688 copy($xzfile, $check_file_tmpdir);
2689 }
2690 unlink($xzfile);
2691 return;
2692 }
2693 }
2694 # We cannot remove the file here, otherwise restoring of backups
2695 # or unwind packages might die.
2696 }
2697
2698 =pod
2699
2700 =item C<unpack($what, $targetdir, @opts>
2701
2702 If necessary, downloads C$what>, and then unpacks it into C<$targetdir>.
2703 C<@opts> is assigned to a hash and can contain the following
2704 keys: C<tmpdir> (use this directory for downloaded files),
2705 C<checksum> (check downloaded file against this checksum),
2706 C<size> (check downloaded file against this size),
2707 C<remove> (remove temporary files after operation).
2708
2709 Returns a pair of values: in case of error return 0 and an additional
2710 explanation, in case of success return 1 and the name of the package.
2711
2712 If C<checksum> or C<size> is C<-1>, no warnings about missing checksum/size
2713 is printed. This is used during restore and unwinding of failed updates.
2714
2715 =cut
2716
2717 sub unpack {
2718 my ($what, $target, %opts) = @_;
2719 # remove by default
2720 my $remove = (defined($opts{'remove'}) ? $opts{'remove'} : 1);
2721 my $tempdir = (defined($opts{'tmpdir'}) ? $opts{'tmpdir'} : tl_tmpdir());
2722 my $checksum = (defined($opts{'checksum'}) ? $opts{'checksum'} : 0);
2723 my $size = (defined($opts{'size'}) ? $opts{'size'} : 0);
2724
2725 if (!defined($what)) {
2726 return (0, "nothing to unpack");
2727 }
2728
2729 my $decompressorType;
2730 my $compressorextension;
2731 if ($what =~ m/\.tar\.$CompressorExtRegexp$/) {
2732 $compressorextension = $1;
2733 $decompressorType = $1 eq "gz" ? "gzip" : $1;
2734 }
2735 if (!$decompressorType) {
2736 return(0, "don't know how to unpack");
2737 }
2738 # make sure that the found uncompressor type is also available
2739 if (!member($decompressorType, @{$::progs{'working_compressors'}})) {
2740 return(0, "unsupported container format $decompressorType");
2741 }
2742
2743 # only check the necessary compressor program
2744 my $decompressor = $::progs{$decompressorType};
2745 my @decompressorArgs = @{$Compressors{$decompressorType}{'decompress_args'}};
2746
2747 my $fn = basename($what);
2748 my $pkg = $fn;
2749 $pkg =~ s/\.tar\.$compressorextension$//;
2750 my $remove_containerfile = $remove;
2751 my $containerfile = "$tempdir/$fn";
2752 my $tarfile = "$tempdir/$fn";
2753 $tarfile =~ s/\.$compressorextension$//;
2754 if ($what =~ m,^(https?|ftp)://, || $what =~ m!$SshURIRegex!) {
2755 # we are installing from the NET
2756 # check for the presence of $what in $tempdir
2757 if (-r $containerfile) {
2758 check_file_and_remove($containerfile, $checksum, $size);
2759 }
2760 # if the file is now not present, we can use it
2761 if (! -r $containerfile) {
2762 # try download the file and put it into temp
2763 if (!download_file($what, $containerfile)) {
2764 return(0, "downloading did not succeed (download_file failed)");
2765 }
2766 # remove false downloads
2767 check_file_and_remove($containerfile, $checksum, $size);
2768 if ( ! -r $containerfile ) {
2769 return(0, "downloading did not succeed (check_file_and_remove failed)");
2770 }
2771 }
2772 } else {
2773 # we are installing from local compressed files
2774 # copy it to temp with dereferencing of link target
2775 TeXLive::TLUtils::copy("-L", $what, $tempdir);
2776
2777 check_file_and_remove($containerfile, $checksum, $size);
2778 if (! -r $containerfile) {
2779 return (0, "consistency checks failed");
2780 }
2781 # we can remove it afterwards
2782 $remove_containerfile = 1;
2783 }
2784 if (!system_pipe($decompressor, $containerfile, $tarfile,
2785 $remove_containerfile, @decompressorArgs)
2786 ||
2787 ! -f $tarfile) {
2788 unlink($tarfile, $containerfile);
2789 return(0, "Decompressing $containerfile failed");
2790 }
2791 if (untar($tarfile, $target, 1)) {
2792 return (1, "$pkg");
2793 } else {
2794 return (0, "untar failed");
2795 }
2796 }
2797
2798 =pod
2799
2800 =item C<untar($tarfile, $targetdir, $remove_tarfile)>
2801
2802 Unpacks C<$tarfile> in C<$targetdir> (changing directories to
2803 C<$targetdir> and then back to the original directory). If
2804 C<$remove_tarfile> is true, unlink C<$tarfile> after unpacking.
2805
2806 Assumes the global C<$::progs{"tar"}> has been set up.
2807
2808 =cut
2809
2810 # return 1 if success, 0 if failure.
2811 sub untar {
2812 my ($tarfile, $targetdir, $remove_tarfile) = @_;
2813 my $ret;
2814
2815 my $tar = $::progs{'tar'}; # assume it's been set up
2816
2817 # don't use the -C option to tar since Solaris tar et al. don't support it.
2818 # don't use system("cd ... && $tar ...") since that opens us up to
2819 # quoting issues.
2820 # so fall back on chdir in Perl.
2821 #
2822 debug("TLUtils::untar: unpacking $tarfile in $targetdir\n");
2823 my $cwd = cwd();
2824 chdir($targetdir) || die "chdir($targetdir) failed: $!";
2825
2826 # on w32 don't extract file modified time, because AV soft can open
2827 # files in the mean time causing time stamp modification to fail
2828 my $taropt = wndws() ? "xmf" : "xf";
2829 if (system($tar, $taropt, $tarfile) != 0) {
2830 tlwarn("TLUtils::untar: $tar $taropt $tarfile failed (in $targetdir)\n");
2831 $ret = 0;
2832 } else {
2833 $ret = 1;
2834 }
2835 unlink($tarfile) if $remove_tarfile;
2836
2837 chdir($cwd) || die "chdir($cwd) failed: $!";
2838 return $ret;
2839 }
2840
2841
2842 =item C<tlcmp($file, $file)>
2843
2844 Compare two files considering CR, LF, and CRLF as equivalent.
2845 Returns 1 if different, 0 if the same.
2846
2847 =cut
2848
2849 sub tlcmp {
2850 my ($filea, $fileb) = @_;
2851 if (!defined($fileb)) {
2852 die <<END_USAGE;
2853 tlcmp needs two arguments FILE1 FILE2.
2854 Compare as text files, ignoring line endings.
2855 Exit status is zero if the same, 1 if different, something else if trouble.
2856 END_USAGE
2857 }
2858 my $file1 = &read_file_ignore_cr ($filea);
2859 my $file2 = &read_file_ignore_cr ($fileb);
2860
2861 return $file1 eq $file2 ? 0 : 1;
2862 }
2863
2864
2865 =item C<read_file_ignore_cr($file)>
2866
2867 Return contents of FILE as a string, converting all of CR, LF, and
2868 CRLF to just LF.
2869
2870 =cut
2871
2872 sub read_file_ignore_cr {
2873 my ($fname) = @_;
2874 my $ret = "";
2875
2876 local *FILE;
2877 open (FILE, $fname) || die "open($fname) failed: $!";
2878 while (<FILE>) {
2879 s/\r\n?/\n/g;
2880 #warn "line is |$_|";
2881 $ret .= $_;
2882 }
2883 close (FILE) || warn "close($fname) failed: $!";
2884
2885 return $ret;
2886 }
2887
2888
2889 =item C<setup_programs($bindir, $platform, $tlfirst)>
2890
2891 Populate the global C<$::progs> hash containing the paths to the
2892 programs C<lz4>, C<tar>, C<wget>, C<xz>. The C<$bindir> argument specifies
2893 the path to the location of the C<xz> binaries, the C<$platform>
2894 gives the TeX Live platform name, used as the extension on our
2895 executables. If a program is not present in the TeX Live tree, we also
2896 check along PATH (without the platform extension.)
2897
2898 If the C<$tlfirst> argument or the C<TEXLIVE_PREFER_OWN> envvar is set,
2899 prefer TL versions; else prefer system versions (except for Windows
2900 C<tar.exe>, where we always use ours).
2901
2902 Check many different downloads and compressors to determine what is
2903 working.
2904
2905 Return 0 if failure, nonzero if success.
2906
2907 =cut
2908
2909 sub setup_programs {
2910 my ($bindir, $platform, $tlfirst) = @_;
2911 my $ok = 1;
2912
2913 # tlfirst is (currently) not passed in by either the installer or
2914 # tlmgr, so it will be always false.
2915 # If it is not defined, we check for the env variable
2916 # TEXLIVE_PREFER_OWN
2917 #
2918 if (!defined($tlfirst)) {
2919 if ($ENV{'TEXLIVE_PREFER_OWN'}) {
2920 debug("setup_programs: TEXLIVE_PREFER_OWN is set!\n");
2921 $tlfirst = 1;
2922 }
2923 }
2924
2925 debug("setup_programs: preferring " . ($tlfirst ? "TL" : "system") . " versions\n");
2926
2927 my $isWin = ($^O =~ /^MSWin/i);
2928
2929 if ($isWin) {
2930 # we need to make sure that we use our own tar, since
2931 # Windows system tar is stupid bsdtar ...
2932 setup_one("w32", 'tar', "$bindir/tar.exe", "--version", 1);
2933 $platform = "exe";
2934 } else {
2935 # tar needs to be provided by the system, we not even check!
2936 $::progs{'tar'} = "tar";
2937
2938 setup_one("unix", "df", undef, "-P .", 0);
2939
2940 if (!defined($platform) || ($platform eq "")) {
2941 # we assume that we run from uncompressed media, so we can call
2942 # platform() and thus also the config.guess script but we have to
2943 # setup $::installerdir because the platform script relies on it
2944 $::installerdir = "$bindir/../..";
2945 $platform = platform();
2946 }
2947 }
2948
2949 # setup of the fallback downloaders
2950 my @working_downloaders;
2951 for my $dltype (@AcceptedFallbackDownloaders) {
2952 my $defprog = $FallbackDownloaderProgram{$dltype};
2953 # do not warn on errors
2954 push @working_downloaders, $dltype if
2955 setup_one(($isWin ? "w32" : "unix"), $defprog,
2956 "$bindir/$dltype/$defprog.$platform", "--version", $tlfirst);
2957 }
2958 # check for curl special stuff on MacOS
2959 if (member("curl", @working_downloaders) && platform() =~ m/darwin/) {
2960 # copied from platform_name
2961 chomp (my $sw_vers = `sw_vers -productVersion`);
2962 my ($os_major,$os_minor) = split (/\./, $sw_vers);
2963 if ($os_major == 10 && ($os_minor == 13 || $os_minor == 14)) {
2964 my @curlargs = @{$TeXLive::TLConfig::FallbackDownloaderArgs{'curl'}};
2965 # can't push new arg at end of list because builtin list ends with
2966 # -o to set the output file.
2967 unshift (@curlargs, '--cacert', "$::installerdir/tlpkg/installer/curl/curl-ca-bundle.crt");
2968 $TeXLive::TLConfig::FallbackDownloaderArgs{'curl'} = \@curlargs;
2969 debug("TLUtils::setup_programs: curl on old darwin, final curl args: @{$TeXLive::TLConfig::FallbackDownloaderArgs{'curl'}}\n");
2970 }
2971 }
2972 # check for wget/ssl support
2973 if (member("wget", @working_downloaders)) {
2974 debug("TLUtils::setup_programs: checking for ssl enabled wget\n");
2975 my @lines = `$::progs{'wget'} --version 2>&1`;
2976 if (grep(/\+ssl/, @lines)) {
2977 $::progs{'options'}{'wget-ssl'} = 1;
2978 my @wgetargs = @{$TeXLive::TLConfig::FallbackDownloaderArgs{'wget'}};
2979 # can't push new arg at end of list because builtin list ends with
2980 # -O to set the output file.
2981 unshift (@wgetargs, '--no-check-certificate');
2982 $TeXLive::TLConfig::FallbackDownloaderArgs{'wget'} = \@wgetargs;
2983 debug("TLUtils::setup_programs: wget has ssl, final wget args: @{$TeXLive::TLConfig::FallbackDownloaderArgs{'wget'}}\n");
2984 } else {
2985 debug("TLUtils::setup_programs: wget without ssl support found\n");
2986 $::progs{'options'}{'wget-ssl'} = 0;
2987 }
2988 }
2989 $::progs{'working_downloaders'} = [ @working_downloaders ];
2990 my @working_compressors;
2991 for my $defprog (sort
2992 { $Compressors{$a}{'priority'} <=> $Compressors{$b}{'priority'} }
2993 keys %Compressors) {
2994 # do not warn on errors
2995 if (setup_one(($isWin ? "w32" : "unix"), $defprog,
2996 "$bindir/$defprog/$defprog.$platform", "--version",
2997 $tlfirst)) {
2998 push @working_compressors, $defprog;
2999 # also set up $::{'compressor'} if not already done
3000 # this selects the first one, but we might reset this depending on
3001 # TEXLIVE_COMPRESSOR setting, see below
3002 defined($::progs{'compressor'}) || ($::progs{'compressor'} = $defprog);
3003 }
3004 }
3005 $::progs{'working_compressors'} = [ @working_compressors ];
3006
3007 # check whether selected downloader/compressor is working
3008 # for downloader we allow 'lwp' as setting, too
3009 if ($ENV{'TEXLIVE_DOWNLOADER'}
3010 && $ENV{'TEXLIVE_DOWNLOADER'} ne 'lwp'
3011 && !TeXLive::TLUtils::member($ENV{'TEXLIVE_DOWNLOADER'},
3012 @{$::progs{'working_downloaders'}})) {
3013 tlwarn(<<END_DOWNLOADER_BAD);
3014 Selected download program TEXLIVE_DOWNLOADER=$ENV{'TEXLIVE_DOWNLOADER'}
3015 is not working!
3016 Please choose a different downloader or don't set TEXLIVE_DOWNLOADER.
3017 Detected working downloaders: @{$::progs{'working_downloaders'}}.
3018 END_DOWNLOADER_BAD
3019 $ok = 0;
3020 }
3021 if ($ENV{'TEXLIVE_COMPRESSOR'}
3022 && !TeXLive::TLUtils::member($ENV{'TEXLIVE_COMPRESSOR'},
3023 @{$::progs{'working_compressors'}})) {
3024 tlwarn(<<END_COMPRESSOR_BAD);
3025 Selected compression program TEXLIVE_COMPRESSOR=$ENV{'TEXLIVE_COMPRESSOR'}
3026 is not working!
3027 Please choose a different compressor or don't set TEXLIVE_COMPRESSOR.
3028 Detected working compressors: @{$::progs{'working_compressors'}}.
3029 END_COMPRESSOR_BAD
3030 $ok = 0;
3031 }
3032 # setup default compressor $::progs{'compressor'} which is used in
3033 # tlmgr in the calls to make_container. By default we have already
3034 # chosen the first that is actually working from our list of
3035 # @AcceptableCompressors, but let the user override this.
3036 if ($ENV{'TEXLIVE_COMPRESSOR'}) {
3037 $::progs{'compressor'} = $ENV{'TEXLIVE_COMPRESSOR'};
3038 }
3039
3040 if ($::opt_verbosity >= 2) {
3041 require Data::Dumper;
3042 # avoid spurious "used only once" warnings due to require
3043 # (warnings restored at end of scope). https://perlmonks.org/?node_id=3333
3044 no warnings 'once';
3045 local $Data::Dumper::Sortkeys = 1; # stable output
3046 local $Data::Dumper::Purity = 1; # reconstruct recursive structures
3047 print STDERR "DD:dumping ";
3048 print STDERR Data::Dumper->Dump([\%::progs], [qw(::progs)]);
3049 }
3050 return $ok;
3051 }
3052
3053 sub setup_one {
3054 my ($what, $p, $def, $arg, $tlfirst) = @_;
3055 my $setupfunc = ($what eq "unix") ? \&setup_unix_tl_one : \&setup_windows_tl_one ;
3056 if ($tlfirst) {
3057 if (&$setupfunc($p, $def, $arg)) {
3058 return(1);
3059 } else {
3060 return(setup_system_one($p, $arg));
3061 }
3062 } else {
3063 if (setup_system_one($p, $arg)) {
3064 return(1);
3065 } else {
3066 return(&$setupfunc($p, $def, $arg));
3067 }
3068 }
3069 }
3070
3071 sub setup_system_one {
3072 my ($p, $arg) = @_;
3073 my $nulldev = nulldev();
3074 ddebug("trying to set up system $p, arg $arg\n");
3075 my $ret = system("$p $arg >$nulldev 2>&1");
3076 if ($ret == 0) {
3077 debug("program $p found in path\n");
3078 $::progs{$p} = $p;
3079 return(1);
3080 } else {
3081 debug("program $p not usable from path\n");
3082 return(0);
3083 }
3084 }
3085
3086 sub setup_windows_tl_one {
3087 my ($p, $def, $arg) = @_;
3088 debug("(w32) trying to set up $p, default $def, arg $arg\n");
3089
3090 if (-r $def) {
3091 my $prog = conv_to_w32_path($def);
3092 my $ret = system("$prog $arg >nul 2>&1"); # on windows
3093 if ($ret == 0) {
3094 debug("Using shipped $def for $p (tested).\n");
3095 $::progs{$p} = $prog;
3096 return(1);
3097 } else {
3098 tlwarn("Setting up $p with $def as $prog didn't work\n");
3099 system("$prog $arg");
3100 return(0);
3101 }
3102 } else {
3103 debug("Default program $def not readable?\n");
3104 return(0);
3105 }
3106 }
3107
3108
3109 # setup one prog on unix using the following logic:
3110 # - if the shipped one is -x and can be executed, use it
3111 # - if the shipped one is -x but cannot be executed, copy it. set -x
3112 # . if the copy is -x and executable, use it
3113 # - if the shipped one is not -x, copy it, set -x
3114 # . if the copy is -x and executable, use it
3115 sub setup_unix_tl_one {
3116 my ($p, $def, $arg) = @_;
3117 if (!$def) {
3118 debug("(unix) no default program for $p, no setup done\n");
3119 return(1);
3120 }
3121 our $tmp;
3122 debug("(unix) trying to set up $p, default $def, arg $arg\n");
3123 if (-r $def) {
3124 if (-x $def) {
3125 ddebug(" Default $def has executable permissions\n");
3126 # we have to check for actual "executability" since a "noexec"
3127 # mount option may interfere, which is not taken into account by -x.
3128 my $ret = system("'$def' $arg >/dev/null 2>&1" ); # we are on Unix
3129 if ($ret == 0) {
3130 $::progs{$p} = $def;
3131 debug(" Using shipped $def for $p (tested).\n");
3132 return(1);
3133 } else {
3134 ddebug(" Shipped $def has -x but cannot be executed, "
3135 . "trying tmp copy.\n");
3136 }
3137 }
3138 # we are still here
3139 # out of some reasons we couldn't execute the shipped program
3140 # try to copy it to a temp directory and make it executable
3141 #
3142 # create tmp dir only when necessary
3143 $tmp = TeXLive::TLUtils::tl_tmpdir() unless defined($tmp);
3144 # probably we are running from uncompressed media and want to copy it to
3145 # some temporary location
3146 copy($def, $tmp);
3147 my $bn = basename($def);
3148 my $tmpprog = "$tmp/$bn";
3149 chmod(0755,$tmpprog);
3150 # we do not check the return value of chmod, but check whether
3151 # the -x bit is now set, the only thing that counts
3152 if (! -x $tmpprog) {
3153 # hmm, something is going really bad, not even the copy is
3154 # executable. Fall back to normal path element
3155 ddebug(" Copied $p $tmpprog does not have -x bit, strange!\n");
3156 return(0);
3157 } else {
3158 # check again for executability
3159 my $ret = system("$tmpprog $arg > /dev/null 2>&1");
3160 if ($ret == 0) {
3161 # ok, the copy works
3162 debug(" Using copied $tmpprog for $p (tested).\n");
3163 $::progs{$p} = $tmpprog;
3164 return(1);
3165 } else {
3166 # even the copied prog is not executable, strange
3167 ddebug(" Copied $p $tmpprog has x bit but not executable?!\n");
3168 return(0);
3169 }
3170 }
3171 } else {
3172 # default program is not readable
3173 return(0);
3174 }
3175 }
3176
3177
3178 =item C<download_file( $relpath, $destination )>
3179
3180 Try to download the file given in C<$relpath> from C<$TeXLiveURL>
3181 into C<$destination>, which can be either
3182 a filename of simply C<|>. In the latter case a file handle is returned.
3183
3184 Downloading first checks for the environment variable C<TEXLIVE_DOWNLOADER>,
3185 which takes various built-in values. If not set, the next check is for
3186 C<TL_DOWNLOAD_PROGRAM> and C<TL_DOWNLOAD_ARGS>. The former overrides the
3187 above specification devolving to C<wget>, and the latter overrides the
3188 default wget arguments.
3189
3190 C<TL_DOWNLOAD_ARGS> must be defined so that the file the output goes to
3191 is the first argument after the C<TL_DOWNLOAD_ARGS>. Thus, for wget it
3192 would end in C<-O>. Use with care.
3193
3194 =cut
3195
3196 sub download_file {
3197 my ($relpath, $dest) = @_;
3198 # create output dir if necessary
3199 my $par;
3200 if ($dest ne "|") {
3201 $par = dirname($dest);
3202 mkdirhier ($par) unless -d "$par";
3203 }
3204 my $url;
3205 if ($relpath =~ m;^file://*(.*)$;) {
3206 my $filetoopen = "/$1";
3207 # $dest is a file name, we have to get the respective dirname
3208 if ($dest eq "|") {
3209 open(RETFH, "<$filetoopen") or
3210 die("Cannot open $filetoopen for reading");
3211 # opening to a pipe always succeeds, so we return immediately
3212 return \*RETFH;
3213 } else {
3214 if (-r $filetoopen) {
3215 copy ("-f", "-L", $filetoopen, $dest);
3216 return 1;
3217 }
3218 return 0;
3219 }
3220 }
3221
3222 if ($relpath =~ m!$SshURIRegex!) {
3223 my $downdest;
3224 if ($dest eq "|") {
3225 my ($fh, $fn) = TeXLive::TLUtils::tl_tmpfile();
3226 $downdest = $fn;
3227 } else {
3228 $downdest = $dest;
3229 }
3230 # massage ssh:// into the scp-acceptable scp://
3231 $relpath =~ s!^ssh://!scp://!;
3232 my $retval = system("scp", "-q", $relpath, $downdest);
3233 if ($retval != 0) {
3234 $retval /= 256 if $retval > 0;
3235 my $pwd = cwd ();
3236 tlwarn("$0: system(scp -q $relpath $downdest) failed in $pwd, status $retval");
3237 return 0;
3238 }
3239 if ($dest eq "|") {
3240 open(RETFH, "<$downdest") or
3241 die("Cannot open $downdest for reading");
3242 # opening to a pipe always succeeds, so we return immediately
3243 return \*RETFH;
3244 } else {
3245 return 1;
3246 }
3247 }
3248
3249 if ($relpath =~ /^(https?|ftp):\/\//) {
3250 $url = $relpath;
3251 } else {
3252 $url = "$TeXLiveURL/$relpath";
3253 }
3254
3255 my @downloader_trials;
3256 if ($ENV{'TEXLIVE_DOWNLOADER'}) {
3257 push @downloader_trials, $ENV{'TEXLIVE_DOWNLOADER'};
3258 } elsif ($ENV{"TL_DOWNLOAD_PROGRAM"}) {
3259 push @downloader_trials, 'custom';
3260 } else {
3261 @downloader_trials = qw/lwp curl wget/;
3262 }
3263
3264 my $success = 0;
3265 for my $downtype (@downloader_trials) {
3266 if ($downtype eq 'lwp') {
3267 if (_download_file_lwp($url, $dest)) {
3268 $success = $downtype;
3269 last;
3270 }
3271 }
3272 if ($downtype eq "custom" || TeXLive::TLUtils::member($downtype, @{$::progs{'working_downloaders'}})) {
3273 if (_download_file_program($url, $dest, $downtype)) {
3274 $success = $downtype;
3275 last;
3276 }
3277 }
3278 }
3279 if ($success) {
3280 debug("TLUtils::download_file: downloading using $success succeeded\n");
3281 return(1);
3282 } else {
3283 debug("TLUtils::download_file: tried to download using @downloader_trials, none succeeded\n");
3284 return(0);
3285 }
3286 }
3287
3288
3289 sub _download_file_lwp {
3290 my ($url, $dest) = @_;
3291 if (!defined($::tldownload_server)) {
3292 ddebug("::tldownload_server not defined\n");
3293 return(0);
3294 }
3295 if (!$::tldownload_server->enabled) {
3296 # try to reinitialize a disabled connection
3297 # disabling happens after 6 failed download trials
3298 # we just re-initialize the connection
3299 if (!setup_persistent_downloads()) {
3300 # setup failed, give up
3301 debug("reinitialization of LWP download failed\n");
3302 return(0);
3303 }
3304 # we don't need to check for ->enabled, because
3305 # setup_persistent_downloads calls TLDownload->new()
3306 # which, if it succeeds, automatically set enabled to 1
3307 }
3308 # we are still here, so try to download
3309 debug("persistent connection set up, trying to get $url (for $dest)\n");
3310 my $ret = $::tldownload_server->get_file($url, $dest);
3311 if ($ret) {
3312 ddebug("downloading file via persistent connection succeeded\n");
3313 return $ret;
3314 } else {
3315 debug("TLUtils::download_file: persistent connection ok,"
3316 . " but download failed: $url\n");
3317 debug("TLUtils::download_file: retrying with other downloaders.\n");
3318 }
3319 # if we are still here, download with LWP didn't succeed.
3320 return(0);
3321 }
3322
3323
3324 sub _download_file_program {
3325 my ($url, $dest, $type) = @_;
3326 if (wndws()) {
3327 $dest =~ s!/!\\!g;
3328 }
3329
3330 debug("TLUtils::_download_file_program: $type $url $dest\n");
3331 my $downloader;
3332 my $downloaderargs;
3333 my @downloaderargs;
3334 if ($type eq 'custom') {
3335 $downloader = $ENV{"TL_DOWNLOAD_PROGRAM"};
3336 if ($ENV{"TL_DOWNLOAD_ARGS"}) {
3337 $downloaderargs = $ENV{"TL_DOWNLOAD_ARGS"};
3338 @downloaderargs = split(' ', $downloaderargs);
3339 }
3340 } else {
3341 $downloader = $::progs{$FallbackDownloaderProgram{$type}};
3342 @downloaderargs = @{$FallbackDownloaderArgs{$type}};
3343 $downloaderargs = join(' ',@downloaderargs);
3344 }
3345
3346 debug("downloading $url using $downloader $downloaderargs\n");
3347 my $ret;
3348 if ($dest eq "|") {
3349 open(RETFH, "$downloader $downloaderargs - $url|")
3350 || die "open($url) via $downloader $downloaderargs failed: $!";
3351 # opening to a pipe always succeeds, so we return immediately
3352 return \*RETFH;
3353 } else {
3354 $ret = system ($downloader, @downloaderargs, $dest, $url);
3355 # we have to reverse the meaning of ret because system has 0=success.
3356 $ret = ($ret ? 0 : 1);
3357 }
3358 # return false/undef in case the download did not succeed.
3359 return ($ret) unless $ret;
3360 debug("download of $url succeeded\n");
3361 if ($dest eq "|") {
3362 return \*RETFH;
3363 } else {
3364 return 1;
3365 }
3366 }
3367
3368 =item C<nulldev ()>
3369
3370 Return C</dev/null> on Unix and C<nul> on Windows.
3371
3372 =cut
3373
3374 sub nulldev {
3375 return (&wndws()) ? 'nul' : '/dev/null';
3376 }
3377
3378 =item C<get_full_line ($fh)>
3379
3380 returns the next line from the file handle $fh, taking
3381 continuation lines into account (last character of a line is \, and
3382 no quoting is parsed).
3383
3384 =cut
3385
3386 # open my $f, '<', $file_name or die;
3387 # while (my $l = get_full_line($f)) { ... }
3388 # close $f or die;
3389 sub get_full_line {
3390 my ($fh) = @_;
3391 my $line = <$fh>;
3392 return undef unless defined $line;
3393 return $line unless $line =~ s/\\\r?\n$//;
3394 my $cont = get_full_line($fh);
3395 if (!defined($cont)) {
3396 tlwarn('Continuation disallowed at end of file');
3397 $cont = "";
3398 }
3399 $cont =~ s/^\s*//;
3400 return $line . $cont;
3401 }
3402
3403
3404 =back
3405
3406 =head2 Installer Functions
3407
3408 =over 4
3409
3410 =item C<make_var_skeleton($prefix)>
3411
3412 Generate a skeleton of empty directories in the C<TEXMFSYSVAR> tree.
3413
3414 =cut
3415
3416 sub make_var_skeleton {
3417 my ($prefix) = @_;
3418
3419 mkdirhier "$prefix/tex/generic/config";
3420 mkdirhier "$prefix/fonts/map/dvipdfmx/updmap";
3421 mkdirhier "$prefix/fonts/map/dvips/updmap";
3422 mkdirhier "$prefix/fonts/map/pdftex/updmap";
3423 mkdirhier "$prefix/fonts/pk";
3424 mkdirhier "$prefix/fonts/tfm";
3425 mkdirhier "$prefix/web2c";
3426 mkdirhier "$prefix/xdvi";
3427 mkdirhier "$prefix/tex/context/config";
3428 }
3429
3430
3431 =item C<make_local_skeleton($prefix)>
3432
3433 Generate a skeleton of empty directories in the C<TEXMFLOCAL> tree,
3434 unless C<TEXMFLOCAL> already exists.
3435
3436 =cut
3437
3438 sub make_local_skeleton {
3439 my ($prefix) = @_;
3440
3441 return if (-d $prefix);
3442
3443 mkdirhier "$prefix/bibtex/bib/local";
3444 mkdirhier "$prefix/bibtex/bst/local";
3445 mkdirhier "$prefix/doc/local";
3446 mkdirhier "$prefix/dvips/local";
3447 mkdirhier "$prefix/fonts/source/local";
3448 mkdirhier "$prefix/fonts/tfm/local";
3449 mkdirhier "$prefix/fonts/type1/local";
3450 mkdirhier "$prefix/fonts/vf/local";
3451 mkdirhier "$prefix/metapost/local";
3452 mkdirhier "$prefix/tex/latex/local";
3453 mkdirhier "$prefix/tex/plain/local";
3454 mkdirhier "$prefix/tlpkg";
3455 mkdirhier "$prefix/web2c";
3456 }
3457
3458
3459 =item C<create_fmtutil($tlpdb, $dest)>
3460
3461 =item C<create_updmap($tlpdb, $dest)>
3462
3463 =item C<create_language_dat($tlpdb, $dest, $localconf)>
3464
3465 =item C<create_language_def($tlpdb, $dest, $localconf)>
3466
3467 =item C<create_language_lua($tlpdb, $dest, $localconf)>
3468
3469 These five functions create C<fmtutil.cnf>, C<updmap.cfg>, C<language.dat>,
3470 C<language.def>, and C<language.dat.lua> respectively, in C<$dest> (which by
3471 default is below C<$TEXMFSYSVAR>). These functions merge the information
3472 present in the TLPDB C<$tlpdb> (formats, maps, hyphenations) with local
3473 configuration additions: C<$localconf>.
3474
3475 Currently the merging is done by omitting disabled entries specified
3476 in the local file, and then appending the content of the local
3477 configuration files at the end of the file. We should also check for
3478 duplicates, maybe even error checking.
3479
3480 =cut
3481
3482 #
3483 # get_disabled_local_configs
3484 # returns the list of disabled formats/hyphenpatterns/maps
3485 # disabling is done by putting
3486 # #!NAME
3487 # or
3488 # %!NAME
3489 # into the respective foo-local.cnf/cfg file
3490 #
3491 sub get_disabled_local_configs {
3492 my $localconf = shift;
3493 my $cc = shift;
3494 my @disabled = ();
3495 if ($localconf && -r $localconf) {
3496 open (FOO, "<$localconf")
3497 || die "strange, -r ok but open($localconf) failed: $!";
3498 my @tmp = <FOO>;
3499 close(FOO) || warn("close($localconf) failed: $!");
3500 @disabled = map { if (m/^$cc!(\S+)\s*$/) { $1 } else { } } @tmp;
3501 }
3502 return @disabled;
3503 }
3504
3505 sub create_fmtutil {
3506 my ($tlpdb,$dest) = @_;
3507 my @lines = $tlpdb->fmtutil_cnf_lines();
3508 _create_config_files($tlpdb, "texmf-dist/web2c/fmtutil-hdr.cnf", $dest,
3509 undef, 0, '#', \@lines);
3510 }
3511
3512 sub create_updmap {
3513 my ($tlpdb,$dest) = @_;
3514 check_for_old_updmap_cfg();
3515 my @tlpdblines = $tlpdb->updmap_cfg_lines();
3516 _create_config_files($tlpdb, "texmf-dist/web2c/updmap-hdr.cfg", $dest,
3517 undef, 0, '#', \@tlpdblines);
3518 }
3519
3520 sub check_for_old_updmap_cfg {
3521 chomp( my $tmfsysconf = `kpsewhich -var-value=TEXMFSYSCONFIG` ) ;
3522 my $oldupd = "$tmfsysconf/web2c/updmap.cfg";
3523 return unless -r $oldupd; # if no such file, good.
3524
3525 open (OLDUPD, "<$oldupd") || die "open($oldupd) failed: $!";
3526 my $firstline = <OLDUPD>;
3527 close(OLDUPD);
3528 # cygwin returns undef when reading from an empty file, we have
3529 # to make sure that this is anyway initialized
3530 $firstline = "" if (!defined($firstline));
3531 chomp ($firstline);
3532 #
3533 if ($firstline =~ m/^# Generated by (install-tl|.*\/tlmgr) on/) {
3534 # assume it was our doing, rename it.
3535 my $nn = "$oldupd.DISABLED";
3536 if (-r $nn) {
3537 my $fh;
3538 ($fh, $nn) = tl_tmpfile(
3539 "updmap.cfg.DISABLED.XXXXXX", DIR => "$tmfsysconf/web2c");
3540 }
3541 print "Renaming old config file from
3542 $oldupd
3543 to
3544 $nn
3545 ";
3546 if (rename($oldupd, $nn)) {
3547 if (system("mktexlsr", $tmfsysconf) != 0) {
3548 die "mktexlsr $tmfsysconf failed after updmap.cfg rename, fix fix: $!";
3549 }
3550 print "No further action should be necessary.\n";
3551 } else {
3552 print STDERR "
3553 Renaming of
3554 $oldupd
3555 did not succeed. This config file should not be used anymore,
3556 so please do what's necessary to eliminate it.
3557 See the documentation for updmap.
3558 ";
3559 }
3560
3561 } else { # first line did not match
3562 # that is NOT a good idea, because updmap creates updmap.cfg in
3563 # TEXMFSYSCONFIG when called with --enable Map etc, so we should
3564 # NOT warn here
3565 # print STDERR "Apparently
3566 # $oldupd
3567 # was created by hand. This config file should not be used anymore,
3568 # so please do what's necessary to eliminate it.
3569 # See the documentation for updmap.
3570 # ";
3571 }
3572 }
3573
3574 sub check_updmap_config_value {
3575 my ($k, $v, $f) = @_;
3576 return 0 if !defined($k);
3577 return 0 if !defined($v);
3578 if (member( $k, qw/dvipsPreferOutline dvipsDownloadBase35
3579 pdftexDownloadBase14 dvipdfmDownloadBase14/)) {
3580 if ($v eq "true" || $v eq "false") {
3581 return 1;
3582 } else {
3583 tlwarn("Unknown setting for $k in $f: $v\n");
3584 return 0;
3585 }
3586 } elsif ($k eq "LW35") {
3587 if (member($v, qw/URW URWkb ADOBE ADOBEkb/)) {
3588 return 1;
3589 } else {
3590 tlwarn("Unknown setting for LW35 in $f: $v\n");
3591 return 0;
3592 }
3593 } elsif ($k eq "kanjiEmbed") {
3594 # any string is fine
3595 return 1;
3596 } else {
3597 return 0;
3598 }
3599 }
3600
3601 sub create_language_dat {
3602 my ($tlpdb,$dest,$localconf) = @_;
3603 # no checking for disabled stuff for language.dat and .def
3604 my @lines = $tlpdb->language_dat_lines(
3605 get_disabled_local_configs($localconf, '%'));
3606 _create_config_files($tlpdb, "texmf-dist/tex/generic/config/language.us",
3607 $dest, $localconf, 0, '%', \@lines);
3608 }
3609
3610 sub create_language_def {
3611 my ($tlpdb,$dest,$localconf) = @_;
3612 # no checking for disabled stuff for language.dat and .def
3613 my @lines = $tlpdb->language_def_lines(
3614 get_disabled_local_configs($localconf, '%'));
3615 my @postlines;
3616 push @postlines, "%%% No changes may be made beyond this point.\n";
3617 push @postlines, "\n";
3618 push @postlines, "\\uselanguage {USenglish} %%% This MUST be the last line of the file.\n";
3619 _create_config_files ($tlpdb,"texmf-dist/tex/generic/config/language.us.def",
3620 $dest, $localconf, 1, '%', \@lines, @postlines);
3621 }
3622
3623 sub create_language_lua {
3624 my ($tlpdb,$dest,$localconf) = @_;
3625 # no checking for disabled stuff for language.dat and .lua
3626 my @lines = $tlpdb->language_lua_lines(
3627 get_disabled_local_configs($localconf, '--'));
3628 my @postlines = ("}\n");
3629 _create_config_files ($tlpdb,"texmf-dist/tex/generic/config/language.us.lua",
3630 $dest, $localconf, 0, '--', \@lines, @postlines);
3631 }
3632
3633 sub _create_config_files {
3634 my ($tlpdb, $headfile, $dest,$localconf, $keepfirstline, $cc,
3635 $tlpdblinesref, @postlines) = @_;
3636 my $root = $tlpdb->root;
3637 my @lines = ();
3638 my $usermode = $tlpdb->setting( "usertree" );
3639 if (-r "$root/$headfile") {
3640 open (INFILE, "<$root/$headfile")
3641 || die "open($root/$headfile) failed, but -r ok: $!";
3642 @lines = <INFILE>;
3643 close (INFILE);
3644 } elsif (!$usermode) {
3645 # we might be in user mode and then do *not* want the generation
3646 # of the configuration file to just bail out.
3647 tldie ("TLUtils::_create_config_files: giving up, unreadable: "
3648 . "$root/$headfile\n")
3649 }
3650 push @lines, @$tlpdblinesref;
3651 if (defined($localconf) && -r $localconf) {
3652 #
3653 # this should be done more intelligently, but for now only add those
3654 # lines without any duplication check ...
3655 open (FOO, "<$localconf")
3656 || die "strange, -r ok but cannot open $localconf: $!";
3657 my @tmp = <FOO>;
3658 close (FOO);
3659 push @lines, @tmp;
3660 }
3661 if (@postlines) {
3662 push @lines, @postlines;
3663 }
3664 if ($usermode && -e $dest) {
3665 tlwarn("Updating $dest, backup copy in $dest.backup\n");
3666 copy("-f", $dest, "$dest.backup");
3667 }
3668 # ensure destination directory exists.
3669 my $destdir = dirname ($dest);
3670 -d $destdir || mkdirhier $destdir; # if fails, the next open will die.
3671 open(OUTFILE,">$dest")
3672 or die("Cannot open $dest for writing: $!");
3673
3674 if (!$keepfirstline) {
3675 print OUTFILE $cc;
3676 printf OUTFILE " Generated by %s on %s\n", "$0", scalar localtime;
3677 }
3678 print OUTFILE @lines;
3679 close(OUTFILE) || warn "close(>$dest) failed: $!";
3680 }
3681
3682 #
3683 sub parse_AddHyphen_line {
3684 my $line = shift;
3685 my %ret;
3686 # default values
3687 my $default_lefthyphenmin = -1;
3688 my $default_righthyphenmin = -1;
3689 $ret{"synonyms"} = [];
3690 $ret{"databases"} = ["dat", "def", "lua"];
3691 for my $p (quotewords('\s+', 0, "$line")) {
3692 my ($a, $b) = split /=/, $p;
3693 if ($a eq "name") {
3694 if (!$b) {
3695 $ret{"error"} = "AddHyphen line needs name=something: $line";
3696 return %ret;
3697 }
3698 $ret{"name"} = $b;
3699 next;
3700 }
3701 if ($a eq "lefthyphenmin") {
3702 if (! defined $b) {
3703 $ret{"error"} = "AddHyphen line needs lefthyphenmin=something: $line";
3704 return %ret;
3705 }
3706 $ret{"lefthyphenmin"} = $b;
3707 next;
3708 }
3709 if ($a eq "righthyphenmin") {
3710 if (! defined $b) {
3711 $ret{"error"} = "AddHyphen line needs righthyphenmin=something: $line";
3712 return %ret;
3713 }
3714 $ret{"righthyphenmin"} = $b;
3715 next;
3716 }
3717 if ($a eq "file") {
3718 if (!$b) {
3719 $ret{"error"} = "AddHyphen line needs file=something: $line ";
3720 return %ret;
3721 }
3722 $ret{"file"} = $b;
3723 next;
3724 }
3725 if ($a eq "file_patterns") {
3726 # many are blank in hyph-utf8, don't check.
3727 $ret{"file_patterns"} = $b;
3728 next;
3729 }
3730 if ($a eq "file_exceptions") {
3731 # many are blank in hyph-utf8, don't check.
3732 $ret{"file_exceptions"} = $b;
3733 next;
3734 }
3735 if ($a eq "luaspecial") {
3736 if (!$b) {
3737 $ret{"error"} = "AddHyphen line needs luaspecial=something: $line";
3738 return %ret;
3739 }
3740 $ret{"luaspecial"} = $b;
3741 next;
3742 }
3743 if ($a eq "databases") {
3744 if (!$b) {
3745 $ret{"error"} = "AddHyphen line needs databases=foo[,bar]: $line";
3746 return %ret;
3747 }
3748 @{$ret{"databases"}} = split /,/, $b;
3749 next;
3750 }
3751 if ($a eq "synonyms") {
3752 if (!$b) {
3753 $ret{"error"} = "AddHyphen line needs synonyms=foo[,bar]: $line";
3754 return %ret;
3755 }
3756 @{$ret{"synonyms"}} = split /,/, $b;
3757 next;
3758 }
3759 if ($a eq "comment") {
3760 $ret{"comment"} = $b;
3761 next;
3762 }
3763 # should not be reached at all
3764 $ret{"error"} = "Unknown AddHyphen directive $a: $line";
3765 return %ret;
3766 }
3767 if (! $ret{"name"}) {
3768 $ret{"error"} = "AddHyphen is missing name setting: $line";
3769 return %ret;
3770 }
3771 if ($ret{"lefthyphenmin"} !~ /^[0-9]$/) {
3772 $ret{"lefthyphenmin"} = "" if ! $ret{"lefthyphenmin"}; #undef warning
3773 $ret{"error"} = "AddHyphen has missing or bad "
3774 . " lefthyphenmin ($ret{lefthyphenmin}): $line";
3775 return %ret;
3776 }
3777 if ($ret{"righthyphenmin"} !~ /^[0-9]$/) {
3778 $ret{"righthyphenmin"} = "" if ! $ret{"righthyphenmin"}; #undef warning
3779 $ret{"error"} = "AddHyphen has missing or bad "
3780 . " righthyphenmin ($ret{righthyphenmin}): $line";
3781 return %ret;
3782 }
3783 return %ret;
3784 }
3785
3786 #
3787 # return hash of items on AddFormat line LINE (which must not have the
3788 # leading "execute AddFormat"). If parse fails, hash will contain a key
3789 # "error" with a message.
3790 #
3791 sub parse_AddFormat_line {
3792 my $line = shift;
3793 my %ret;
3794 $ret{"options"} = "";
3795 $ret{"patterns"} = "-";
3796 $ret{"mode"} = 1;
3797 for my $p (quotewords('\s+', 0, "$line")) {
3798 my ($a, $b);
3799 if ($p =~ m/^(name|engine|mode|patterns|options|fmttriggers)=(.*)$/) {
3800 $a = $1;
3801 $b = $2;
3802 } else {
3803 $ret{"error"} = "Unknown format directive $p";
3804 return %ret;
3805 }
3806 if ($a eq "name") {
3807 if (!$b) {
3808 $ret{"error"} = "AddFormat line needs name=something";
3809 return %ret;
3810 }
3811 $ret{"name"} = $b;
3812 next;
3813 }
3814 if ($a eq "engine") {
3815 if (!$b) {
3816 $ret{"error"} = "AddFormat line needs engine=something";
3817 return %ret;
3818 }
3819 $ret{"engine"} = $b;
3820 next;
3821 }
3822 if ($a eq "patterns") {
3823 $ret{"patterns"} = ( $b ? $b : "-" );
3824 next;
3825 }
3826 if ($a eq "mode") {
3827 $ret{"mode"} = ( $b eq "disabled" ? 0 : 1 );
3828 next;
3829 }
3830 if ($a eq "options") {
3831 $ret{"options"} = ( $b ? $b : "" );
3832 next;
3833 }
3834 if ($a eq "fmttriggers") {
3835 my @tl = split(',',$b);
3836 $ret{"fmttriggers"} = \@tl ;
3837 next;
3838 }
3839 # should not be reached at all
3840 $ret{"error"} = "Unknown format directive $p";
3841 return %ret;
3842 }
3843 return %ret;
3844 }
3845
3846 =back
3847
3848 =head2 Logging
3849
3850 Logging and debugging messages.
3851
3852 =over 4
3853
3854 =item C<logit($out,$level,@rest)>
3855
3856 Internal routine to write message to both C<$out> (references to
3857 filehandle) and C<$::LOGFILE>, at level C<$level>, of concatenated items
3858 in C<@rest>. If the log file is not initialized yet, the message is
3859 saved to be logged later (unless the log file never comes into existence).
3860
3861 =cut
3862
3863 sub logit {
3864 my ($out, $level, @rest) = @_;
3865 _logit($out, $level, @rest) unless $::opt_quiet;
3866 _logit('file', $level, @rest);
3867 }
3868
3869 sub _logit {
3870 my ($out, $level, @rest) = @_;
3871 if ($::opt_verbosity >= $level) {
3872 # if $out is a ref/glob to STDOUT or STDERR, print it there
3873 if (ref($out) eq "GLOB") {
3874 print $out @rest;
3875 } else {
3876 # we should log it into the logfile, but that might be not initialized
3877 # so either print it to the filehandle $::LOGFILE, or push it onto
3878 # the to be printed log lines @::LOGLINES
3879 if (defined($::LOGFILE)) {
3880 print $::LOGFILE @rest;
3881 } else {
3882 push (@::LOGLINES, join ("", @rest));
3883 }
3884 }
3885 }
3886 }
3887
3888 =item C<info ($str1, $str2, ...)>
3889
3890 Write a normal informational message, the concatenation of the argument
3891 strings. The message will be written unless C<-q> was specified. If
3892 the global C<$::machinereadable> is set (the C<--machine-readable>
3893 option to C<tlmgr>), then output is written to stderr, else to stdout.
3894 If the log file (see L<process_logging_options>) is defined, it also
3895 writes there.
3896
3897 It is best to use this sparingly, mainly to give feedback during lengthy
3898 operations and for final results.
3899
3900 =cut
3901
3902 sub info {
3903 my $str = join("", @_);
3904 my $fh = ($::machinereadable ? \*STDERR : \*STDOUT);
3905 logit($fh, 0, $str);
3906 for my $i (@::info_hook) {
3907 &{$i}($str);
3908 }
3909 }
3910
3911 =item C<debug ($str1, $str2, ...)>
3912
3913 Write a debugging message, the concatenation of the argument strings.
3914 The message will be omitted unless C<-v> was specified. If the log
3915 file (see L<process_logging_options>) is defined, it also writes there.
3916
3917 This first level debugging message reports on the overall flow of
3918 work, but does not include repeated messages about processing of each
3919 package.
3920
3921 =cut
3922
3923 sub debug {
3924 return if ($::opt_verbosity < 1);
3925 my $str = "D:" . join("", @_);
3926 logit(\*STDERR, 1, $str);
3927 for my $i (@::debug_hook) {
3928 &{$i}($str);
3929 }
3930 }
3931
3932 =item C<ddebug ($str1, $str2, ...)>
3933
3934 Write a deep debugging message, the concatenation of the argument
3935 strings. The message will be omitted unless C<-v -v> (or higher) was
3936 specified. If the log file (see L<process_logging_options>) is defined,
3937 it also writes there.
3938
3939 This second level debugging message reports messages about processing
3940 each package, in addition to the first level.
3941
3942 =cut
3943
3944 sub ddebug {
3945 return if ($::opt_verbosity < 2);
3946 my $str = "DD:" . join("", @_);
3947 logit(\*STDERR, 2, $str);
3948 for my $i (@::ddebug_hook) {
3949 &{$i}($str);
3950 }
3951 }
3952
3953 =item C<dddebug ($str1, $str2, ...)>
3954
3955 Write the deepest debugging message, the concatenation of the argument
3956 strings. The message will be omitted unless C<-v -v -v> was specified.
3957 If the log file (see L<process_logging_options>) is defined, it also
3958 writes there.
3959
3960 In addition to the first and second levels, this third level debugging
3961 message reports messages about processing each line of any tlpdb files
3962 read, and messages about files tested or matched against tlpsrc
3963 patterns. This output is extremely voluminous, so unless you're
3964 debugging those parts of the code, it just gets in the way.
3965
3966 =cut
3967
3968 sub dddebug {
3969 return if ($::opt_verbosity < 3);
3970 my $str = "DDD:" . join("", @_);
3971 logit(\*STDERR, 3, $str);
3972 for my $i (@::dddebug_hook) {
3973 &{$i}($str);
3974 }
3975 }
3976
3977 =item C<log ($str1, $str2, ...)>
3978
3979 Write a message to the log file (and nowhere else), the concatenation of
3980 the argument strings. The log file may not ever be defined (e.g., the
3981 C<-logfile> option isn't given), in which case the message will never be
3982 written anywhere.
3983
3984 =cut
3985
3986 sub log {
3987 my $savequiet = $::opt_quiet;
3988 $::opt_quiet = 0;
3989 _logit('file', -100, @_);
3990 $::opt_quiet = $savequiet;
3991 }
3992
3993 =item C<tlwarn ($str1, $str2, ...)>
3994
3995 Write a warning message, the concatenation of the argument strings.
3996 This always and unconditionally writes the message to standard error; if
3997 the log file (see L<process_logging_options>) is defined, it also writes
3998 there.
3999
4000 =cut
4001
4002 sub tlwarn {
4003 my $savequiet = $::opt_quiet;
4004 my $str = join("", @_);
4005 $::opt_quiet = 0;
4006 logit (\*STDERR, -100, $str);
4007 $::opt_quiet = $savequiet;
4008 for my $i (@::warn_hook) {
4009 &{$i}($str);
4010 }
4011 }
4012
4013 =item C<tldie ($str1, $str2, ...)>
4014
4015 Uses C<tlwarn> to issue a warning for @_ preceded by a newline, then
4016 exits with exit code 1.
4017
4018 =cut
4019
4020 sub tldie {
4021 tlwarn("\n", @_);
4022 if ($::gui_mode) {
4023 Tk::exit(1);
4024 } else {
4025 exit(1);
4026 }
4027 }
4028
4029 =item C<debug_hash_str($label, HASH)>
4030
4031 Return LABEL followed by HASH elements, followed by a newline, as a
4032 single string. If HASH is a reference, it is followed (but no recursive
4033 derefencing).
4034
4035 =item C<debug_hash($label, HASH)>
4036
4037 Write the result of C<debug_hash_str> to stderr.
4038
4039 =cut
4040
4041 sub debug_hash_str {
4042 my ($label) = shift;
4043 my (%hash) = (ref $_[0] && $_[0] =~ /.*HASH.*/) ? %{$_[0]} : @_;
4044
4045 my $str = "$label: {";
4046 my @items = ();
4047 for my $key (sort keys %hash) {
4048 my $val = $hash{$key};
4049 $val = ".undef" if ! defined $val;
4050 $key =~ s/\n/\\n/g;
4051 $val =~ s/\n/\\n/g;
4052 push (@items, "$key:$val");
4053 }
4054 $str .= join (",", @items);
4055 $str .= "}";
4056
4057 return "$str\n";
4058 }
4059
4060 sub debug_hash {
4061 warn &debug_hash_str(@_);
4062 }
4063
4064 =item C<backtrace()>
4065
4066 Return call(er) stack, as a string.
4067
4068 =cut
4069
4070 sub backtrace {
4071 my $ret = "";
4072
4073 my ($filename, $line, $subr);
4074 my $stackframe = 1; # skip ourselves
4075 while ((undef,$filename,$line,$subr) = caller ($stackframe)) {
4076 # the undef is for the package, which is already included in $subr.
4077 $ret .= " -> ${filename}:${line}: ${subr}\n";
4078 $stackframe++;
4079 }
4080
4081 return $ret;
4082 }
4083
4084 =item C<process_logging_options ($texdir)>
4085
4086 This function handles the common logging options for TeX Live scripts.
4087 It should be called before C<GetOptions> for any program-specific option
4088 handling. For our conventional calling sequence, see (for example) the
4089 L<tlpfiles> script.
4090
4091 These are the options handled here:
4092
4093 =over 4
4094
4095 =item B<-q>
4096
4097 Omit normal informational messages.
4098
4099 =item B<-v>
4100
4101 Include debugging messages. With one C<-v>, reports overall flow; with
4102 C<-v -v> (or C<-vv>), also reports per-package processing; with C<-v -v
4103 -v> (or C<-vvv>), also reports each line read from any tlpdb files.
4104 Further repeats of C<-v>, as in C<-v -v -v -v>, are accepted but
4105 ignored. C<-vvvv> is an error.
4106
4107 The idea behind these levels is to be able to specify C<-v> to get an
4108 overall idea of what is going on, but avoid terribly voluminous output
4109 when processing many packages, as we often are. When debugging a
4110 specific problem with a specific package, C<-vv> can help. When
4111 debugging problems with parsing tlpdb files, C<-vvv> gives that too.
4112
4113 =item B<-logfile> I<file>
4114
4115 Write all messages (informational, debugging, warnings) to I<file>, in
4116 addition to standard output or standard error. In TeX Live, only the
4117 installer sets a log file by default; none of the other standard TeX
4118 Live scripts use this feature, but you can specify it explicitly.
4119
4120 =back
4121
4122 See also the L<info>, L<debug>, L<ddebug>, and L<tlwarn> functions,
4123 which actually write the messages.
4124
4125 =cut
4126
4127 sub process_logging_options {
4128 $::opt_verbosity = 0;
4129 $::opt_quiet = 0;
4130 my $opt_logfile;
4131 my $opt_Verbosity = 0;
4132 my $opt_VERBOSITY = 0;
4133 # check all the command line options for occurrences of -q and -v;
4134 # do not report errors.
4135 my $oldconfig = Getopt::Long::Configure(qw(pass_through permute));
4136 GetOptions("logfile=s" => \$opt_logfile,
4137 "v+" => \$::opt_verbosity,
4138 "vv" => \$opt_Verbosity,
4139 "vvv" => \$opt_VERBOSITY,
4140 "q" => \$::opt_quiet);
4141 Getopt::Long::Configure($oldconfig);
4142
4143 # verbosity level, forcing -v -v instead of -vv is too annoying.
4144 $::opt_verbosity = 2 if $opt_Verbosity;
4145 $::opt_verbosity = 3 if $opt_VERBOSITY;
4146
4147 # open log file if one was requested.
4148 if ($opt_logfile) {
4149 open(TLUTILS_LOGFILE, ">$opt_logfile")
4150 || die "open(>$opt_logfile) failed: $!\n";
4151 $::LOGFILE = \*TLUTILS_LOGFILE;
4152 $::LOGFILENAME = $opt_logfile;
4153 }
4154 }
4155
4156 =back
4157
4158 =head2 Miscellaneous
4159
4160 A few ideas from Fabrice Popineau's C<FileUtils.pm>.
4161
4162 =over 4
4163
4164 =item C<sort_uniq(@list)>
4165
4166 The C<sort_uniq> function sorts the given array and throws away multiple
4167 occurrences of elements. It returns a sorted and unified array.
4168
4169 =cut
4170
4171 sub sort_uniq {
4172 my (@l) = @_;
4173 my ($e, $f, @r);
4174 $f = "";
4175 @l = sort(@l);
4176 foreach $e (@l) {
4177 if ($e ne $f) {
4178 $f = $e;
4179 push @r, $e;
4180 }
4181 }
4182 return @r;
4183 }
4184
4185
4186 =item C<push_uniq(\@list, @new_items)>
4187
4188 The C<push_uniq> function pushes each element in the last argument
4189 @ITEMS to the $LIST referenced by the first argument, if it is not
4190 already in the list.
4191
4192 =cut
4193
4194 sub push_uniq {
4195 my ($l, @new_items) = @_;
4196 for my $e (@new_items) {
4197 # turns out this is one of the most-used functions when updating the
4198 # tlpdb, with hundreds of thousands of calls. So let's write it out
4199 # to eliminate the sub overhead.
4200 #if (! &member($e, @$l)) {
4201 if (! scalar grep($_ eq $e, @$l)) {
4202 push (@$l, $e);
4203 }
4204 }
4205 }
4206
4207 =item C<member($item, @list)>
4208
4209 The C<member> function returns true if the first argument
4210 is also inclued in the list of the remaining arguments.
4211
4212 =cut
4213
4214 sub member {
4215 my $what = shift;
4216 return scalar grep($_ eq $what, @_);
4217 }
4218
4219 =item C<merge_into(\%to, \%from)>
4220
4221 Merges the keys of %from into %to.
4222
4223 =cut
4224
4225 sub merge_into {
4226 my ($to, $from) = @_;
4227 foreach my $k (keys %$from) {
4228 if (defined($to->{$k})) {
4229 push @{$to->{$k}}, @{$from->{$k}};
4230 } else {
4231 $to->{$k} = [ @{$from->{$k}} ];
4232 }
4233 }
4234 }
4235
4236 =item C<texdir_check($texdir)>
4237
4238 Test whether installation with TEXDIR set to $texdir should be ok, e.g.,
4239 would be a creatable directory. Return 1 if ok, 0 if not.
4240
4241 Writable or not, we will not allow installation to the root
4242 directory (Unix) or the root of a drive (Windows).
4243
4244 We also do not allow paths containing various special characters, and
4245 print a message about this if second argument WARN is true. (We only
4246 want to do this for the regular text installer, since spewing output in
4247 a GUI program wouldn't be good; the generic message will have to do for
4248 them.)
4249
4250 =cut
4251
4252 sub texdir_check {
4253 my ($orig_texdir,$warn) = @_;
4254 return 0 unless defined $orig_texdir;
4255
4256 # convert to absolute, for safer parsing.
4257 # also replaces backslashes with slashes on w32.
4258 # The return value may still contain symlinks,
4259 # but no unnecessary terminating '/'.
4260 my $texdir = tl_abs_path($orig_texdir);
4261 return 0 unless defined $texdir;
4262
4263 # reject the root of a drive,
4264 # assuming that only the canonical form of the root ends with /
4265 return 0 if $texdir =~ m!/$!;
4266
4267 # Unfortunately we have lots of special characters.
4268 # On Windows, backslashes are normal but will already have been changed
4269 # to slashes by tl_abs_path. And we should only check for : on Unix.
4270 my $colon = wndws() ? "" : ":";
4271 if ($texdir =~ /[,$colon;\\{}\$]/) {
4272 if ($warn) {
4273 print " !! TEXDIR value has problematic characters: $orig_texdir\n";
4274 print " !! (such as comma, colon, semicolon, backslash, braces\n";
4275 print " !! and dollar sign; sorry)\n";
4276 }
4277 # although we could check each character individually and give a
4278 # specific error, it seems plausibly useful to report all the chars
4279 # that cause problems, regardless of which was there. Simpler too.
4280 return 0;
4281 }
4282 # w32: for now, reject the root of a samba share
4283 return 0 if wndws() && $texdir =~ m!^//[^/]+/[^/]+$!;
4284
4285 # if texdir already exists, make sure we can write into it.
4286 return dir_writable($texdir) if (-d $texdir);
4287
4288 # if texdir doesn't exist, make sure we can write the parent.
4289 (my $texdirparent = $texdir) =~ s!/[^/]*$!!;
4290 #print STDERR "Checking $texdirparent".'[/]'."\n";
4291 return dir_creatable($texdirparent) if -d dir_slash($texdirparent);
4292
4293 # ditto for the next level up the tree
4294 (my $texdirpparent = $texdirparent) =~ s!/[^/]*$!!;
4295 #print STDERR "Checking $texdirpparent".'[/]'."\n";
4296 return dir_creatable($texdirpparent) if -d dir_slash($texdirpparent);
4297
4298 # doesn't look plausible.
4299 return 0;
4300 }
4301
4302 =pod
4303
4304 This function takes a single argument I<path> and returns it with
4305 C<"> chars surrounding it on Unix. On Windows, the C<"> chars are only
4306 added if I<path> contains special characters, since unconditional quoting
4307 leads to errors there. In all cases, any C<"> chars in I<path> itself
4308 are (erroneously) eradicated.
4309
4310 =cut
4311
4312 sub quotify_path_with_spaces {
4313 my $p = shift;
4314 my $m = wndws() ? '[+=^&();,!%\s]' : '.';
4315 if ( $p =~ m/$m/ ) {
4316 $p =~ s/"//g; # remove any existing double quotes
4317 $p = "\"$p\"";
4318 }
4319 return($p);
4320 }
4321
4322 =pod
4323
4324 This function returns a "Windows-ized" version of its single argument
4325 I<path>, i.e., replaces all forward slashes with backslashes, and adds
4326 an additional C<"> at the beginning and end if I<path> contains any
4327 spaces. It also makes the path absolute. So if $path does not start
4328 with one (arbitrary) characer followed by C<:>, we add the output of
4329 C<`cd`>.
4330
4331 The result is suitable for running in shell commands, but not file tests
4332 or other manipulations, since in such internal Perl contexts, the quotes
4333 would be considered part of the filename.
4334
4335 =cut
4336
4337 sub conv_to_w32_path {
4338 my $p = shift;
4339 # we need absolute paths, too
4340 my $pabs = tl_abs_path($p);
4341 if (not $pabs) {
4342 $pabs = $p;
4343 tlwarn ("sorry, could not determine absolute path of $p!\n".
4344 "using original path instead");
4345 }
4346 $pabs =~ s!/!\\!g;
4347 $pabs = quotify_path_with_spaces($pabs);
4348 return($pabs);
4349 }
4350
4351 =pod
4352
4353 The next two functions are meant for user input/output in installer menus.
4354 They help making the windows user happy by turning slashes into backslashes
4355 before displaying a path, and our code happy by turning backslashes into forwars
4356 slashes after reading a path. They both are no-ops on Unix.
4357
4358 =cut
4359
4360 sub native_slashify {
4361 my ($r) = @_;
4362 $r =~ s!/!\\!g if wndws();
4363 return $r;
4364 }
4365
4366 sub forward_slashify {
4367 my ($r) = @_;
4368 $r =~ s!\\!/!g if wndws();
4369 return $r;
4370 }
4371
4372 =item C<setup_persistent_downloads()>
4373
4374 Set up to use persistent connections using LWP/TLDownload, that is look
4375 for a download server. Return the TLDownload object if successful, else
4376 false.
4377
4378 =cut
4379
4380 sub setup_persistent_downloads {
4381 my $certs = shift;
4382 if ($TeXLive::TLDownload::net_lib_avail) {
4383 ddebug("setup_persistent_downloads has net_lib_avail set\n");
4384 if ($::tldownload_server) {
4385 if ($::tldownload_server->initcount() > $TeXLive::TLConfig::MaxLWPReinitCount) {
4386 debug("stop retrying to initialize LWP after 10 failures\n");
4387 return 0;
4388 } else {
4389 $::tldownload_server->reinit(certificates => $certs);
4390 }
4391 } else {
4392 $::tldownload_server = TeXLive::TLDownload->new(certificates => $certs);
4393 }
4394 if (!defined($::tldownload_server)) {
4395 ddebug("TLUtils:setup_persistent_downloads: failed to get ::tldownload_server\n");
4396 } else {
4397 ddebug("TLUtils:setup_persistent_downloads: got ::tldownload_server\n");
4398 }
4399 return $::tldownload_server;
4400 }
4401 return 0;
4402 }
4403
4404
4405 =item C<query_ctan_mirror()>
4406
4407 Return a particular mirror given by the generic CTAN auto-redirecting
4408 default (specified in L<$TLConfig::TexLiveServerURL>) if we get a
4409 response, else the empty string.
4410
4411 Use C<curl> if it is listed as a C<working_downloader>, else C<wget>,
4412 else give up. We can't support arbitrary downloaders here, as we do for
4413 regular package downloads, since certain options have to be set and the
4414 output has to be parsed.
4415
4416 We try invoking the program three times (hardwired).
4417
4418 =cut
4419
4420 sub query_ctan_mirror {
4421 my @working_downloaders = @{$::progs{'working_downloaders'}};
4422 ddebug("query_ctan_mirror: working_downloaders: @working_downloaders\n");
4423 if (TeXLive::TLUtils::member("curl", @working_downloaders)) {
4424 return query_ctan_mirror_curl();
4425 } elsif (TeXLive::TLUtils::member("wget", @working_downloaders)) {
4426 if ($::progs{'options'}{'wget-ssl'}) {
4427 # we need ssl enabled wget to query ctan
4428 return query_ctan_mirror_wget();
4429 } else {
4430 tlwarn(<<END_NO_SSL);
4431 TLUtils::query_ctan_mirror: neither curl nor an ssl-enabled wget is
4432 available, so no CTAN mirror can be resolved via https://mirror.ctan.org.
4433
4434 Please install curl or ssl-enabled wget; otherwise, please pick an
4435 http (not https) mirror from the list at https://ctan.org/mirrors/mirmon.
4436
4437 To report a bug about this, please rerun your command with -vv and
4438 include the resulting output with the report.
4439 END_NO_SSL
4440 return;
4441 }
4442 } else {
4443 return;
4444 }
4445 }
4446
4447 # curl will follow the redirect chain for us.
4448 #
4449 sub query_ctan_mirror_curl {
4450 my $max_trial = 3;
4451 my $warg = (wndws() ? '-w "%{url_effective}" ' : "-w '%{url_effective}' ");
4452 for (my $i = 1; $i <= $max_trial; $i++) {
4453 # -L -> follow redirects
4454 # -s -> silent
4455 # -w -> what to output after completion
4456 my $cmd = "$::progs{'curl'} -Ls "
4457 . "-o " . nulldev() . " "
4458 . $warg
4459 . "--connect-timeout $NetworkTimeout "
4460 . "--max-time $NetworkTimeout "
4461 . $TeXLiveServerURL;
4462 ddebug("query_ctan_mirror_curl: cmd: $cmd\n");
4463 my $url = `$cmd`;
4464 if (length $url) {
4465 # remove trailing slashes
4466 $url =~ s,/*$,,;
4467 ddebug("query_ctan_mirror_curl: returning url: $url\n");
4468 return $url;
4469 }
4470 sleep(1);
4471 }
4472 return;
4473 }
4474
4475 sub query_ctan_mirror_wget {
4476 my $wget = $::progs{'wget'};
4477 if (!defined ($wget)) {
4478 tlwarn("query_ctan_mirror_wget: Programs not set up, trying wget\n");
4479 $wget = "wget";
4480 }
4481
4482 # we need the verbose output, so no -q.
4483 # do not reduce retries here, but timeout still seems desirable.
4484 my $mirror = $TeXLiveServerURL;
4485 my $cmd = "$wget $mirror --timeout=$NetworkTimeout "
4486 . "-O " . nulldev() . " 2>&1";
4487 ddebug("query_ctan_mirror_wget: cmd is $cmd\n");
4488
4489 # since we are reading the output of wget to find a mirror
4490 # we have to make sure that the locale is unset
4491 my $saved_lcall;
4492 if (defined($ENV{'LC_ALL'})) {
4493 $saved_lcall = $ENV{'LC_ALL'};
4494 }
4495 $ENV{'LC_ALL'} = "C";
4496 # we try 3 times to get a mirror from mirror.ctan.org in case we have
4497 # bad luck with what gets returned.
4498 my $max_trial = 3;
4499 my $mhost;
4500 for (my $i = 1; $i <= $max_trial; $i++) {
4501 my @out = `$cmd`;
4502 # analyze the output for the mirror actually selected.
4503 foreach (@out) {
4504 if (m/^Location: (\S*)\s*.*$/) {
4505 (my $mhost = $1) =~ s,/*$,,; # remove trailing slashes since we add it
4506 ddebug("query_ctan_mirror_wget: returning url: $mhost\n");
4507 return $mhost;
4508 }
4509 }
4510 sleep(1);
4511 }
4512
4513 # reset LC_ALL to undefined or the previous value
4514 if (defined($saved_lcall)) {
4515 $ENV{'LC_ALL'} = $saved_lcall;
4516 } else {
4517 delete($ENV{'LC_ALL'});
4518 }
4519
4520 # we are still here, so three times we didn't get a mirror, give up
4521 # and return undefined
4522 return;
4523 }
4524
4525 =item C<check_on_working_mirror($mirror)>
4526
4527 Check if MIRROR is functional.
4528
4529 =cut
4530
4531 sub check_on_working_mirror {
4532 my $mirror = shift;
4533
4534 my $wget = $::progs{'wget'};
4535 if (!defined ($wget)) {
4536 tlwarn ("check_on_working_mirror: Programs not set up, trying wget\n");
4537 $wget = "wget";
4538 }
4539 $wget = quotify_path_with_spaces($wget);
4540 #
4541 # the test is currently not completely correct, because we do not
4542 # use the LWP if it is set up for it, but I am currently too lazy
4543 # to program it,
4544 # so try wget and only check for the return value
4545 # please KEEP the / after $mirror, some ftp mirrors do give back
4546 # an error if the / is missing after ../CTAN/
4547 my $cmd = "$wget $mirror/ --timeout=$NetworkTimeout -O -"
4548 . " >" . (TeXLive::TLUtils::nulldev())
4549 . " 2>" . (TeXLive::TLUtils::nulldev());
4550 my $ret = system($cmd);
4551 # if return value is not zero it is a failure, so switch the meanings
4552 return ($ret ? 0 : 1);
4553 }
4554
4555 =item C<give_ctan_mirror_base()>
4556
4557 1. get a mirror (retries 3 times to contact mirror.ctan.org)
4558 - if no mirror found, use one of the backbone servers
4559 - if it is an http server return it (no test is done)
4560 - if it is a ftp server, continue
4561 2. if the ftp mirror is good, return it
4562 3. if the ftp mirror is bad, search for http mirror (5 times)
4563 4. if http mirror is found, return it (again, no test,)
4564 5. if no http mirror is found, return one of the backbone servers
4565
4566 =cut
4567
4568 sub give_ctan_mirror_base {
4569 # only one backbone has existed for a while (2018).
4570 my @backbone = qw!https://www.ctan.org/tex-archive!;
4571
4572 # start by selecting a mirror and test its operationality
4573 ddebug("give_ctan_mirror_base: calling query_ctan_mirror\n");
4574 my $mirror = query_ctan_mirror();
4575 if (!defined($mirror)) {
4576 # three times calling mirror.ctan.org did not give anything useful,
4577 # return one of the backbone servers
4578 tlwarn("cannot contact mirror.ctan.org, returning a backbone server!\n");
4579 return $backbone[int(rand($#backbone + 1))];
4580 }
4581
4582 if ($mirror =~ m!^https?://!) { # if http mirror, assume good and return.
4583 return $mirror;
4584 }
4585
4586 # we are still here, so we got a ftp mirror from mirror.ctan.org
4587 if (check_on_working_mirror($mirror)) {
4588 return $mirror; # ftp mirror is working, return.
4589 }
4590
4591 # we are still here, so the ftp mirror failed, retry and hope for http.
4592 # theory is that if one ftp fails, probably all ftp is broken.
4593 my $max_mirror_trial = 5;
4594 for (my $try = 1; $try <= $max_mirror_trial; $try++) {
4595 my $m = query_ctan_mirror();
4596 debug("querying mirror, got " . (defined($m) ? $m : "(nothing)") . "\n");
4597 if (defined($m) && $m =~ m!^https?://!) {
4598 return $m; # got http this time, assume ok.
4599 }
4600 # sleep to make mirror happy, but only if we are not ready to return
4601 sleep(1) if $try < $max_mirror_trial;
4602 }
4603
4604 # 5 times contacting the mirror service did not return a http server,
4605 # use one of the backbone servers.
4606 debug("no mirror found ... randomly selecting backbone\n");
4607 return $backbone[int(rand($#backbone + 1))];
4608 }
4609
4610
4611 sub give_ctan_mirror {
4612 return (give_ctan_mirror_base(@_) . "/$TeXLiveServerPath");
4613 }
4614
4615 =item C<create_mirror_list()>
4616
4617 =item C<extract_mirror_entry($listentry)>
4618
4619 C<create_mirror_list> returns the lists of viable mirrors according to
4620 ctan-mirrors.pl, in a list which also contains continents, and country headers.
4621
4622 C<extract_mirror_entry> extracts the actual repository data from one
4623 of these entries.
4624
4625 # KEEP THESE TWO FUNCTIONS IN SYNC!!!
4626
4627 =cut
4628
4629 sub create_mirror_list {
4630 our $mirrors;
4631 my @ret = ();
4632 require("installer/ctan-mirrors.pl");
4633 my @continents = sort keys %$mirrors;
4634 for my $continent (@continents) {
4635 # first push the name of the continent
4636 push @ret, uc($continent);
4637 my @countries = sort keys %{$mirrors->{$continent}};
4638 for my $country (@countries) {
4639 my @mirrors = sort keys %{$mirrors->{$continent}{$country}};
4640 my $first = 1;
4641 for my $mirror (@mirrors) {
4642 my $mfull = $mirror;
4643 $mfull =~ s!/$!!;
4644 # do not append the server path part here, but add
4645 # it down there in the extract mirror entry
4646 #$mfull .= "/" . $TeXLive::TLConfig::TeXLiveServerPath;
4647 #if ($first) {
4648 my $country_str = sprintf "%-12s", $country;
4649 push @ret, " $country_str $mfull";
4650 # $first = 0;
4651 #} else {
4652 # push @ret, " $mfull";
4653 #}
4654 }
4655 }
4656 }
4657 return @ret;
4658 }
4659
4660 # extract_mirror_entry is not very intelligent, it assumes that
4661 # the last "word" is the URL
4662 sub extract_mirror_entry {
4663 my $ent = shift;
4664 my @foo = split ' ', $ent;
4665 return $foo[$#foo] . "/" . $TeXLive::TLConfig::TeXLiveServerPath;
4666 }
4667
4668 =pod
4669
4670 =item C<< slurp_file($file) >>
4671
4672 Reads the whole file and returns the content in a scalar.
4673
4674 =cut
4675
4676 sub slurp_file {
4677 my $file = shift;
4678 my $file_data = do {
4679 local $/ = undef;
4680 open my $fh, "<", $file || die "open($file) failed: $!";
4681 <$fh>;
4682 };
4683 return($file_data);
4684 }
4685
4686 =pod
4687
4688 =item C<< download_to_temp_or_file($url) >>
4689
4690 If C<$url> is a url, tries to download the file into a temporary file.
4691 Otherwise assume that C<$url> is a local file.
4692 In both cases returns the local file.
4693
4694 Returns the local file name if succeeded, otherwise undef.
4695
4696 =cut
4697
4698 sub download_to_temp_or_file {
4699 my $url = shift;
4700 my $ret;
4701 my ($url_fh, $url_file);
4702 if ($url =~ m,^(https?|ftp|file)://, || $url =~ m!$SshURIRegex!) {
4703 ($url_fh, $url_file) = tl_tmpfile();
4704 # now $url_fh filehandle is open, the file created
4705 # TLUtils::download_file will just overwrite what is there
4706 # on windows that doesn't work, so we close the fh immediately
4707 # this creates a short loophole, but much better than before anyway
4708 close($url_fh);
4709 $ret = download_file($url, $url_file);
4710 } else {
4711 $url_file = $url;
4712 $ret = 1;
4713 }
4714 if ($ret && (-r "$url_file")) {
4715 return $url_file;
4716 }
4717 return;
4718 }
4719
4720
4721 =item C<< compare_tlpobjs($tlpA, $tlpB) >>
4722
4723 Compare the two passed L<TLPOBJ> objects. Returns a hash:
4724
4725 $ret{'revision'} = "revA:revB" # if revisions differ
4726 $ret{'removed'} = \[ list of files removed from A to B ]
4727 $ret{'added'} = \[ list of files added from A to B ]
4728 $ret{'fmttriggers'} = 1 if the fmttriggers have changed
4729
4730 =cut
4731
4732 sub compare_tlpobjs {
4733 my ($tlpA, $tlpB) = @_;
4734 my %ret;
4735
4736 my $rA = $tlpA->revision;
4737 my $rB = $tlpB->revision;
4738 if ($rA != $rB) {
4739 $ret{'revision'} = "$rA:$rB";
4740 }
4741 if ($tlpA->relocated) {
4742 $tlpA->replace_reloc_prefix;
4743 }
4744 if ($tlpB->relocated) {
4745 $tlpB->replace_reloc_prefix;
4746 }
4747 my @fA = $tlpA->all_files;
4748 my @fB = $tlpB->all_files;
4749 my %removed;
4750 my %added;
4751 for my $f (@fA) { $removed{$f} = 1; }
4752 for my $f (@fB) { delete($removed{$f}); $added{$f} = 1; }
4753 for my $f (@fA) { delete($added{$f}); }
4754 my @rem = sort keys %removed;
4755 my @add = sort keys %added;
4756 $ret{'removed'} = \@rem if @rem;
4757 $ret{'added'} = \@add if @add;
4758
4759 # changed dependencies should not trigger a change without a
4760 # change in revision, so for now (until we find a reason why
4761 # we need to) we don't check.
4762 # OTOH, execute statements like
4763 # execute AddFormat name=aleph engine=aleph options=*aleph.ini fmttriggers=cm,hyphen-base,knuth-lib,plain
4764 # might change due to changes in the fmttriggers variables.
4765 # Again, name/engine/options are only defined in the package's
4766 # tlpsrc file, so changes here will trigger revision changes,
4767 # but fmttriggers are defined outside the tlpsrc and thus do
4768 # not trigger an automatic revision change. Check for that!
4769 # No need to record actual changes, just record that it has changed.
4770 my %triggersA;
4771 my %triggersB;
4772 # we sort executes after format/engine like fmtutil does, since this
4773 # should be unique
4774 for my $e ($tlpA->executes) {
4775 if ($e =~ m/AddFormat\s+(.*)\s*/) {
4776 my %r = parse_AddFormat_line("$1");
4777 if (defined($r{"error"})) {
4778 die "$r{'error'} when comparing packages $tlpA->name execute $e";
4779 }
4780 for my $t (@{$r{'fmttriggers'}}) {
4781 $triggersA{"$r{'name'}:$r{'engine'}:$t"} = 1;
4782 }
4783 }
4784 }
4785 for my $e ($tlpB->executes) {
4786 if ($e =~ m/AddFormat\s+(.*)\s*/) {
4787 my %r = parse_AddFormat_line("$1");
4788 if (defined($r{"error"})) {
4789 die "$r{'error'} when comparing packages $tlpB->name execute $e";
4790 }
4791 for my $t (@{$r{'fmttriggers'}}) {
4792 $triggersB{"$r{'name'}:$r{'engine'}:$t"} = 1;
4793 }
4794 }
4795 }
4796 for my $t (keys %triggersA) {
4797 delete($triggersA{$t});
4798 delete($triggersB{$t});
4799 }
4800 if (keys(%triggersA) || keys(%triggersB)) {
4801 $ret{'fmttrigger'} = 1;
4802 }
4803
4804 return %ret;
4805 }
4806
4807
4808 =item C<< compare_tlpdbs($tlpdbA, $tlpdbB, @more_ignored_pkgs) >>
4809
4810 Compare the two passed L<TLPDB> objects, ignoring the packages
4811 C<00texlive.installer>, C<00texlive.image>, and any passed
4812 C<@more_ignore_pkgs>. Returns a hash:
4813
4814 $ret{'removed_packages'} = \[ list of removed packages from A to B ]
4815 $ret{'added_packages'} = \[ list of added packages from A to B ]
4816 $ret{'different_packages'}->{$package} = output of compare_tlpobjs
4817
4818 =cut
4819
4820 sub compare_tlpdbs {
4821 my ($tlpdbA, $tlpdbB, @add_ignored_packs) = @_;
4822 my @ignored_packs = qw/00texlive.installer 00texlive.image/;
4823 push @ignored_packs, @add_ignored_packs;
4824
4825 my @inAnotinB;
4826 my @inBnotinA;
4827 my %diffpacks;
4828 my %do_compare;
4829 my %ret;
4830
4831 for my $p ($tlpdbA->list_packages()) {
4832 my $is_ignored = 0;
4833 for my $ign (@ignored_packs) {
4834 if (($p =~ m/^$ign$/) || ($p =~ m/^$ign\./)) {
4835 $is_ignored = 1;
4836 last;
4837 }
4838 }
4839 next if $is_ignored;
4840 my $tlpB = $tlpdbB->get_package($p);
4841 if (!defined($tlpB)) {
4842 push @inAnotinB, $p;
4843 } else {
4844 $do_compare{$p} = 1;
4845 }
4846 }
4847 $ret{'removed_packages'} = \@inAnotinB if @inAnotinB;
4848
4849 for my $p ($tlpdbB->list_packages()) {
4850 my $is_ignored = 0;
4851 for my $ign (@ignored_packs) {
4852 if (($p =~ m/^$ign$/) || ($p =~ m/^$ign\./)) {
4853 $is_ignored = 1;
4854 last;
4855 }
4856 }
4857 next if $is_ignored;
4858 my $tlpA = $tlpdbA->get_package($p);
4859 if (!defined($tlpA)) {
4860 push @inBnotinA, $p;
4861 } else {
4862 $do_compare{$p} = 1;
4863 }
4864 }
4865 $ret{'added_packages'} = \@inBnotinA if @inBnotinA;
4866
4867 for my $p (sort keys %do_compare) {
4868 my $tlpA = $tlpdbA->get_package($p);
4869 my $tlpB = $tlpdbB->get_package($p);
4870 my %foo = compare_tlpobjs($tlpA, $tlpB);
4871 if (keys %foo) {
4872 # some diffs were found
4873 $diffpacks{$p} = \%foo;
4874 }
4875 }
4876 $ret{'different_packages'} = \%diffpacks if (keys %diffpacks);
4877
4878 return %ret;
4879 }
4880
4881 sub tlnet_disabled_packages {
4882 my ($root) = @_;
4883 my $disabled_pkgs = "$root/tlpkg/dev/tlnet-disabled-packages.txt";
4884 my @ret;
4885 if (-r $disabled_pkgs) {
4886 open (DISABLED, "<$disabled_pkgs") || die "Huu, -r but cannot open: $?";
4887 while (<DISABLED>) {
4888 chomp;
4889 next if /^\s*#/;
4890 next if /^\s*$/;
4891 $_ =~ s/^\s*//;
4892 $_ =~ s/\s*$//;
4893 push @ret, $_;
4894 }
4895 close(DISABLED) || warn ("Cannot close tlnet-disabled-packages.txt: $?");
4896 }
4897 return @ret;
4898 }
4899
4900 =item C<< report_tlpdb_differences($rret) >>
4901
4902 Report, using info function, as given in hash reference argument RET,
4903 with keys removed_packages, added_packages, different_packages.
4904
4905 =cut
4906
4907 sub report_tlpdb_differences {
4908 my $rret = shift;
4909 my %ret = %$rret;
4910
4911 if (defined($ret{'removed_packages'})) {
4912 info ("removed packages from A to B:\n");
4913 for my $f (sort @{$ret{'removed_packages'}}) {
4914 info (" $f\n");
4915 }
4916 }
4917 if (defined($ret{'added_packages'})) {
4918 info ("added packages from A to B:\n");
4919 for my $f (sort @{$ret{'added_packages'}}) {
4920 info (" $f\n");
4921 }
4922 }
4923 if (defined($ret{'different_packages'})) {
4924 info ("different packages from A to B:\n");
4925 my $printed_fmttriggers_msg = 0;
4926 for my $p (sort keys %{$ret{'different_packages'}}) {
4927 info (" $p:\n");
4928 for my $k (sort keys %{$ret{'different_packages'}->{$p}}) {
4929 if ($k eq "revision") {
4930 info(" revision differ: $ret{'different_packages'}->{$p}->{$k}\n");
4931 } elsif ($k eq "removed" || $k eq "added") {
4932 info (" $k files:\n");
4933 for my $f (sort @{$ret{'different_packages'}->{$p}->{$k}}) {
4934 info (" $f\n");
4935 }
4936 } elsif ($k eq "fmttriggers") {
4937 # fmttriggers; don't bother making a complete report.
4938 # The fmttriggers will differ when the global variables in
4939 # 00texlive.autopatterns.tlpsrc change but we forgot to
4940 # tlforceincr all the packages that depend on the variables.
4941 # Which happens depressingly often.
4942 info(" $k differ)\n");
4943 info("(if 00texlive.autopatterns change, tlforceincr dependents.)\n")
4944 if ! $printed_fmttriggers_msg; # just show once
4945 $printed_fmttriggers_msg = 1;
4946 } else {
4947 info(" $k differ\n");
4948 }
4949 }
4950 }
4951 }
4952 }
4953
4954 sub sort_archs ($$) {
4955 my $aa = $_[0];
4956 my $bb = $_[1];
4957 $aa =~ s/^(.*)-(.*)$/$2-$1/;
4958 $bb =~ s/^(.*)-(.*)$/$2-$1/;
4959 $aa cmp $bb ;
4960 }
4961
4962 # Taken from Text::ParseWords
4963 #
4964 sub quotewords {
4965 my($delim, $keep, @lines) = @_;
4966 my($line, @words, @allwords);
4967
4968 foreach $line (@lines) {
4969 @words = parse_line($delim, $keep, $line);
4970 return() unless (@words || !length($line));
4971 push(@allwords, @words);
4972 }
4973 return(@allwords);
4974 }
4975
4976 sub parse_line {
4977 my($delimiter, $keep, $line) = @_;
4978 my($word, @pieces);
4979
4980 no warnings 'uninitialized'; # we will be testing undef strings
4981
4982 $line =~ s/\s+$//; # kill trailing whitespace
4983 while (length($line)) {
4984 $line =~ s/^(["']) # a $quote
4985 ((?:\\.|(?!\1)[^\\])*) # and $quoted text
4986 \1 # followed by the same quote
4987 | # --OR--
4988 ^((?:\\.|[^\\"'])*?) # an $unquoted text
4989 (\Z(?!\n)|(?-x:$delimiter)|(?!^)(?=["']))
4990 # plus EOL, delimiter, or quote
4991 //xs or return; # extended layout
4992 my($quote, $quoted, $unquoted, $delim) = ($1, $2, $3, $4);
4993 return() unless( defined($quote) || length($unquoted) || length($delim));
4994
4995 if ($keep) {
4996 $quoted = "$quote$quoted$quote";
4997 } else {
4998 $unquoted =~ s/\\(.)/$1/sg;
4999 if (defined $quote) {
5000 $quoted =~ s/\\(.)/$1/sg if ($quote eq '"');
5001 $quoted =~ s/\\([\\'])/$1/g if ( $PERL_SINGLE_QUOTE && $quote eq "'");
5002 }
5003 }
5004 $word .= substr($line, 0, 0); # leave results tainted
5005 $word .= defined $quote ? $quoted : $unquoted;
5006
5007 if (length($delim)) {
5008 push(@pieces, $word);
5009 push(@pieces, $delim) if ($keep eq 'delimiters');
5010 undef $word;
5011 }
5012 if (!length($line)) {
5013 push(@pieces, $word);
5014 }
5015 }
5016 return(@pieces);
5017 }
5018
5019
5020 =item C<mktexupd ()>
5021
5022 Append entries to C<ls-R> files. Usage example:
5023
5024 my $updLSR=&mktexupd();
5025 $updLSR->{mustexist}(1);
5026 $updLSR->{add}(file1);
5027 $updLSR->{add}(file2);
5028 $updLSR->{add}(file3);
5029 $updLSR->{exec}();
5030
5031 The first line creates a new object. Only one such object should be
5032 created in a program in order to avoid duplicate entries in C<ls-R> files.
5033
5034 C<add> pushes a filename or a list of filenames to a hash encapsulated
5035 in a closure. Filenames must be specified with the full (absolute) path.
5036 Duplicate entries are ignored.
5037
5038 C<exec> checks for each component of C<$TEXMFDBS> whether there are files
5039 in the hash which have to be appended to the corresponding C<ls-R> files
5040 and eventually updates the corresponding C<ls-R> files. Files which are
5041 in directories not stated in C<$TEXMFDBS> are silently ignored.
5042
5043 If the flag C<mustexist> is set, C<exec> aborts with an error message
5044 if a file supposed to be appended to an C<ls-R> file doesn't exist physically
5045 on the file system. This option was added for compatibility with the
5046 C<mktexupd> shell script. This option shouldn't be enabled in scripts,
5047 except for testing, because it degrades performance on non-cached file
5048 systems.
5049
5050 =cut
5051
5052 sub mktexupd {
5053 my %files;
5054 my $mustexist=0;
5055
5056 my $hash={
5057 "add" => sub {
5058 foreach my $file (@_) {
5059 $file =~ s|\\|/|g;
5060 $files{$file}=1;
5061 }
5062 },
5063 "reset" => sub {
5064 %files=();
5065 },
5066 "mustexist" => sub {
5067 $mustexist=shift;
5068 },
5069 "exec" => sub {
5070 # check whether files exist
5071 if ($mustexist) {
5072 foreach my $file (keys %files) {
5073 die "mktexupd: exec file does not exist: $file" if (! -f $file);
5074 }
5075 }
5076 my $delim= (&wndws)? ';' : ':';
5077 my $TEXMFDBS;
5078 chomp($TEXMFDBS=`kpsewhich --show-path="ls-R"`);
5079
5080 my @texmfdbs=split ($delim, "$TEXMFDBS");
5081 my %dbs;
5082
5083 foreach my $path (keys %files) {
5084 foreach my $db (@texmfdbs) {
5085 $db=substr($db, -1) if ($db=~m|/$|); # strip leading /
5086 $db = lc($db) if wndws();
5087 my $up = (wndws() ? lc($path) : $path);
5088 if (substr($up, 0, length("$db/")) eq "$db/") {
5089 # we appended a / because otherwise "texmf" is recognized as a
5090 # substring of "texmf-dist".
5091 my $np = './' . substr($up, length("$db/"));
5092 my ($dir, $file);
5093 $_=$np;
5094 ($dir, $file) = m|(.*)/(.*)|;
5095 $dbs{$db}{$dir}{$file}=1;
5096 }
5097 }
5098 }
5099 foreach my $db (keys %dbs) {
5100 if (! -f "$db" || ! -w "$db/ls-R") {
5101 &mkdirhier ($db);
5102 }
5103 open LSR, ">>$db/ls-R";
5104 foreach my $dir (keys %{$dbs{$db}}) {
5105 print LSR "\n$dir:\n";
5106 foreach my $file (keys %{$dbs{$db}{$dir}}) {
5107 print LSR "$file\n";
5108 }
5109 }
5110 close LSR;
5111 }
5112 }
5113 };
5114 return $hash;
5115 }
5116
5117
5118 =item C<setup_sys_user_mode($prg, $optsref, $tmfc, $tmfsc, $tmfv, $tmfsv)>
5119
5120 Return two-element list C<($texmfconfig,$texmfvar)> specifying which
5121 directories to use, either user or sys. If C<$optsref->{'sys'}> is
5122 true, we are in sys mode; else if C<$optsref->{'user'}> is set, we are
5123 in user mode; else a fatal error.
5124
5125 If C<$prg> eq C<"mktexfmt">, and C<$TEXMFSYSVAR/web2c> is writable, use
5126 it instead of C<$TEXMFVAR>, even if we are in user mode. C<$TEXMFCONFIG>
5127 is not switched, however.
5128
5129 =cut
5130
5131 sub setup_sys_user_mode {
5132 my ($prg, $optsref, $TEXMFCONFIG, $TEXMFSYSCONFIG,
5133 $TEXMFVAR, $TEXMFSYSVAR) = @_;
5134
5135 if ($optsref->{'user'} && $optsref->{'sys'}) {
5136 print STDERR "$prg [ERROR]: only one of -sys or -user can be used.\n";
5137 exit(1);
5138 }
5139
5140 # check if we are in *hidden* sys mode, in which case we switch
5141 # to sys mode
5142 # Nowdays we use -sys switch instead of simply overriding TEXMFVAR
5143 # and TEXMFCONFIG
5144 # This is used to warn users when they run updmap in usermode the first time.
5145 # But it might happen that this script is called via another wrapper that
5146 # sets TEXMFCONFIG and TEXMFVAR, and does not pass on the -sys option.
5147 # for this case we check whether the SYS and non-SYS variants agree,
5148 # and if, then switch to sys mode (with a warning)
5149 if (($TEXMFSYSCONFIG eq $TEXMFCONFIG) && ($TEXMFSYSVAR eq $TEXMFVAR)) {
5150 if ($optsref->{'user'}) {
5151 print STDERR "$prg [ERROR]: -user mode but path setup is -sys type, bailing out.\n";
5152 exit(1);
5153 }
5154 if (!$optsref->{'sys'}) {
5155 print STDERR "$prg [WARNING]: hidden sys mode found, switching to sys mode.\n"
5156 if (!$optsref->{'quiet'});
5157 $optsref->{'sys'} = 1;
5158 }
5159 }
5160
5161 my ($texmfconfig, $texmfvar);
5162 if ($optsref->{'sys'}) {
5163 # we are running as updmap-sys, make sure that the right tree is used
5164 $texmfconfig = $TEXMFSYSCONFIG;
5165 $texmfvar = $TEXMFSYSVAR;
5166 &debug("TLUtils::setup_sys_user_mode: sys mode\n");
5167
5168 } elsif ($optsref->{'user'}) {
5169 $texmfconfig = $TEXMFCONFIG;
5170 $texmfvar = $TEXMFVAR;
5171 &debug("TLUtils::setup_sys_user_mode: user mode\n");
5172
5173 # mktexfmt is run (accidentally or on purpose) by a user with
5174 # missing formats; we want to put the resulting format dumps in
5175 # TEXMFSYSVAR if possible, so that future format updates will just
5176 # work. Until 2021, they were put in TEXMFVAR, causing problems.
5177 #
5178 # We only do this for mktexfmt, not fmtutil; if fmtutil is called
5179 # explicitly with fmtutil -user, ok, do what they said to do.
5180 #
5181 if ($prg eq "mktexfmt") {
5182 my $switchit = 0;
5183 if (-d "$TEXMFSYSVAR/web2c") {
5184 $switchit = 1 if (-w "$TEXMFSYSVAR/web2c");
5185 } elsif (-d $TEXMFSYSVAR && -w $TEXMFSYSVAR) {
5186 $switchit = 1;
5187 }
5188 if ($switchit) {
5189 $texmfvar = $TEXMFSYSVAR;
5190 &ddebug(" switched to $texmfvar for mktexfmt\n");
5191 }
5192 }
5193 } else {
5194 print STDERR
5195 "$prg [ERROR]: Either -sys or -user mode is required.\n" .
5196 "$prg [ERROR]: In nearly all cases you should use $prg -sys.\n" .
5197 "$prg [ERROR]: For special cases see https://tug.org/texlive/scripts-sys-user.html\n" ;
5198 exit(1);
5199 }
5200
5201 &debug(" returning: ($texmfconfig,$texmfvar)\n");
5202 return ($texmfconfig, $texmfvar);
5203 }
5204
5205
5206 =item C<prepend_own_path()>
5207
5208 Prepend the location of the TeX Live binaries to the PATH environment
5209 variable. This is used by (e.g.) C<fmtutil>. The location is found by
5210 calling C<Cwd::abs_path> on C<which('kpsewhich')>. We use kpsewhich
5211 because it is known to be a true binary executable; C<$0> could be a
5212 symlink into (say) C<texmf-dist/scripts/>, which is not a useful
5213 directory for PATH.
5214
5215 =cut
5216
5217 sub prepend_own_path {
5218 my $bindir = dirname(Cwd::abs_path(which('kpsewhich')));
5219 if (wndws()) {
5220 $bindir =~ s!\\!/!g;
5221 $ENV{'PATH'} = "$bindir;$ENV{PATH}";
5222 } else {
5223 $ENV{'PATH'} = "$bindir:$ENV{PATH}";
5224 }
5225 }
5226
5227
5228 =item C<repository_to_array($r)>
5229
5230 Return hash of tags to urls for space-separated list of repositories
5231 passed in C<$r>. If passed undef or empty string, die.
5232
5233 =cut
5234
5235 sub repository_to_array {
5236 my $r = shift;
5237 my %r;
5238 if (!$r) {
5239 # either empty string or undef was passed
5240 # before 20181023 we die here, now we return
5241 # an empty array
5242 return %r;
5243 }
5244 #die "internal error, repository_to_array passed nothing (caller="
5245 # . caller . ")" if (!$r);
5246 my @repos = split (' ', $r);
5247 if ($#repos == 0) {
5248 # only one repo, this is the main one!
5249 $r{'main'} = $repos[0];
5250 return %r;
5251 }
5252 for my $rr (@repos) {
5253 my $tag;
5254 my $url;
5255 # decode spaces and % in reverse order
5256 $rr =~ s/%20/ /g;
5257 $rr =~ s/%25/%/g;
5258 $tag = $url = $rr;
5259 if ($rr =~ m/^([^#]+)#(.*)$/) {
5260 $tag = $2;
5261 $url = $1;
5262 }
5263 $r{$tag} = $url;
5264 }
5265 return %r;
5266 }
5267
5268
5269 =back
5270
5271 =head2 JSON
5272
5273 =over 4
5274
5275 =item C<encode_json($ref)>
5276
5277 Returns the JSON representation of the object C<$ref> is pointing at.
5278 This tries to load the C<JSON> Perl module, and uses it if available,
5279 otherwise falls back to module internal conversion.
5280
5281 The used backend can be selected by setting the environment variable
5282 C<TL_JSONMODE> to either C<json> or C<texlive> (all other values are
5283 ignored). If C<json> is requested and the C<JSON> module cannot be loaded
5284 the program terminates.
5285
5286 =cut
5287
5288 my $TLTrueValue = 1;
5289 my $TLFalseValue = 0;
5290 my $TLTrue = \$TLTrueValue;
5291 my $TLFalse = \$TLFalseValue;
5292 bless $TLTrue, 'TLBOOLEAN';
5293 bless $TLFalse, 'TLBOOLEAN';
5294
5295 our $jsonmode = "";
5296
5297 =pod
5298
5299 =item C<True()>
5300
5301 =item C<False()>
5302
5303 These two crazy functions must be used to get proper JSON C<true> and
5304 C<false> in the output independent of the backend used.
5305
5306 =cut
5307
5308 sub True {
5309 ensure_json_available();
5310 if ($jsonmode eq "json") {
5311 return($JSON::true);
5312 } else {
5313 return($TLTrue);
5314 }
5315 }
5316 sub False {
5317 ensure_json_available();
5318 if ($jsonmode eq "json") {
5319 return($JSON::false);
5320 } else {
5321 return($TLFalse);
5322 }
5323 }
5324
5325 sub ensure_json_available {
5326 return if ($jsonmode);
5327 # check the environment for mode to use:
5328 # $ENV{'TL_JSONMODE'} = texlive | json
5329 my $envdefined = 0;
5330 if ($ENV{'TL_JSONMODE'}) {
5331 $envdefined = 1;
5332 if ($ENV{'TL_JSONMODE'} eq "texlive") {
5333 $jsonmode = "texlive";
5334 debug("texlive json module used!\n");
5335 return;
5336 } elsif ($ENV{'TL_JSONMODE'} eq "json") {
5337 # nothing to do
5338 } else {
5339 tlwarn("Unsupported mode \'$ENV{TL_JSONMODE}\' set in TL_JSONMODE, ignoring it!");
5340 $envdefined = 0;
5341 }
5342 }
5343 return if ($jsonmode); # was set to texlive
5344 eval { require JSON; };
5345 if ($@) {
5346 # that didn't work out, use home-grown json
5347 if ($envdefined) {
5348 # environment asks for JSON but cannot be loaded, die!
5349 tldie("envvar TL_JSONMODE request JSON module but cannot be loaded!\n");
5350 }
5351 $jsonmode = "texlive";
5352 debug("texlive json module used!\n");
5353 } else {
5354 $jsonmode = "json";
5355 my $json = JSON->new;
5356 debug("JSON " . $json->backend . " used!\n");
5357 }
5358 }
5359
5360 sub encode_json {
5361 my $val = shift;
5362 ensure_json_available();
5363 if ($jsonmode eq "json") {
5364 my $utf8_encoded_json_text = JSON::encode_json($val);
5365 return $utf8_encoded_json_text;
5366 } else {
5367 my $type = ref($val);
5368 if ($type eq "") {
5369 tldie("encode_json: accept only refs: $val");
5370 } elsif ($type eq 'SCALAR') {
5371 return(scalar_to_json($$val));
5372 } elsif ($type eq 'ARRAY') {
5373 return(array_to_json($val));
5374 } elsif ($type eq 'HASH') {
5375 return(hash_to_json($val));
5376 } elsif ($type eq 'REF') {
5377 return(encode_json($$val));
5378 } elsif (Scalar::Util::blessed($val)) {
5379 if ($type eq "TLBOOLEAN") {
5380 return($$val ? "true" : "false");
5381 } else {
5382 tldie("encode_json: unsupported blessed object");
5383 }
5384 } else {
5385 tldie("encode_json: unsupported format $type");
5386 }
5387 }
5388 }
5389
5390 sub scalar_to_json {
5391 sub looks_like_numeric {
5392 # code from JSON/backportPP.pm
5393 my $value = shift;
5394 no warnings 'numeric';
5395 # detect numbers
5396 # string & "" -> ""
5397 # number & "" -> 0 (with warning)
5398 # nan and inf can detect as numbers, so check with * 0
5399 return unless length((my $dummy = "") & $value);
5400 return unless 0 + $value eq $value;
5401 return 1 if $value * 0 == 0;
5402 return -1; # inf/nan
5403 }
5404 my $val = shift;
5405 if (defined($val)) {
5406 if (looks_like_numeric($val)) {
5407 return("$val");
5408 } else {
5409 return(string_to_json($val));
5410 }
5411 } else {
5412 return("null");
5413 }
5414 }
5415
5416 sub string_to_json {
5417 my $val = shift;
5418 my %esc = (
5419 "\n" => '\n',
5420 "\r" => '\r',
5421 "\t" => '\t',
5422 "\f" => '\f',
5423 "\b" => '\b',
5424 "\"" => '\"',
5425 "\\" => '\\\\',
5426 "\'" => '\\\'',
5427 );
5428 $val =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
5429 return("\"$val\"");
5430 }
5431
5432 sub hash_to_json {
5433 my $hr = shift;
5434 my @retvals;
5435 for my $k (keys(%$hr)) {
5436 my $val = $hr->{$k};
5437 push @retvals, "\"$k\":" . encode_json(\$val);
5438 }
5439 my $ret = "{" . join(",", @retvals) . "}";
5440 return($ret);
5441 }
5442
5443 sub array_to_json {
5444 my $hr = shift;
5445 my $ret = "[" . join(",", map { encode_json(\$_) } @$hr) . "]";
5446 return($ret);
5447 }
5448
5449 =pod
5450
5451 =back
5452
5453 =cut
5454
5455 1;
5456 __END__
5457
5458 =head1 SEE ALSO
5459
5460 The other modules in C<Master/tlpkg/TeXLive/> (L<TeXLive::TLConfig> and
5461 the rest), and the scripts in C<Master/tlpg/bin/> (especially
5462 C<tl-update-tlpdb>), the documentation in C<Master/tlpkg/doc/>, etc.
5463
5464 =head1 AUTHORS AND COPYRIGHT
5465
5466 This script and its documentation were written for the TeX Live
5467 distribution (L<https://tug.org/texlive>) and both are licensed under the
5468 GNU General Public License Version 2 or later.
5469
5470 =cut
5471
5472 ### Local Variables:
5473 ### perl-indent-level: 2
5474 ### tab-width: 2
5475 ### indent-tabs-mode: nil
5476 ### End:
5477 # vim:set tabstop=2 shiftwidth=2 expandtab: #