# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

# The Mail gem and the parsers built on it walk the part tree recursively, at a cost that grows
#   steeply with its depth. The Mail gem splits the bodies of the parts lazily, so this walk
#   measures the tree one level at a time without recursion, before anything else descends into it.
class Channel::EmailParser::StructureCheck
  MAX_DEPTH = 30
  MAX_PARTS = 500

  class LimitExceeded < StandardError; end

  attr_reader :mail

  def initialize(mail)
    @mail = mail
  end

  def verify!
    pending     = [[mail, 0]]
    parts_count = 0

    while (part, depth = pending.pop)
      next if !part.multipart?

      raise LimitExceeded, "The email has more than #{MAX_DEPTH} levels of nested parts." if depth >= MAX_DEPTH

      raise_too_many_parts if parts_count + delimiters_count(part) - 1 > MAX_PARTS

      parts_count += part.parts.size
      raise_too_many_parts if parts_count > MAX_PARTS

      part.parts.each { |sub_part| pending.push([sub_part, depth + 1]) }
    end

    true
  end

  private

  def raise_too_many_parts
    raise LimitExceeded, "The email has more than #{MAX_PARTS} parts."
  end

  # The Mail gem builds every part of a level at once, so a level with too many of them is rejected
  #   on its delimiter lines, matched as the Mail gem splits on them, before it is split. It takes
  #   the text between two of them as a part, whether the second one is a closing delimiter or not.
  def delimiters_count(part)
    count = 0
    part.raw_source.scan(%r{^--#{Regexp.escape(part.boundary.to_s)}(?:--)?(?=\s*$)}) do
      count += 1
      break if count > MAX_PARTS + 1
    end
    count
  end
end
