forked from mirage/mirage
/
server.ml
92 lines (83 loc) · 2.81 KB
/
server.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
(*
* Copyright (c) 2005-2011 Anil Madhavapeddy <anil@recoil.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Lwt
open Printf
module DL = Dnsloader
module DQ = Dnsquery
module DR = Dnsrr
module DP = Dnspacket
let dnstrie = DL.(state.db.trie)
let get_answer qname qtype id =
let qname = List.map String.lowercase qname in
let ans = DQ.answer_query qname qtype dnstrie in
let detail =
DP.(build_detail { qr=`Answer; opcode=`Query;
aa=ans.DQ.aa; tc=false; rd=false; ra=false;
rcode=ans.DQ.rcode;
})
in
let questions = [ DP.({ q_name=qname; q_type=qtype; q_class=`IN }) ] in
DP.({ id; detail; questions;
answers=ans.DQ.answer;
authorities=ans.DQ.authority;
additionals=ans.DQ.additional;
})
(* Space leaking hash table cache, always grows *)
module Leaking_cache = Hashtbl.Make (struct
type t = string list * DP.q_type
let equal (a:t) (b:t) = a = b
let hash = Hashtbl.hash
end)
let cache = Leaking_cache.create 1
let get_answer_memo qname qtype id =
let qargs = qname, qtype in
let r =
try
Leaking_cache.find cache qargs
with Not_found -> (
let r = get_answer qname qtype id in
Leaking_cache.add cache qargs r;
r
)
in
DP.({ r with id })
let no_memo mgr src dst bits =
let names = Hashtbl.create 8 in
DP.(
let d = parse_dns names bits in
let q = List.hd d.questions in
let r = get_answer q.q_name q.q_type d.id in
let p = marshal r in
let _ = Net.Datagram.UDPv4.send mgr ~src dst p in return ()
)
let leaky mgr src dst bits =
let names = Hashtbl.create 8 in
DP.(
let d = DP.parse_dns names bits in
let q = List.hd d.questions in
let r = get_answer_memo q.q_name q.q_type d.id in
let p = marshal r in
Net.Datagram.UDPv4.send mgr ~src dst p
)
let listen ?(mode=`none) ~zonebuf mgr src =
Dnsserver.load_zone [] zonebuf;
Gc.compact ();
Net.Datagram.UDPv4.(recv mgr src
(match mode with
|`none -> no_memo mgr src
|`leaky -> leaky mgr src
)
)