From 2fa8f1083bebc403058bd00d4a00859569922b29 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 14 Jun 2023 16:34:49 +0200 Subject: [PATCH] parse the question --- lib/response.ml | 28 ++++++++++++++++++++++++++-- lib/utils.ml | 2 ++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/response.ml b/lib/response.ml index 002a2cd..6221034 100644 --- a/lib/response.ml +++ b/lib/response.ml @@ -2,8 +2,32 @@ open Types open Utils let parse_header reader = - match List.init 6 (fun offset -> unpack_short_be reader (offset * 2)) with + let max_size = 6 in + match List.init max_size (fun offset -> unpack_short_be reader (offset * 2)) with | [ id; flags; num_questions; num_answers; num_authorities; num_additionals ] -> - { id; flags; num_questions; num_answers; num_authorities; num_additionals } + ( bytes_forward reader (max_size * 2) + , { id; flags; num_questions; num_answers; num_authorities; num_additionals } ) + | _ -> failwith "Invalid number of fields" +;; + +let decode_name_simple reader = + let rec read_parts parts pos = + let length = int_of_char (Bytes.get reader pos) in + if length = 0 + then 1, parts + else ( + let part = Bytes.sub_string reader (pos + 1) length in + let last_length, parts' = read_parts (parts @ [ part ]) (pos + 1 + length) in + last_length + length + 1, parts') + in + let offset, parts = read_parts [] 0 in + bytes_forward reader offset, String.concat "." parts +;; + +let parse_question reader = + let reader', name_b = decode_name_simple reader in + let name = String.to_bytes name_b in + match List.init 2 (fun offset -> unpack_short_be reader' (offset * 2)) with + | [ type_; class_ ] -> { name; type_; class_ } | _ -> failwith "Invalid number of fields" ;; diff --git a/lib/utils.ml b/lib/utils.ml index 5a1fe61..6e75aeb 100644 --- a/lib/utils.ml +++ b/lib/utils.ml @@ -32,3 +32,5 @@ let unpack_short_be data offset = let lsb = int_of_char (Bytes.get data (offset + 1)) in (msb lsl 8) + lsb ;; + +let bytes_forward data offset = Bytes.sub data offset (Bytes.length data - offset)