@@ -9,10 +9,13 @@ use tokio::sync::{RwLock, mpsc::UnboundedSender};
99
1010use moka:: future:: Cache ;
1111
12+ use std:: collections:: hash_map:: DefaultHasher ;
13+ use std:: hash:: { Hash , Hasher } ;
14+
1215pub struct Nat {
1316 nat_type : Type ,
14- cache : Cache < u32 , Arc < Session > > ,
15- mapping : Arc < RwLock < BiMap < u32 , u16 > > > ,
17+ cache : Cache < u64 , Arc < Session > > ,
18+ mapping : Arc < RwLock < BiMap < u64 , u16 > > > ,
1619}
1720
1821pub enum Type {
@@ -32,8 +35,8 @@ pub struct Session {
3235impl Nat {
3336 pub fn new ( nat_type : Type , tx : Option < UnboundedSender < u16 > > ) -> Self {
3437 let ttl = match nat_type {
35- Type :: Tcp => Duration :: from_secs ( 60 ) ,
36- Type :: Udp => Duration :: from_secs ( 20 ) ,
38+ Type :: Tcp => Duration :: from_secs ( 600 ) ,
39+ Type :: Udp => Duration :: from_secs ( 60 ) ,
3740 } ;
3841
3942 let mapping = Arc :: new ( RwLock :: new ( BiMap :: new ( ) ) ) ;
@@ -53,7 +56,12 @@ impl Nat {
5356 dst_addr : Ipv4Addr ,
5457 dst_port : u16 ,
5558 ) -> Result < Session , Error > {
56- let addr_key = u32:: from_be_bytes ( src_addr. octets ( ) ) + src_port as u32 ;
59+ let mut hasher = DefaultHasher :: new ( ) ;
60+ src_addr. hash ( & mut hasher) ;
61+ src_port. hash ( & mut hasher) ;
62+ dst_addr. hash ( & mut hasher) ;
63+ dst_port. hash ( & mut hasher) ;
64+ let addr_key = hasher. finish ( ) ;
5765
5866 if let Some ( session) = self . cache . get ( & addr_key) . await {
5967 return Ok ( * session) ;
@@ -121,13 +129,13 @@ impl Nat {
121129
122130 fn new_cache (
123131 ttl : Duration ,
124- mapping : Arc < RwLock < BiMap < u32 , u16 > > > ,
132+ mapping : Arc < RwLock < BiMap < u64 , u16 > > > ,
125133 tx : Option < UnboundedSender < u16 > > ,
126- ) -> Cache < u32 , Arc < Session > > {
134+ ) -> Cache < u64 , Arc < Session > > {
127135 Cache :: builder ( )
128136 . max_capacity ( 5000 )
129137 . time_to_idle ( ttl)
130- . eviction_listener ( move |addr_key : Arc < u32 > , session : Arc < Session > , _cause| {
138+ . eviction_listener ( move |addr_key : Arc < u64 > , session : Arc < Session > , _cause| {
131139 let mapping = mapping. clone ( ) ;
132140 let tx = tx. clone ( ) ;
133141 tokio:: task:: spawn ( async move {
@@ -141,7 +149,7 @@ impl Nat {
141149 . build ( )
142150 }
143151
144- async fn get_addr_key_by_port_fast ( & self , nat_port : & u16 ) -> Option < u32 > {
152+ async fn get_addr_key_by_port_fast ( & self , nat_port : & u16 ) -> Option < u64 > {
145153 let mapping = self . mapping . read ( ) . await ;
146154 mapping. get_by_right ( nat_port) . copied ( )
147155 }
0 commit comments