///|
/// The three NTLM wire messages.
///
/// Only the fields this project actually consumes are modelled. A type 2
/// message is parsed so the client can answer it; a type 3 message is parsed
/// so a server (and the test suite) can check what a client sent. Encoding a
/// type 1 and a type 2 is enough to drive a real client, which is how the
/// implementation is tested against curl.
pub suberror MessageError {
  Truncated(Int)
  BadSignature
  BadMessageType(Int)
  BadField(Int, Int, Int)
}

///|
const SIGNATURE : Bytes = b"NTLMSSP\x00"

///|
/// The only Version field this library emits: Windows 10, build 19041,
/// revision 15. MS-NLMP 2.2.1.1 requires major 0x0A and revision 0x0F, so a
/// zero-filled eight-byte slot is not a valid Version.
const VERSION_FIELD : Bytes = b"\x0a\x00\x4a\x61\x00\x00\x00\x0f"

///|
fn has_signature(data : Bytes) -> Bool {
  if data.length() < 12 {
    return false
  }
  let mut same = true
  for i = 0; i < 8; i = i + 1 {
    if data[i] != SIGNATURE[i] {
      same = false
    }
  }
  same
}

///|
fn slice(data : Bytes, offset : Int, length : Int) -> Bytes raise MessageError {
  if offset < 0 || length < 0 || offset + length > data.length() {
    raise BadField(offset, length, data.length())
  }
  let out = FixedArray::make(length, b'\x00')
  for i = 0; i < length; i = i + 1 {
    out[i] = data[offset + i]
  }
  FixedArray::unsafe_reinterpret_as_bytes(out)
}

///|
/// A security buffer: 2-byte length, 2-byte allocated length, 4-byte offset.
fn read_sec_buffer(data : Bytes, at : Int) -> (Int, Int) raise MessageError {
  if at + 8 > data.length() {
    raise Truncated(at + 8)
  }
  let length = data[at].to_int() | (data[at + 1].to_int() << 8)
  let offset = @crypto.read_u32le(data, at + 4).reinterpret_as_int()
  (length, offset)
}

///|
fn write_sec_buffer(
  out : FixedArray[Byte],
  at : Int,
  length : Int,
  offset : Int,
) -> Unit {
  out[at] = (length & 0xFF).to_byte()
  out[at + 1] = ((length >> 8) & 0xFF).to_byte()
  out[at + 2] = (length & 0xFF).to_byte()
  out[at + 3] = ((length >> 8) & 0xFF).to_byte()
  for i = 0; i < 4; i = i + 1 {
    out[at + 4 + i] = ((offset >> (i * 8)) & 0xFF).to_byte()
  }
}

///|
pub fn message_type(data : Bytes) -> Int raise MessageError {
  if data.length() < 12 {
    raise Truncated(data.length())
  }
  if !has_signature(data) {
    raise BadSignature
  }
  @crypto.read_u32le(data, 8).reinterpret_as_int()
}

///|
/// Type 1, the client's opening message. Emitted with empty domain and
/// workstation: both are optional and servers do not require them.
///
/// `NEGOTIATE_VERSION` makes the eight-byte Version field part of the header,
/// so the two security buffers move to 40. Encoding a flag the layout does not
/// follow would produce a message a strict server rejects.
pub fn encode_type1(flags : UInt) -> Bytes {
  let has_version = (flags & 0x02000000U) != 0U
  let header = 32 + (if has_version { 8 } else { 0 })
  let out = FixedArray::make(header, b'\x00')
  for i = 0; i < 8; i = i + 1 {
    out[i] = SIGNATURE[i]
  }
  out[8] = b'\x01'
  for i = 0; i < 4; i = i + 1 {
    out[12 + i] = ((flags >> (i * 8)) & 0xFF).to_byte()
  }
  // Domain and workstation buffers both point past the header and carry 0.
  write_sec_buffer(out, 16, 0, header)
  write_sec_buffer(out, 24, 0, header)
  if has_version {
    for i = 0; i < 8; i = i + 1 {
      out[32 + i] = VERSION_FIELD[i]
    }
  }
  FixedArray::unsafe_reinterpret_as_bytes(out)
}

///|
pub struct Type2 {
  flags : UInt
  server_challenge : Bytes
  target_name : Bytes
  target_info : Bytes
}

///|
/// Parse a type 2 challenge. `target_info` is returned exactly as sent,
/// including its end-of-list pair; `make_blob` wants it without.
pub fn parse_type2(data : Bytes) -> Type2 raise MessageError {
  if message_type(data) != 2 {
    raise BadMessageType(message_type(data))
  }
  if data.length() < 48 {
    raise Truncated(data.length())
  }
  let (name_len, name_off) = read_sec_buffer(data, 12)
  let challenge = slice(data, 24, 8)
  let (info_len, info_off) = read_sec_buffer(data, 40)
  let name = if name_len == 0 { b"" } else { slice(data, name_off, name_len) }
  let info = if info_len == 0 { b"" } else { slice(data, info_off, info_len) }
  {
    flags: @crypto.read_u32le(data, 20),
    server_challenge: challenge,
    target_name: name,
    target_info: info,
  }
}

///|
pub fn Type2::flags(self : Type2) -> UInt {
  self.flags
}

///|
pub fn Type2::server_challenge(self : Type2) -> Bytes {
  self.server_challenge
}

///|
pub fn Type2::target_name(self : Type2) -> Bytes {
  self.target_name
}

///|
/// Target info without the trailing end-of-list pair, ready for `make_blob`.
///
/// The list is walked pair by pair rather than by looking at the last four
/// bytes, so a final pair whose value is zero (`MsvAvFlags = 0`) survives.
pub fn Type2::av_pairs(self : Type2) -> Bytes {
  let end = av_pairs_len(self.target_info)
  if end == self.target_info.length() {
    self.target_info
  } else {
    take_prefix(self.target_info, end)
  }
}

///|
/// `MsvAvFlags` (AV id 6) from the challenge, or 0 when the server sent none.
///
/// Bit 1 of the value tells the client to put a MIC in the authenticate
/// message; a server that sets it and then reads the field is the only way
/// this code path is exercised in practice.
pub fn Type2::av_flags(self : Type2) -> UInt {
  av_flags_of(self.target_info)
}

///|
/// `MsvAvTimestamp` (AV id 7) from the challenge, or `None` when absent.
///
/// MS-NLMP 3.1.5.2.1: if this pair is present, the client must use its value
/// as the timestamp of the NTLMv2 blob rather than the current time. A server
/// that sends a timestamp checks the blob against it, so an answer built with
/// a different time is rejected even when the password is right.
pub fn Type2::timestamp(self : Type2) -> UInt64? {
  av_timestamp_of(self.target_info)
}

///|
/// Whether the challenge carries `MsvAvTimestamp` (AV id 7).
pub fn Type2::has_timestamp(self : Type2) -> Bool {
  match self.timestamp() {
    Some(_) => true
    None => false
  }
}

///|
/// Whether the challenge asks for a MIC in the authenticate message.
///
/// MS-NLMP 3.1.5.1.2 gives two signals. `MsvAvFlags` bit 1 is the explicit
/// one; a `MsvAvTimestamp` pair is the other, and a server that sends one
/// expects the answer to be signed even when the flag is absent. Treating
/// only the flag as authoritative leaves those servers with an unsigned
/// answer, so both are checked.
pub fn Type2::requires_mic(self : Type2) -> Bool {
  (self.av_flags() & 0x2U) != 0U || self.has_timestamp()
}

///|
/// Build a challenge message, used by the mock server and by the tests.
///
/// As in `encode_type1`, setting `NEGOTIATE_VERSION` inserts the eight-byte
/// Version field before the payload and moves both security buffers past it.
pub fn encode_type2(
  flags : UInt,
  server_challenge : Bytes,
  target_name : Bytes,
  target_info : Bytes,
) -> Bytes {
  if server_challenge.length() != 8 {
    abort("encode_type2: the server challenge must be 8 bytes")
  }
  let has_version = (flags & 0x02000000U) != 0U
  let header = 48 + (if has_version { 8 } else { 0 })
  let out = FixedArray::make(
    header + target_name.length() + target_info.length(),
    b'\x00',
  )
  for i = 0; i < 8; i = i + 1 {
    out[i] = SIGNATURE[i]
  }
  out[8] = b'\x02'
  write_sec_buffer(out, 12, target_name.length(), header)
  for i = 0; i < 4; i = i + 1 {
    out[20 + i] = ((flags >> (i * 8)) & 0xFF).to_byte()
  }
  for i = 0; i < 8; i = i + 1 {
    out[24 + i] = server_challenge[i]
  }
  write_sec_buffer(out, 40, target_info.length(), header + target_name.length())
  if has_version {
    for i = 0; i < 8; i = i + 1 {
      out[48 + i] = VERSION_FIELD[i]
    }
  }
  for i = 0; i < target_name.length(); i = i + 1 {
    out[header + i] = target_name[i]
  }
  for i = 0; i < target_info.length(); i = i + 1 {
    out[header + target_name.length() + i] = target_info[i]
  }
  FixedArray::unsafe_reinterpret_as_bytes(out)
}

///|
pub struct Type3 {
  flags : UInt
  lm_response : Bytes
  nt_response : Bytes
  domain : String
  user : String
  workstation : String
  mic : Bytes
}

///|
/// The lowest offset any non-empty security buffer points at: where the
/// variable-length payload begins.
fn payload_start(data : Bytes) -> Int raise MessageError {
  let (lm_len, lm_off) = read_sec_buffer(data, 12)
  let (nt_len, nt_off) = read_sec_buffer(data, 20)
  let (dom_len, dom_off) = read_sec_buffer(data, 28)
  let (user_len, user_off) = read_sec_buffer(data, 36)
  let (ws_len, ws_off) = read_sec_buffer(data, 44)
  let (sk_len, sk_off) = read_sec_buffer(data, 52)
  let mut first = data.length()
  if lm_len > 0 && lm_off < first {
    first = lm_off
  }
  if nt_len > 0 && nt_off < first {
    first = nt_off
  }
  if dom_len > 0 && dom_off < first {
    first = dom_off
  }
  if user_len > 0 && user_off < first {
    first = user_off
  }
  if ws_len > 0 && ws_off < first {
    first = ws_off
  }
  if sk_len > 0 && sk_off < first {
    first = sk_off
  }
  first
}

///|
/// Where the MIC sits, or `None` when the message carries none.
///
/// The `NEGOTIATE_VERSION` flag is not enough to answer this. MS-NLMP puts the
/// optional Version field immediately before the MIC, so the payload offset is
/// the evidence that cannot lie: 88 means Version then MIC, 80 means MIC with
/// no Version, 72 means Version and no MIC, and 64 means neither. Windows sets
/// the flag and writes the field; pyspnego 0.13 sets the flag and writes no
/// field, and a parser that trusts the flag reads the MIC eight bytes off.
fn mic_offset(data : Bytes) -> Int? {
  let first = payload_start(data) catch { _ => return None }
  if first >= 88 {
    Some(72)
  } else if first >= 80 {
    Some(64)
  } else {
    None
  }
}

///|
/// Parse a type 3 message from any client. Strings are decoded as UTF-16LE;
/// malformed units are replaced rather than rejected, because a diagnostic
/// tool should still be able to show what arrived.
pub fn parse_type3(data : Bytes) -> Type3 raise MessageError {
  if message_type(data) != 3 {
    raise BadMessageType(message_type(data))
  }
  if data.length() < 64 {
    raise Truncated(data.length())
  }
  let (lm_len, lm_off) = read_sec_buffer(data, 12)
  let (nt_len, nt_off) = read_sec_buffer(data, 20)
  let (dom_len, dom_off) = read_sec_buffer(data, 28)
  let (user_len, user_off) = read_sec_buffer(data, 36)
  let (ws_len, ws_off) = read_sec_buffer(data, 44)
  let flags = @crypto.read_u32le(data, 60)
  let mic = match mic_offset(data) {
    Some(at) => if data.length() >= at + 16 { slice(data, at, 16) } else { b"" }
    None => b""
  }
  {
    flags,
    lm_response: if lm_len == 0 {
      b""
    } else {
      slice(data, lm_off, lm_len)
    },
    nt_response: if nt_len == 0 {
      b""
    } else {
      slice(data, nt_off, nt_len)
    },
    domain: if dom_len == 0 {
      ""
    } else {
      decode_utf16(slice(data, dom_off, dom_len))
    },
    user: if user_len == 0 {
      ""
    } else {
      decode_utf16(slice(data, user_off, user_len))
    },
    workstation: if ws_len == 0 {
      ""
    } else {
      decode_utf16(slice(data, ws_off, ws_len))
    },
    mic,
  }
}

///|
fn decode_utf16(data : Bytes) -> String {
  @utf16.decode_lossy(data, endianness=Little)
}

///|
pub fn Type3::user(self : Type3) -> String {
  self.user
}

///|
pub fn Type3::domain(self : Type3) -> String {
  self.domain
}

///|
pub fn Type3::workstation(self : Type3) -> String {
  self.workstation
}

///|
pub fn Type3::nt_response(self : Type3) -> Bytes {
  self.nt_response
}

///|
pub fn Type3::lm_response(self : Type3) -> Bytes {
  self.lm_response
}

///|
pub fn Type3::flags(self : Type3) -> UInt {
  self.flags
}

///|
/// The MIC carried by this message, or empty when it carries none.
pub fn Type3::mic(self : Type3) -> Bytes {
  self.mic
}

///|
/// Build a type 3 message. `session_key` may be empty: without
/// NEGOTIATE_KEY_EXCH the field is unused, and every server this project has
/// been tried against accepts an empty one.
pub fn encode_type3(
  user : String,
  domain : String,
  workstation : String,
  lm_response : Bytes,
  nt_response : Bytes,
  session_key : Bytes,
  flags : UInt,
) -> Bytes {
  encode_type3_with_mic(
    user, domain, workstation, lm_response, nt_response, session_key, flags, b"",
  )
}

///|
/// Build an authenticate message, optionally carrying a MIC.
///
/// MS-NLMP 2.2.1.3 puts an eight-byte Version field and then a sixteen-byte
/// MIC between NegotiateFlags and the payload. Both are optional, but a
/// message that carries a MIC has to carry the Version field before it,
/// otherwise the MIC lands at 64 and the server reads it as the tail of the
/// Version. Passing 16 bytes here writes both and starts the payload at 88;
/// passing an empty value writes neither. Any other length is treated as
/// "no MIC" — the caller has nothing valid to say at that size.
pub fn encode_type3_with_mic(
  user : String,
  domain : String,
  workstation : String,
  lm_response : Bytes,
  nt_response : Bytes,
  session_key : Bytes,
  flags : UInt,
  mic : Bytes,
) -> Bytes {
  let dom = @utf16.encode(domain, endianness=Little)
  let usr = @utf16.encode(user, endianness=Little)
  let ws = @utf16.encode(workstation, endianness=Little)
  let has_mic = mic.length() == 16
  // NEGOTIATE_VERSION is optional and independent of the MIC. When it is set,
  // the eight-byte Version field sits before the MIC; when it is clear the MIC
  // follows NegotiateFlags directly. MS-NLMP 2.2.1.3 lists both as optional,
  // so the header length is four combinations, not two.
  let has_version = (flags & 0x02000000U) != 0U
  let header = 64 +
    (if has_version { 8 } else { 0 }) +
    (if has_mic { 16 } else { 0 })
  let total = header +
    dom.length() +
    usr.length() +
    ws.length() +
    lm_response.length() +
    nt_response.length() +
    session_key.length()
  let out = FixedArray::make(total, b'\x00')
  for i = 0; i < 8; i = i + 1 {
    out[i] = SIGNATURE[i]
  }
  out[8] = b'\x03'
  let mut offset = header
  write_sec_buffer(out, 28, dom.length(), offset)
  offset = offset + dom.length()
  write_sec_buffer(out, 36, usr.length(), offset)
  offset = offset + usr.length()
  write_sec_buffer(out, 44, ws.length(), offset)
  offset = offset + ws.length()
  write_sec_buffer(out, 12, lm_response.length(), offset)
  offset = offset + lm_response.length()
  write_sec_buffer(out, 20, nt_response.length(), offset)
  offset = offset + nt_response.length()
  write_sec_buffer(out, 52, session_key.length(), offset)
  for i = 0; i < 4; i = i + 1 {
    out[60 + i] = ((flags >> (i * 8)) & 0xFF).to_byte()
  }
  if has_version {
    for i = 0; i < 8; i = i + 1 {
      out[64 + i] = VERSION_FIELD[i]
    }
  }
  if has_mic {
    let mic_at = header - 16
    for i = 0; i < 16; i = i + 1 {
      out[mic_at + i] = mic[i]
    }
  }
  let mut at = header
  for i = 0; i < dom.length(); i = i + 1 {
    out[at + i] = dom[i]
  }
  at = at + dom.length()
  for i = 0; i < usr.length(); i = i + 1 {
    out[at + i] = usr[i]
  }
  at = at + usr.length()
  for i = 0; i < ws.length(); i = i + 1 {
    out[at + i] = ws[i]
  }
  at = at + ws.length()
  for i = 0; i < lm_response.length(); i = i + 1 {
    out[at + i] = lm_response[i]
  }
  at = at + lm_response.length()
  for i = 0; i < nt_response.length(); i = i + 1 {
    out[at + i] = nt_response[i]
  }
  at = at + nt_response.length()
  for i = 0; i < session_key.length(); i = i + 1 {
    out[at + i] = session_key[i]
  }
  FixedArray::unsafe_reinterpret_as_bytes(out)
}

///|
/// Tokens travel base64-encoded inside `Authorization` and
/// `WWW-Authenticate`. These two helpers exist so callers do not have to know
/// which base64 flavour the protocol uses (standard, padded, with whitespace
/// tolerated on the way in).
pub fn token_to_header(token : Bytes) -> String {
  @base64.encode(token)
}

///|
pub fn token_from_header(text : String) -> Bytes raise {
  @base64.decode(text, ignore_whitespace=true)
}