| 1 | package BATsh::MB; | ||
| 2 | ###################################################################### | ||
| 3 | # | ||
| 4 | # BATsh::MB - Multibyte (DBCS) script guard for BATsh | ||
| 5 | # | ||
| 6 | # https://metacpan.org/dist/BATsh | ||
| 7 | # | ||
| 8 | # Copyright (c) 2026 INABA Hitoshi <ina.cpan@gmail.com> | ||
| 9 | # | ||
| 10 | ###################################################################### | ||
| 11 | # | ||
| 12 | # THE PROBLEM (the classic "0x5C problem" of CP932 aka DAME-MOJI) | ||
| 13 | # | ||
| 14 | # In double-byte character sets such as CP932 (Shift_JIS as used on | ||
| 15 | # Japanese Windows), the SECOND byte of a two-byte character may fall | ||
| 16 | # in the ASCII range 0x40-0x7E. That range contains shell | ||
| 17 | # metacharacters: | ||
| 18 | # | ||
| 19 | # \ 0x5C escape character / path separator (SO, HYOU, NOH, ...) | ||
| 20 | # | 0x7C pipeline separator (PO, BO, ...) | ||
| 21 | # ` 0x60 command substitution (CHI, ...) | ||
| 22 | # ^ 0x5E cmd.exe escape character (DA, ...) | ||
| 23 | # { 0x7B } 0x7D [ 0x5B ] 0x5D ~ 0x7E @ 0x40 | ||
| 24 | # A-Z a-z (corrupted by uc/lc on variable names and values) | ||
| 25 | # | ||
| 26 | # A byte-oriented parser that scans for these characters will tear a | ||
| 27 | # two-byte character in half: "ECHO <SO>FUTO" loses a byte to caret | ||
| 28 | # unescaping, "echo <PO>INTO | cmd" splits the pipeline in the middle | ||
| 29 | # of a character, and so on. | ||
| 30 | # | ||
| 31 | # THE SOLUTION (guard transform) | ||
| 32 | # | ||
| 33 | # Rather than teaching every scanner in BATsh::CMD / BATsh::SH about | ||
| 34 | # lead and trail bytes, the script text is passed through a reversible | ||
| 35 | # GUARD TRANSFORM on input: | ||
| 36 | # | ||
| 37 | # LEAD TRAIL (TRAIL in the dangerous 0x40-0x7E range) | ||
| 38 | # is rewritten to | ||
| 39 | # \x01 LEAD (TRAIL+0x80) (three bytes, no ASCII metacharacters) | ||
| 40 | # | ||
| 41 | # a literal \x01 byte (never present in real scripts) is rewritten | ||
| 42 | # to \x01\x01 so that the transform is bijective. | ||
| 43 | # | ||
| 44 | # Two-byte characters whose trail byte is already >= 0x80 are left | ||
| 45 | # unchanged (they contain no ASCII bytes and are harmless). After the | ||
| 46 | # transform, NO byte of any multibyte character is an ASCII | ||
| 47 | # metacharacter, so every existing byte-oriented scanner in BATsh is | ||
| 48 | # automatically DBCS-safe. The inverse transform (decode) is applied | ||
| 49 | # at the output boundaries: print, external command execution, | ||
| 50 | # filesystem calls, and %ENV export. | ||
| 51 | # | ||
| 52 | # Because uc()/lc() never modify bytes >= 0x80 and the guard moves all | ||
| 53 | # ASCII trail bytes up into 0xC0-0xFE, case conversion of guarded text | ||
| 54 | # (variable-name uppercasing in BATsh::Env, ${VAR^^}, ...) is also | ||
| 55 | # safe as a side effect. | ||
| 56 | # | ||
| 57 | # SUPPORTED ENCODINGS | ||
| 58 | # | ||
| 59 | # cp932 (aliases: sjis, shiftjis, shift_jis, shift-jis, 932) | ||
| 60 | # gbk (aliases: cp936, 936) | ||
| 61 | # uhc (aliases: cp949, ksc5601, 949) | ||
| 62 | # big5 (aliases: cp950, 950) | ||
| 63 | # utf8 (aliases: utf-8) -- pass-through: UTF-8 trail bytes are | ||
| 64 | # all >= 0x80 and need no guarding | ||
| 65 | # none (aliases: ascii, us-ascii, binary) -- pass-through | ||
| 66 | # auto -- detect from the script source (see detect() below) | ||
| 67 | # | ||
| 68 | ###################################################################### | ||
| 69 | |||
| 70 | use 5.00503; | ||
| 71 | use strict; | ||
| 72 | BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } } | ||
| 73 | use warnings; local $^W = 1; | ||
| 74 | BEGIN { pop @INC if $INC[-1] eq '.' } | ||
| 75 | |||
| 76 | use vars qw($VERSION); | ||
| 77 | $VERSION = '0.10'; | ||
| 78 | $VERSION = $VERSION; | ||
| 79 | |||
| 80 | use vars qw($ENCODING $ACTIVE $ACTIVE_ENC $LEAD $TRAIL $DANGER); | ||
| 81 | |||
| 82 | # Requested encoding ('auto' until told otherwise) and the currently | ||
| 83 | # ACTIVE guard. Under 'auto' the guard is switched on when a DBCS | ||
| 84 | # source is detected and is then STICKY: a later pure-ASCII run_string | ||
| 85 | # does not switch it off, because Env may still hold guarded values | ||
| 86 | # from the earlier script. Only an explicit set_encoding() call | ||
| 87 | # deactivates the guard. | ||
| 88 | $ENCODING = 'auto'; | ||
| 89 | $ACTIVE = 0; | ||
| 90 | $ACTIVE_ENC = ''; | ||
| 91 | |||
| 92 | # Per-encoding byte classes (as character-class body strings). | ||
| 93 | # lead : first byte of a two-byte character | ||
| 94 | # trail : any valid second byte | ||
| 95 | # danger : second bytes that are also ASCII metacharacter candidates | ||
| 96 | my %ENC_TABLE = ( | ||
| 97 | 'cp932' => { | ||
| 98 | lead => "\x81-\x9f\xe0-\xfc", | ||
| 99 | trail => "\x40-\x7e\x80-\xfc", | ||
| 100 | danger => "\x40-\x7e", | ||
| 101 | }, | ||
| 102 | 'gbk' => { | ||
| 103 | lead => "\x81-\xfe", | ||
| 104 | trail => "\x40-\x7e\x80-\xfe", | ||
| 105 | danger => "\x40-\x7e", | ||
| 106 | }, | ||
| 107 | 'uhc' => { | ||
| 108 | lead => "\x81-\xfe", | ||
| 109 | trail => "\x41-\x5a\x61-\x7a\x81-\xfe", | ||
| 110 | danger => "\x41-\x5a\x61-\x7a", | ||
| 111 | }, | ||
| 112 | 'big5' => { | ||
| 113 | lead => "\x81-\xfe", | ||
| 114 | trail => "\x40-\x7e\xa1-\xfe", | ||
| 115 | danger => "\x40-\x7e", | ||
| 116 | }, | ||
| 117 | ); | ||
| 118 | |||
| 119 | my %ALIAS = ( | ||
| 120 | 'cp932' => 'cp932', | ||
| 121 | 'sjis' => 'cp932', | ||
| 122 | 'shiftjis' => 'cp932', | ||
| 123 | 'shift_jis' => 'cp932', | ||
| 124 | 'shift-jis' => 'cp932', | ||
| 125 | '932' => 'cp932', | ||
| 126 | 'gbk' => 'gbk', | ||
| 127 | 'cp936' => 'gbk', | ||
| 128 | '936' => 'gbk', | ||
| 129 | 'uhc' => 'uhc', | ||
| 130 | 'cp949' => 'uhc', | ||
| 131 | 'ksc5601' => 'uhc', | ||
| 132 | '949' => 'uhc', | ||
| 133 | 'big5' => 'big5', | ||
| 134 | 'cp950' => 'big5', | ||
| 135 | '950' => 'big5', | ||
| 136 | 'utf8' => 'utf8', | ||
| 137 | 'utf-8' => 'utf8', | ||
| 138 | 'none' => 'none', | ||
| 139 | 'ascii' => 'none', | ||
| 140 | 'us-ascii' => 'none', | ||
| 141 | 'binary' => 'none', | ||
| 142 | 'auto' => 'auto', | ||
| 143 | ); | ||
| 144 | |||
| 145 | # ---------------------------------------------------------------- | ||
| 146 | # set_encoding: select the requested encoding | ||
| 147 | # 'auto' detect per script (sticky activation) | ||
| 148 | # a DBCS name activate the guard now | ||
| 149 | # 'utf8'/'none' deactivate the guard now | ||
| 150 | # Returns the canonical name; dies on an unknown encoding. | ||
| 151 | # ---------------------------------------------------------------- | ||
| 152 | sub set_encoding { | ||
| 153 | my $enc = defined $_[0] && $_[0] !~ /\ABATsh::MB\z/ ? $_[0] : $_[1]; | ||
| 154 | $enc = 'auto' unless defined $enc && $enc ne ''; | ||
| 155 | my $canon = $ALIAS{lc $enc}; | ||
| 156 | unless (defined $canon) { | ||
| 157 | require Carp; | ||
| 158 | Carp::croak("BATsh::MB: unknown encoding '$enc' (supported: " . | ||
| 159 | "cp932 sjis gbk uhc big5 utf8 none auto)"); | ||
| 160 | } | ||
| 161 | $ENCODING = $canon; | ||
| 162 | if ($canon eq 'auto') { } # sticky | ||
| 163 | elsif (exists $ENC_TABLE{$canon}) { _activate($canon) } | ||
| 164 | else { _deactivate() } # utf8/none | ||
| 165 | return $canon; | ||
| 166 | } | ||
| 167 | |||
| 168 | sub encoding { return $ENCODING } | ||
| 169 | sub active { return $ACTIVE ? $ACTIVE_ENC : '' } | ||
| 170 | |||
| 171 | sub _activate { | ||
| 172 | my ($canon) = @_; | ||
| 173 | my $t = $ENC_TABLE{$canon}; | ||
| 174 | $LEAD = $t->{lead}; | ||
| 175 | $TRAIL = $t->{trail}; | ||
| 176 | $DANGER = $t->{danger}; | ||
| 177 | $ACTIVE = 1; | ||
| 178 | $ACTIVE_ENC = $canon; | ||
| 179 | } | ||
| 180 | |||
| 181 | sub _deactivate { | ||
| 182 | $ACTIVE = 0; | ||
| 183 | $ACTIVE_ENC = ''; | ||
| 184 | } | ||
| 185 | |||
| 186 | # ---------------------------------------------------------------- | ||
| 187 | # detect: guess the encoding of a chunk of script source (bytes) | ||
| 188 | # no bytes >= 0x80 -> 'none' | ||
| 189 | # well-formed UTF-8 -> 'utf8' | ||
| 190 | # otherwise -> 'cp932' | ||
| 191 | # The UTF-8 test is structural (RFC 3629 sequence forms), written | ||
| 192 | # byte-wise so it runs identically from Perl 5.005_03 onward. | ||
| 193 | # ---------------------------------------------------------------- | ||
| 194 | sub detect { | ||
| 195 | my $src = defined $_[0] && $_[0] !~ /\ABATsh::MB\z/ ? $_[0] : $_[1]; | ||
| 196 | return 'none' unless defined $src; | ||
| 197 | return 'none' unless $src =~ /[\x80-\xff]/; | ||
| 198 | return _valid_utf8($src) ? 'utf8' : 'cp932'; | ||
| 199 | } | ||
| 200 | |||
| 201 | sub _valid_utf8 { | ||
| 202 | my ($s) = @_; | ||
| 203 | my $i = 0; | ||
| 204 | my $n = length($s); | ||
| 205 | while ($i < $n) { | ||
| 206 | my $o = ord(substr($s, $i, 1)); | ||
| 207 | if ($o < 0x80) { $i++ } | ||
| 208 | elsif ($o >= 0xC2 && $o <= 0xDF) { | ||
| 209 | return 0 unless _cont($s, $i + 1, 1); $i += 2; | ||
| 210 | } | ||
| 211 | elsif ($o == 0xE0) { | ||
| 212 | return 0 unless _rng($s, $i+1, 0xA0, 0xBF) && _cont($s, $i+2, 1); | ||
| 213 | $i += 3; | ||
| 214 | } | ||
| 215 | elsif ($o >= 0xE1 && $o <= 0xEF) { | ||
| 216 | return 0 unless _cont($s, $i + 1, 2); $i += 3; | ||
| 217 | } | ||
| 218 | elsif ($o == 0xF0) { | ||
| 219 | return 0 unless _rng($s, $i+1, 0x90, 0xBF) && _cont($s, $i+2, 2); | ||
| 220 | $i += 4; | ||
| 221 | } | ||
| 222 | elsif ($o >= 0xF1 && $o <= 0xF4) { | ||
| 223 | return 0 unless _cont($s, $i + 1, 3); $i += 4; | ||
| 224 | } | ||
| 225 | else { return 0 } | ||
| 226 | } | ||
| 227 | return 1; | ||
| 228 | } | ||
| 229 | |||
| 230 | sub _cont { | ||
| 231 | my ($s, $i, $count) = @_; | ||
| 232 | for my $k (0 .. $count - 1) { | ||
| 233 | return 0 if $i + $k >= length($s); | ||
| 234 | my $o = ord(substr($s, $i + $k, 1)); | ||
| 235 | return 0 unless $o >= 0x80 && $o <= 0xBF; | ||
| 236 | } | ||
| 237 | return 1; | ||
| 238 | } | ||
| 239 | |||
| 240 | sub _rng { | ||
| 241 | my ($s, $i, $lo, $hi) = @_; | ||
| 242 | return 0 if $i >= length($s); | ||
| 243 | my $o = ord(substr($s, $i, 1)); | ||
| 244 | return ($o >= $lo && $o <= $hi) ? 1 : 0; | ||
| 245 | } | ||
| 246 | |||
| 247 | # ---------------------------------------------------------------- | ||
| 248 | # activate_for: called by BATsh with the raw script source before it | ||
| 249 | # is executed. Under 'auto', detection may switch the guard ON (and | ||
| 250 | # it then stays on -- see the stickiness note above). Under an | ||
| 251 | # explicit encoding the guard state is already fixed by set_encoding. | ||
| 252 | # ---------------------------------------------------------------- | ||
| 253 | sub activate_for { | ||
| 254 | my $src = defined $_[0] && $_[0] !~ /\ABATsh::MB\z/ ? $_[0] : $_[1]; | ||
| 255 | if ($ENCODING eq 'auto') { | ||
| 256 | my $det = detect($src); | ||
| 257 | _activate($det) if exists $ENC_TABLE{$det}; | ||
| 258 | } | ||
| 259 | return $ACTIVE; | ||
| 260 | } | ||
| 261 | |||
| 262 | # ---------------------------------------------------------------- | ||
| 263 | # enc: apply the guard transform (raw DBCS bytes -> guarded form) | ||
| 264 | # dec: remove the guard transform (guarded form -> raw DBCS bytes) | ||
| 265 | # Both are identity functions while the guard is inactive, so that | ||
| 266 | # ASCII and UTF-8 operation is entirely unaffected. | ||
| 267 | # ---------------------------------------------------------------- | ||
| 268 | sub enc { | ||
| 269 | my ($s) = @_; | ||
| 270 | return $s unless $ACTIVE && defined $s; | ||
| 271 | return $s unless $s =~ /[\x01\x81-\xfe]/; | ||
| 272 | $s =~ s/\x01/\x01\x01/g; | ||
| 273 | # Deliberately NOT /o: the classes change when the active encoding | ||
| 274 | # changes, so the substitution must be recompiled per call. | ||
| 275 | $s =~ s/([$LEAD])([$TRAIL])/ | ||
| 276 | do { | ||
| 277 | my ($lb, $tb) = ($1, $2); | ||
| 278 | $tb =~ m<\A[$DANGER]\z> | ||
| 279 | ? "\x01" . $lb . chr(ord($tb) + 0x80) | ||
| 280 | : $lb . $tb | ||
| 281 | } | ||
| 282 | /gex; | ||
| 283 | return $s; | ||
| 284 | } | ||
| 285 | |||
| 286 | sub dec { | ||
| 287 | my ($s) = @_; | ||
| 288 | return $s unless $ACTIVE && defined $s; | ||
| 289 | return $s unless index($s, "\x01") >= 0; | ||
| 290 | $s =~ s/\x01(\x01|[$LEAD][\xc0-\xfe])/ | ||
| 291 | $1 eq "\x01" | ||
| 292 | ? "\x01" | ||
| 293 | : substr($1, 0, 1) . chr(ord(substr($1, 1, 1)) - 0x80) | ||
| 294 | /gex; | ||
| 295 | return $s; | ||
| 296 | } | ||
| 297 | |||
| 298 | # ---------------------------------------------------------------- | ||
| 299 | # Character-oriented helpers, operating on GUARDED strings. | ||
| 300 | # While the guard is inactive they fall back to byte semantics, so | ||
| 301 | # existing ASCII behaviour is preserved bit-for-bit. | ||
| 302 | # | ||
| 303 | # mb_length($guarded) -> number of characters | ||
| 304 | # mb_substr($guarded, $off, $len) -> guarded substring by characters | ||
| 305 | # $off may be negative (counts back from the end, like substr); | ||
| 306 | # $len may be omitted (rest of string). | ||
| 307 | # ---------------------------------------------------------------- | ||
| 308 | sub mb_length { | ||
| 309 | my ($s) = @_; | ||
| 310 | return 0 unless defined $s; | ||
| 311 | return length($s) unless $ACTIVE; | ||
| 312 | my $chars = _mb_chars(dec($s)); | ||
| 313 | return scalar @{$chars}; | ||
| 314 | } | ||
| 315 | |||
| 316 | sub mb_substr { | ||
| 317 | my ($s, $off, $len) = @_; | ||
| 318 | return '' unless defined $s; | ||
| 319 | unless ($ACTIVE) { | ||
| 320 | return defined $len ? substr($s, $off, $len) : substr($s, $off); | ||
| 321 | } | ||
| 322 | my $chars = _mb_chars(dec($s)); | ||
| 323 | my $n = scalar @{$chars}; | ||
| 324 | $off = $n + $off if $off < 0; | ||
| 325 | $off = 0 if $off < 0; | ||
| 326 | return '' if $off >= $n; | ||
| 327 | my $end = defined $len ? $off + $len : $n; | ||
| 328 | $end = $n if $end > $n; | ||
| 329 | return '' if $end <= $off; | ||
| 330 | return enc(join('', @{$chars}[$off .. $end - 1])); | ||
| 331 | } | ||
| 332 | |||
| 333 | # Split RAW (decoded) DBCS bytes into characters, forward-scanning: | ||
| 334 | # a lead byte followed by a valid trail byte forms one two-byte | ||
| 335 | # character; anything else is a single byte. | ||
| 336 | sub _mb_chars { | ||
| 337 | my ($s) = @_; | ||
| 338 | my @c = (); | ||
| 339 | my $i = 0; | ||
| 340 | my $n = length($s); | ||
| 341 | while ($i < $n) { | ||
| 342 | my $b = substr($s, $i, 1); | ||
| 343 | if ($b =~ /[$LEAD]/ && $i + 1 < $n | ||
| 344 | && substr($s, $i + 1, 1) =~ /[$TRAIL]/) { | ||
| 345 | push @c, substr($s, $i, 2); | ||
| 346 | $i += 2; | ||
| 347 | } | ||
| 348 | else { | ||
| 349 | push @c, $b; | ||
| 350 | $i++; | ||
| 351 | } | ||
| 352 | } | ||
| 353 | return [ @c ]; | ||
| 354 | } | ||
| 355 | |||
| 356 | # ---------------------------------------------------------------- | ||
| 357 | # strip_bom: remove a UTF-8 byte-order mark from the head of the | ||
| 358 | # first script line (harmless everywhere, required for editors that | ||
| 359 | # save UTF-8-with-BOM). | ||
| 360 | # ---------------------------------------------------------------- | ||
| 361 | sub strip_bom { | ||
| 362 | my $s = defined $_[0] && $_[0] !~ /\ABATsh::MB\z/ ? $_[0] : $_[1]; | ||
| 363 | return $s unless defined $s; | ||
| 364 | $s =~ s/\A\xef\xbb\xbf//; | ||
| 365 | return $s; | ||
| 366 | } | ||
| 367 | |||
| 368 | 1; | ||
| 369 | |||
| 370 | __END__ |