My_nat.free_udp_port: avoid looping forever, use last_resort_port earlier

This commit is contained in:
Hannes Mehnert 2022-11-08 18:57:09 +01:00
parent d094b20950
commit e8e03fe6a6

View File

@ -44,22 +44,25 @@ let pick_free_port t proto =
go 10 go 10
let free_udp_port t ~src ~dst ~dst_port = let free_udp_port t ~src ~dst ~dst_port =
let rec go () = let rec go retries =
let src_port = if retries = 0 then
Option.value ~default:t.last_resort_port (pick_free_port t `Udp) t.last_resort_port, Fun.id
in else
if Nat.is_port_free t.table `Udp ~src ~dst ~src_port ~dst_port then begin let src_port =
let remove = Option.value ~default:t.last_resort_port (pick_free_port t `Udp)
if src_port <> t.last_resort_port then begin
t.udp_dns <- S.add src_port t.udp_dns;
(fun () -> t.udp_dns <- S.remove src_port t.udp_dns)
end else Fun.id
in in
src_port, remove if Nat.is_port_free t.table `Udp ~src ~dst ~src_port ~dst_port then begin
end else let remove =
go () if src_port <> t.last_resort_port then begin
t.udp_dns <- S.add src_port t.udp_dns;
(fun () -> t.udp_dns <- S.remove src_port t.udp_dns)
end else Fun.id
in
src_port, remove
end else
go (retries - 1)
in in
go () go 10
let dns_port t port = S.mem port t.udp_dns || port = t.last_resort_port let dns_port t port = S.mem port t.udp_dns || port = t.last_resort_port