1use super::*;
4
5pub(crate) const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7pub(crate) fn bytes_to_base64(bytes: &[u8]) -> String {
9 let mut out = String::new();
10 for chunk in bytes.chunks(3) {
11 let b0 = chunk.first().copied().unwrap_or(0);
12 let b1 = chunk.get(1).copied().unwrap_or(0);
13 let b2 = chunk.get(2).copied().unwrap_or(0);
14 out.push(B64_CHARS[(b0 >> 2) as usize] as char);
15 out.push(B64_CHARS[(((b0 & 0x3) << 4) | (b1 >> 4)) as usize] as char);
16 out.push(if chunk.len() > 1 {
17 B64_CHARS[(((b1 & 0xf) << 2) | (b2 >> 6)) as usize] as char
18 } else {
19 '='
20 });
21 out.push(if chunk.len() > 2 {
22 B64_CHARS[(b2 & 0x3f) as usize] as char
23 } else {
24 '='
25 });
26 }
27 out
28}
29
30pub(crate) fn base64_to_bytes(s: &str) -> Vec<u8> {
33 let mut bits: u32 = 0;
34 let mut nbits = 0u32;
35 let mut out: Vec<u8> = Vec::new();
36 for c in s.bytes() {
37 let v = match c {
38 b'A'..=b'Z' => c - b'A',
39 b'a'..=b'z' => c - b'a' + 26,
40 b'0'..=b'9' => c - b'0' + 52,
41 b'+' | b'-' => 62, b'/' | b'_' => 63, _ => continue,
44 };
45 bits = (bits << 6) | v as u32;
46 nbits += 6;
47 if nbits >= 8 {
48 nbits -= 8;
49 out.push((bits >> nbits) as u8);
50 }
51 }
52 out
53}
54
55pub(crate) fn bytes_to_hex(bytes: &[u8]) -> String {
57 const HEX: &[u8; 16] = b"0123456789abcdef";
58 let mut out = String::with_capacity(bytes.len() * 2);
59 for &b in bytes {
60 out.push(HEX[(b >> 4) as usize] as char);
61 out.push(HEX[(b & 0xf) as usize] as char);
62 }
63 out
64}
65
66pub(crate) fn hex_to_bytes(s: &str) -> Option<Vec<u8>> {
68 let s = s.as_bytes();
69 if !s.len().is_multiple_of(2) {
70 return None;
71 }
72 fn nibble(c: u8) -> Option<u8> {
73 match c {
74 b'0'..=b'9' => Some(c - b'0'),
75 b'a'..=b'f' => Some(c - b'a' + 10),
76 b'A'..=b'F' => Some(c - b'A' + 10),
77 _ => None,
78 }
79 }
80 let mut out = Vec::with_capacity(s.len() / 2);
81 for pair in s.chunks(2) {
82 let hi = nibble(pair[0])?;
83 let lo = nibble(pair[1])?;
84 out.push((hi << 4) | lo);
85 }
86 Some(out)
87}
88
89pub(crate) fn forgiving_base64_decode(s: &str) -> Option<Vec<u8>> {
91 let mut data: Vec<u8> = Vec::with_capacity(s.len());
92 for c in s.chars() {
93 match c {
94 '\t' | '\n' | '\x0c' | '\r' | ' ' => {}
95 c if c.is_ascii() => data.push(c as u8),
96 _ => return None,
97 }
98 }
99 if data.len().is_multiple_of(4) {
100 if data.ends_with(b"==") {
101 data.truncate(data.len() - 2);
102 } else if data.ends_with(b"=") {
103 data.truncate(data.len() - 1);
104 }
105 }
106 if data.len() % 4 == 1 {
107 return None;
108 }
109 let mut bits: u32 = 0;
110 let mut nbits = 0u32;
111 let mut out: Vec<u8> = Vec::with_capacity(data.len() * 3 / 4);
112 for c in data {
113 let v = match c {
114 b'A'..=b'Z' => c - b'A',
115 b'a'..=b'z' => c - b'a' + 26,
116 b'0'..=b'9' => c - b'0' + 52,
117 b'+' => 62,
118 b'/' => 63,
119 _ => return None,
120 };
121 bits = (bits << 6) | v as u32;
122 nbits += 6;
123 if nbits >= 8 {
124 nbits -= 8;
125 out.push((bits >> nbits) as u8);
126 }
127 }
128 Some(out)
129}
130
131pub(crate) fn ta_to_bytes(this: &Value) -> Vec<u8> {
133 if let Value::Object(o) = this {
134 if let ObjKind::Bytes(st) = &o.borrow().kind {
135 return st.to_vec();
136 }
137 if let ObjKind::Array(items) = &o.borrow().kind {
138 return items.iter().map(|v| v.to_number() as i64 as u8).collect();
139 }
140 }
141 Vec::new()
142}
143
144pub(crate) fn ta_to_base64(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
146 Ok(Value::str(bytes_to_base64(&ta_to_bytes(&this))))
147}
148
149pub(crate) fn ta_to_hex(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
151 Ok(Value::str(bytes_to_hex(&ta_to_bytes(&this))))
152}
153
154pub(crate) fn ta_from_base64(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
156 let s = it.to_string_value(arg(a, 0))?;
157 Ok(make_uint8array(it, base64_to_bytes(&s)))
158}
159
160pub(crate) fn ta_from_hex(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
162 let s = it.to_string_value(arg(a, 0))?;
163 match hex_to_bytes(&s) {
164 Some(bytes) => Ok(make_uint8array(it, bytes)),
165 None => {
166 let err = syntax_error_ctor(
167 it,
168 Value::Undefined,
169 &[Value::str("Uint8Array.fromHex: invalid hex string")],
170 )?;
171 Err(err)
172 }
173 }
174}
175
176pub(crate) fn ta_write_bytes_into(this: &Value, bytes: &[u8], consumed_len: usize) -> Value {
183 let mut written = 0usize;
184 if let Value::Object(o) = this {
185 if let ObjKind::Bytes(st) = &o.borrow().kind {
186 written = bytes.len().min(st.len);
187 for (i, byte) in bytes.iter().take(written).enumerate() {
188 st.set(i, *byte as f64);
189 }
190 }
191 let mut b = o.borrow_mut();
192 if let ObjKind::Array(items) = &mut b.kind {
193 let cap = items.len();
194 written = bytes.len().min(cap);
195 for (slot, byte) in items.iter_mut().zip(bytes.iter()).take(written) {
196 *slot = Value::Number(*byte as f64);
197 }
198 }
199 }
200 let read = if written < bytes.len() {
201 consumed_len * written / bytes.len().max(1)
203 } else {
204 consumed_len
205 };
206 let o = Obj::plain();
207 {
208 let mut ob = o.borrow_mut();
209 ob.props.insert("read".into(), Value::Number(read as f64));
210 ob.props.insert("written".into(), Value::Number(written as f64));
211 }
212 Value::Object(o)
213}
214
215fn decode_base64_char(b: u8, url_safe: bool) -> Option<u8> {
216 match b {
217 b'A'..=b'Z' => Some(b - b'A'),
218 b'a'..=b'z' => Some(b - b'a' + 26),
219 b'0'..=b'9' => Some(b - b'0' + 52),
220 b'+' if !url_safe => Some(62),
221 b'/' if !url_safe => Some(63),
222 b'-' if url_safe => Some(62),
223 b'_' if url_safe => Some(63),
224 _ => None,
225 }
226}
227
228fn is_ascii_ws(b: u8) -> bool {
229 matches!(b, b'\t' | b'\n' | b'\x0c' | b'\r' | b' ')
230}
231
232#[derive(Clone, Copy, PartialEq, Eq)]
233enum LastChunkHandling {
234 Loose,
235 Strict,
236 StopBeforePartial,
237}
238
239fn parse_base64_options(it: &mut Interp, opts: &Value) -> Result<(bool, LastChunkHandling), Value> {
240 if matches!(opts, Value::Undefined) {
241 return Ok((false, LastChunkHandling::Loose));
242 }
243 if !matches!(opts, Value::Object(_)) {
244 return Err(it.type_error("Base64 options must be an object"));
245 }
246 let alph = it.get_property(opts, "alphabet")?;
247 let url_safe = match &alph {
248 Value::Undefined => false,
249 Value::Str(s) if s.as_str() == "base64" => false,
250 Value::Str(s) if s.as_str() == "base64url" => true,
251 _ => return Err(it.type_error("Invalid base64 alphabet option")),
252 };
253 let lch = it.get_property(opts, "lastChunkHandling")?;
254 let handling = match &lch {
255 Value::Undefined => LastChunkHandling::Loose,
256 Value::Str(s) if s.as_str() == "loose" => LastChunkHandling::Loose,
257 Value::Str(s) if s.as_str() == "strict" => LastChunkHandling::Strict,
258 Value::Str(s) if s.as_str() == "stop-before-partial" => LastChunkHandling::StopBeforePartial,
259 _ => return Err(it.type_error("Invalid lastChunkHandling option")),
260 };
261 Ok((url_safe, handling))
262}
263
264type Base64DecodeResult = Result<(Vec<u8>, usize), (&'static str, Vec<u8>)>;
265
266fn decode_base64_into(
267 s: &str,
268 url_safe: bool,
269 handling: LastChunkHandling,
270 max_bytes: usize,
271) -> Base64DecodeResult {
272 let bytes = s.as_bytes();
273 let mut out = Vec::new();
274 if max_bytes == 0 {
275 return Ok((out, 0));
276 }
277 let mut read = 0usize;
278 let mut idx = 0usize;
279 let mut chunk: [u8; 4] = [0; 4];
280 let mut chunk_pos: [usize; 4] = [0; 4];
281 let mut chunk_len = 0usize;
282 let mut pad_count = 0usize;
283 let mut saw_pad = false;
284
285 while idx < bytes.len() {
286 let b = bytes[idx];
287 if is_ascii_ws(b) {
288 idx += 1;
289 continue;
290 }
291 if b == b'=' {
292 if chunk_len < 2 || saw_pad && pad_count >= 2 {
293 return Err(("Unexpected padding in base64 string", out));
294 }
295 saw_pad = true;
296 pad_count += 1;
297 chunk[chunk_len] = 0;
298 chunk_pos[chunk_len] = idx + 1;
299 chunk_len += 1;
300 idx += 1;
301 } else if saw_pad {
302 return Err(("Unexpected character after base64 padding", out));
303 } else if let Some(val) = decode_base64_char(b, url_safe) {
304 chunk[chunk_len] = val;
305 chunk_pos[chunk_len] = idx + 1;
306 chunk_len += 1;
307 idx += 1;
308 } else {
309 return Err(("Invalid character in base64 string", out));
310 }
311
312 if chunk_len == 4 {
313 let emit_len = match pad_count {
314 0 => 3,
315 1 => 2,
316 2 => 1,
317 _ => return Err(("Invalid base64 padding", out)),
318 };
319 if handling == LastChunkHandling::Strict {
320 if pad_count == 1 && (chunk[2] & 0x03) != 0 {
321 return Err(("Non-zero padding bits in strict mode", out));
322 }
323 if pad_count == 2 && (chunk[1] & 0x0f) != 0 {
324 return Err(("Non-zero padding bits in strict mode", out));
325 }
326 }
327 if saw_pad {
328 while idx < bytes.len() && is_ascii_ws(bytes[idx]) {
329 idx += 1;
330 }
331 if idx < bytes.len() {
332 return Err(("Trailing characters after base64 padding", out));
333 }
334 }
335 if out.len() + emit_len > max_bytes {
336 return Ok((out, read));
337 }
338 let combined = ((chunk[0] as u32) << 18)
339 | ((chunk[1] as u32) << 12)
340 | ((chunk[2] as u32) << 6)
341 | (chunk[3] as u32);
342 out.push(((combined >> 16) & 0xff) as u8);
343 if emit_len >= 2 {
344 out.push(((combined >> 8) & 0xff) as u8);
345 }
346 if emit_len >= 3 {
347 out.push((combined & 0xff) as u8);
348 }
349 read = chunk_pos[3];
350 if saw_pad {
351 return Ok((out, bytes.len()));
352 }
353 if out.len() == max_bytes {
354 return Ok((out, read));
355 }
356 chunk_len = 0;
357 pad_count = 0;
358 }
359 }
360
361 if chunk_len == 0 {
362 return Ok((out, bytes.len()));
363 }
364 if saw_pad {
365 if handling == LastChunkHandling::StopBeforePartial {
366 return Ok((out, read));
367 }
368 return Err(("Incomplete padded base64 chunk", out));
369 }
370 match handling {
371 LastChunkHandling::StopBeforePartial => Ok((out, read)),
372 LastChunkHandling::Strict => Err(("Incomplete base64 chunk in strict mode", out)),
373 LastChunkHandling::Loose => {
374 if chunk_len == 1 {
375 return Err(("Single trailing base64 character", out));
376 }
377 let emit_len = if chunk_len == 2 { 1 } else { 2 };
378 if out.len() + emit_len > max_bytes {
379 return Ok((out, read));
380 }
381 let combined = ((chunk[0] as u32) << 18)
382 | ((chunk[1] as u32) << 12)
383 | ((chunk[2] as u32) << 6);
384 out.push(((combined >> 16) & 0xff) as u8);
385 if emit_len >= 2 {
386 out.push(((combined >> 8) & 0xff) as u8);
387 }
388 Ok((out, bytes.len()))
389 }
390 }
391}
392
393pub(crate) fn ta_set_from_base64(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
395 let max_bytes = if let Value::Object(o) = &this {
396 let b = o.borrow();
397 if crate::os_lib::ecma::value::ta_is_immutable(&b) {
398 return Err(it.type_error("Uint8Array buffer is immutable"));
399 }
400 if let Some(len) = crate::os_lib::ecma::value::ta_effective_len(&b) {
401 len
402 } else {
403 return Err(it.type_error("Uint8Array buffer is detached or out of bounds"));
404 }
405 } else {
406 0
407 };
408 let s_val = arg(a, 0);
409 let Value::Str(s) = &s_val else {
410 return Err(it.type_error("Uint8Array.prototype.setFromBase64 requires a string argument"));
411 };
412 if is_symbol_like_key(s) {
413 return Err(it.type_error("Uint8Array.prototype.setFromBase64 requires a string argument"));
414 }
415 let (url_safe, handling) = parse_base64_options(it, &arg(a, 1))?;
416 match decode_base64_into(s, url_safe, handling, max_bytes) {
417 Ok((bytes, read)) => {
418 let written = bytes.len();
419 if let Value::Object(o) = &this {
420 if let ObjKind::Bytes(st) = &o.borrow().kind {
421 for (i, byte) in bytes.iter().enumerate() {
422 st.set(i, *byte as f64);
423 }
424 }
425 }
426 let o = Obj::plain();
427 {
428 let mut ob = o.borrow_mut();
429 ob.props.insert("read".into(), Value::Number(read as f64));
430 ob.props.insert("written".into(), Value::Number(written as f64));
431 }
432 Ok(Value::Object(o))
433 }
434 Err((msg, bytes)) => {
435 if let Value::Object(o) = &this {
436 if let ObjKind::Bytes(st) = &o.borrow().kind {
437 for (i, byte) in bytes.iter().enumerate() {
438 st.set(i, *byte as f64);
439 }
440 }
441 }
442 let err = syntax_error_ctor(it, Value::Undefined, &[Value::str(msg)])?;
443 Err(err)
444 }
445 }
446}
447
448pub(crate) fn ta_set_from_hex(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
450 if let Value::Object(o) = &this {
451 let b = o.borrow();
452 if crate::os_lib::ecma::value::ta_is_immutable(&b) {
453 return Err(it.type_error("Uint8Array buffer is immutable"));
454 }
455 if crate::os_lib::ecma::value::ta_is_detached_or_oob(&b) {
456 return Err(it.type_error("Uint8Array buffer is detached or out of bounds"));
457 }
458 }
459 let s = it.to_string_value(arg(a, 0))?;
460 match hex_to_bytes(&s) {
461 Some(bytes) => {
462 let len = s.chars().count();
463 Ok(ta_write_bytes_into(&this, &bytes, len))
464 }
465 None => {
466 let err = syntax_error_ctor(
467 it,
468 Value::Undefined,
469 &[Value::str("Uint8Array.setFromHex: invalid hex string")],
470 )?;
471 Err(err)
472 }
473 }
474}
475
476pub(crate) fn percent_decode(s: &str, plus_as_space: bool) -> String {
482 let bytes = s.as_bytes();
483 let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
484 let mut i = 0;
485 while i < bytes.len() {
486 if bytes[i] == b'%' && i + 2 < bytes.len() {
487 let h1 = bytes[i + 1];
488 let h2 = bytes[i + 2];
489 if let (Some(n1), Some(n2)) = (char::from(h1).to_digit(16), char::from(h2).to_digit(16)) {
490 let byte = ((n1 << 4) | n2) as u8;
491 out.push(byte);
492 i += 3;
493 continue;
494 }
495 }
496 if plus_as_space && bytes[i] == b'+' {
497 out.push(b' ');
498 } else {
499 out.push(bytes[i]);
500 }
501 i += 1;
502 }
503 String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
504}
505
506pub(crate) fn percent_encode_component(s: &str) -> String {
508 let mut out = String::new();
509 for b in s.as_bytes() {
510 match *b {
511 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*'
512 | b'\'' | b'(' | b')' => {
513 out.push(*b as char);
514 }
515 _ => out.push_str(&alloc::format!("%{:02X}", b)),
516 }
517 }
518 out
519}
520
521pub(crate) fn percent_encode_uri(s: &str) -> String {
524 let mut out = String::new();
525 for b in s.as_bytes() {
526 match *b {
527 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*'
528 | b'\'' | b'(' | b')' | b';' | b'/' | b'?' | b':' | b'@' | b'&' | b'=' | b'+'
529 | b'$' | b',' | b'#' => {
530 out.push(*b as char);
531 }
532 _ => out.push_str(&alloc::format!("%{:02X}", b)),
533 }
534 }
535 out
536}
537
538pub(crate) fn js_encode_uri_component(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
539 Ok(Value::str(percent_encode_component(&it.to_string_value(arg(a, 0))?)))
540}
541pub(crate) fn js_decode_uri_component(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
542 match uri_decode(&it.to_string_value(arg(a, 0))?, "") {
543 Some(s) => Ok(Value::str(s)),
544 None => Err(it.error_of_kind("URIError", "URI malformed")),
545 }
546}
547pub(crate) fn js_encode_uri(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
548 Ok(Value::str(percent_encode_uri(&it.to_string_value(arg(a, 0))?)))
549}
550pub(crate) fn js_decode_uri(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
551 match uri_decode(&it.to_string_value(arg(a, 0))?, ";/?:@&=+$,#") {
552 Some(s) => Ok(Value::str(s)),
553 None => Err(it.error_of_kind("URIError", "URI malformed")),
554 }
555}
556
557fn uri_decode(s: &str, reserved: &str) -> Option<String> {
562 let bytes = s.as_bytes();
563 let hex = |i: usize| -> Option<u8> {
564 let h1 = char::from(*bytes.get(i + 1)?).to_digit(16)?;
565 let h2 = char::from(*bytes.get(i + 2)?).to_digit(16)?;
566 (*bytes.get(i)? == b'%').then_some(((h1 << 4) | h2) as u8)
567 };
568 let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
569 let mut i = 0;
570 while i < bytes.len() {
571 if bytes[i] != b'%' {
572 out.push(bytes[i]);
573 i += 1;
574 continue;
575 }
576 let b = hex(i)?;
577 if b < 0x80 {
578 if reserved.as_bytes().contains(&b) {
579 out.extend_from_slice(bytes.get(i..i + 3)?);
580 } else {
581 out.push(b);
582 }
583 i += 3;
584 continue;
585 }
586 let n = match b {
587 0xC0..=0xDF => 2,
588 0xE0..=0xEF => 3,
589 0xF0..=0xF7 => 4,
590 _ => return None,
591 };
592 let mut seq = alloc::vec![b];
593 for k in 1..n {
594 let c = hex(i + 3 * k)?;
595 if c & 0xC0 != 0x80 {
596 return None;
597 }
598 seq.push(c);
599 }
600 core::str::from_utf8(&seq).ok()?;
601 out.extend_from_slice(&seq);
602 i += 3 * n;
603 }
604 String::from_utf8(out).ok()
605}
606
607pub(crate) fn js_escape(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
613 let s = it.to_string_value(arg(a, 0))?;
614 let mut out = String::new();
615 for c in s.chars() {
616 let unreserved =
617 matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | '@' | '*' | '_' | '+' | '-' | '.' | '/');
618 if unreserved {
619 out.push(c);
620 } else {
621 let cp = c as u32;
622 if cp <= 0xFF {
623 out.push_str(&alloc::format!("%{:02X}", cp));
624 } else {
625 out.push_str(&alloc::format!("%u{:04X}", cp));
626 }
627 }
628 }
629 Ok(Value::str(out))
630}
631pub(crate) fn js_unescape(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
634 let s = it.to_string_value(arg(a, 0))?;
635 let chars: Vec<char> = s.chars().collect();
636 let mut out = String::new();
637 let mut i = 0;
638 while i < chars.len() {
639 if chars[i] == '%' && i + 6 <= chars.len() && chars[i + 1] == 'u' {
640 let hex: String = chars[i + 2..i + 6].iter().collect();
641 if let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
642 out.push(ch);
643 i += 6;
644 continue;
645 }
646 }
647 if chars[i] == '%' && i + 3 <= chars.len() {
648 let hex: String = chars[i + 1..i + 3].iter().collect();
649 if let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
650 out.push(ch);
651 i += 3;
652 continue;
653 }
654 }
655 out.push(chars[i]);
656 i += 1;
657 }
658 Ok(Value::str(out))
659}
660
661pub(crate) fn next_rand_u64() -> u64 {
663 let mut x = RNG_SEED.load(Ordering::Relaxed);
664 if x == RNG_SEED_UNSET {
665 x = boot_seed();
666 }
667 x ^= x >> 12;
668 x ^= x << 25;
669 x ^= x >> 27;
670 RNG_SEED.store(x, Ordering::Relaxed);
671 x.wrapping_mul(0x2545F4914F6CDD1D)
672}
673
674fn boot_seed() -> u64 {
680 let unix = crate::os_lib::platform::unix_time().unwrap_or(0);
681 let us = crate::os_lib::platform::now_us();
682 let mut z = unix.wrapping_mul(0x9E3779B97F4A7C15) ^ us.rotate_left(32) ^ 0xD1B54A32D192ED03;
684 z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
685 z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
686 z ^= z >> 31;
687 if z == 0 || z == RNG_SEED_UNSET {
688 z = 0x9E3779B97F4A7C15;
689 }
690 z
691}
692