/ RNS / Interfaces / Interface.py
Interface.py
  1  # Reticulum License
  2  #
  3  # Copyright (c) 2016-2025 Mark Qvist
  4  #
  5  # Permission is hereby granted, free of charge, to any person obtaining a copy
  6  # of this software and associated documentation files (the "Software"), to deal
  7  # in the Software without restriction, including without limitation the rights
  8  # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9  # copies of the Software, and to permit persons to whom the Software is
 10  # furnished to do so, subject to the following conditions:
 11  #
 12  # - The Software shall not be used in any kind of system which includes amongst
 13  #   its functions the ability to purposefully do harm to human beings.
 14  #
 15  # - The Software shall not be used, directly or indirectly, in the creation of
 16  #   an artificial intelligence, machine learning or language model training
 17  #   dataset, including but not limited to any use that contributes to the
 18  #   training or development of such a model or algorithm.
 19  #
 20  # - The above copyright notice and this permission notice shall be included in
 21  #   all copies or substantial portions of the Software.
 22  #
 23  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 24  # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 25  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 26  # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 27  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 28  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 29  # SOFTWARE.
 30  
 31  import RNS
 32  import time
 33  import threading
 34  from collections import deque
 35  from RNS.vendor.configobj import ConfigObj
 36  
 37  class Interface:
 38      IN  = False
 39      OUT = False
 40      FWD = False
 41      RPT = False
 42      name = None
 43  
 44      # Interface mode definitions
 45      MODE_FULL           = 0x01
 46      MODE_POINT_TO_POINT = 0x02
 47      MODE_ACCESS_POINT   = 0x03
 48      MODE_ROAMING        = 0x04
 49      MODE_BOUNDARY       = 0x05
 50      MODE_GATEWAY        = 0x06
 51  
 52      # Which interface modes a Transport Node should
 53      # actively discover paths for.
 54      DISCOVER_PATHS_FOR  = [MODE_ACCESS_POINT, MODE_GATEWAY, MODE_ROAMING]
 55  
 56      # How many samples to use for announce
 57      # frequency calculations
 58      IA_FREQ_SAMPLES     = 6
 59      OA_FREQ_SAMPLES     = 6
 60  
 61      # Maximum amount of ingress limited announces
 62      # to hold at any given time.
 63      MAX_HELD_ANNOUNCES  = 256
 64  
 65      # How long a spawned interface will be
 66      # considered to be newly created. Two
 67      # hours by default.
 68      IC_NEW_TIME              = 2*60*60
 69      IC_BURST_FREQ_NEW        = 3.5
 70      IC_BURST_FREQ            = 12
 71      IC_BURST_HOLD            = 1*60
 72      IC_BURST_PENALTY         = 5*60
 73      IC_HELD_RELEASE_INTERVAL = 30
 74  
 75      AUTOCONFIGURE_MTU = False
 76      FIXED_MTU         = False
 77  
 78      def __init__(self):
 79          self.rxb      = 0
 80          self.txb      = 0
 81          self.created  = time.time()
 82          self.detached = False
 83          self.online   = False
 84          self.bitrate  = 62500
 85          self.HW_MTU   = None
 86  
 87          self.parent_interface = None
 88          self.spawned_interfaces = None
 89          self.tunnel_id = None
 90          self.ingress_control = True
 91          self.ic_max_held_announces = Interface.MAX_HELD_ANNOUNCES
 92          self.ic_burst_hold = Interface.IC_BURST_HOLD
 93          self.ic_burst_active = False
 94          self.ic_burst_activated = 0
 95          self.ic_held_release = 0
 96          self.ic_burst_freq_new = Interface.IC_BURST_FREQ_NEW
 97          self.ic_burst_freq = Interface.IC_BURST_FREQ
 98          self.ic_new_time = Interface.IC_NEW_TIME
 99          self.ic_burst_penalty = Interface.IC_BURST_PENALTY
100          self.ic_held_release_interval = Interface.IC_HELD_RELEASE_INTERVAL
101          self.held_announces = {}
102  
103          self.ia_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES)
104          self.oa_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES)
105  
106      def get_hash(self):
107          return RNS.Identity.full_hash(str(self).encode("utf-8"))
108  
109      # This is a generic function for determining when an interface
110      # should activate ingress limiting. Since this can vary for
111      # different interface types, this function should be overwritten
112      # in case a particular interface requires a different approach.
113      def should_ingress_limit(self):
114          if self.ingress_control:
115              freq_threshold = self.ic_burst_freq_new if self.age() < self.ic_new_time else self.ic_burst_freq
116              ia_freq = self.incoming_announce_frequency()
117  
118              if self.ic_burst_active:
119                  if ia_freq < freq_threshold and time.time() > self.ic_burst_activated+self.ic_burst_hold:
120                      self.ic_burst_active = False
121                      self.ic_held_release = time.time() + self.ic_burst_penalty
122                  return True
123  
124              else:
125                  if ia_freq > freq_threshold:
126                      self.ic_burst_active = True
127                      self.ic_burst_activated = time.time()
128                      return True
129  
130                  else:
131                      return False
132  
133          else:
134              return False
135  
136      def optimise_mtu(self):
137          if self.AUTOCONFIGURE_MTU:
138              if self.bitrate   >= 1_000_000_000:
139                  self.HW_MTU = 524288
140              elif self.bitrate > 750_000_000:
141                  self.HW_MTU = 262144
142              elif self.bitrate > 400_000_000:
143                  self.HW_MTU = 131072
144              elif self.bitrate > 200_000_000:
145                  self.HW_MTU = 65536
146              elif self.bitrate > 100_000_000:
147                  self.HW_MTU = 32768
148              elif self.bitrate > 10_000_000:
149                  self.HW_MTU = 16384
150              elif self.bitrate > 5_000_000:
151                  self.HW_MTU = 8192
152              elif self.bitrate > 2_000_000:
153                  self.HW_MTU = 4096
154              elif self.bitrate > 1_000_000:
155                  self.HW_MTU = 2048
156              elif self.bitrate > 62_500:
157                  self.HW_MTU = 1024
158              else:
159                  self.HW_MTU = None
160  
161          RNS.log(f"{self} hardware MTU set to {self.HW_MTU}", RNS.LOG_DEBUG) # TODO: Remove debug
162  
163      def age(self):
164          return time.time()-self.created
165  
166      def hold_announce(self, announce_packet):
167          if announce_packet.destination_hash in self.held_announces:
168              self.held_announces[announce_packet.destination_hash] = announce_packet
169          elif not len(self.held_announces) >= self.ic_max_held_announces:
170              self.held_announces[announce_packet.destination_hash] = announce_packet
171  
172      def process_held_announces(self):
173          try:
174              if not self.should_ingress_limit() and len(self.held_announces) > 0 and time.time() > self.ic_held_release:
175                  freq_threshold = self.ic_burst_freq_new if self.age() < self.ic_new_time else self.ic_burst_freq
176                  ia_freq = self.incoming_announce_frequency()
177                  if ia_freq < freq_threshold:
178                      selected_announce_packet = None
179                      min_hops = RNS.Transport.PATHFINDER_M
180                      for destination_hash in self.held_announces:
181                          announce_packet = self.held_announces[destination_hash]
182                          if announce_packet.hops < min_hops:
183                              min_hops = announce_packet.hops
184                              selected_announce_packet = announce_packet
185  
186                      if selected_announce_packet != None:
187                          RNS.log("Releasing held announce packet "+str(selected_announce_packet)+" from "+str(self), RNS.LOG_EXTREME)
188                          self.ic_held_release = time.time() + self.ic_held_release_interval
189                          self.held_announces.pop(selected_announce_packet.destination_hash)
190                          def release():
191                              RNS.Transport.inbound(selected_announce_packet.raw, selected_announce_packet.receiving_interface)
192                          threading.Thread(target=release, daemon=True).start()
193          
194          except Exception as e:
195              RNS.log("An error occurred while processing held announces for "+str(self), RNS.LOG_ERROR)
196              RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
197  
198      def received_announce(self, from_spawned=False):
199          self.ia_freq_deque.append(time.time())
200          if hasattr(self, "parent_interface") and self.parent_interface != None:
201              self.parent_interface.received_announce(from_spawned=True)
202  
203      def sent_announce(self, from_spawned=False):
204          self.oa_freq_deque.append(time.time())
205          if hasattr(self, "parent_interface") and self.parent_interface != None:
206              self.parent_interface.sent_announce(from_spawned=True)
207  
208      def incoming_announce_frequency(self):
209          if not len(self.ia_freq_deque) > 1:
210              return 0
211          else:
212              dq_len = len(self.ia_freq_deque)
213              delta_sum = 0
214              for i in range(1,dq_len):
215                  delta_sum += self.ia_freq_deque[i]-self.ia_freq_deque[i-1]
216              delta_sum += time.time() - self.ia_freq_deque[dq_len-1]
217              
218              if delta_sum == 0:
219                  avg = 0
220              else:
221                  avg = 1/(delta_sum/(dq_len))
222  
223              return avg
224  
225      def outgoing_announce_frequency(self):
226          if not len(self.oa_freq_deque) > 1:
227              return 0
228          else:
229              dq_len = len(self.oa_freq_deque)
230              delta_sum = 0
231              for i in range(1,dq_len):
232                  delta_sum += self.oa_freq_deque[i]-self.oa_freq_deque[i-1]
233              delta_sum += time.time() - self.oa_freq_deque[dq_len-1]
234              
235              if delta_sum == 0:
236                  avg = 0
237              else:
238                  avg = 1/(delta_sum/(dq_len))
239  
240              return avg
241  
242      def process_announce_queue(self):
243          if not hasattr(self, "announce_cap"):
244              self.announce_cap = RNS.Reticulum.ANNOUNCE_CAP
245  
246          if hasattr(self, "announce_queue"):
247              try:
248                  now = time.time()
249                  stale = []
250                  for a in self.announce_queue:
251                      if now > a["time"]+RNS.Reticulum.QUEUED_ANNOUNCE_LIFE:
252                          stale.append(a)
253  
254                  for s in stale:
255                      if s in self.announce_queue:
256                          self.announce_queue.remove(s)
257  
258                  if len(self.announce_queue) > 0:
259                      min_hops = min(entry["hops"] for entry in self.announce_queue)
260                      entries = list(filter(lambda e: e["hops"] == min_hops, self.announce_queue))
261                      entries.sort(key=lambda e: e["time"])
262                      selected = entries[0]
263  
264                      now       = time.time()
265                      tx_time   = (len(selected["raw"])*8) / self.bitrate
266                      wait_time = (tx_time / self.announce_cap)
267                      self.announce_allowed_at = now + wait_time
268  
269                      self.process_outgoing(selected["raw"])
270                      self.sent_announce()
271  
272                      if selected in self.announce_queue:
273                          self.announce_queue.remove(selected)
274  
275                      if len(self.announce_queue) > 0:
276                          timer = threading.Timer(wait_time, self.process_announce_queue)
277                          timer.start()
278  
279              except Exception as e:
280                  self.announce_queue = []
281                  RNS.log("Error while processing announce queue on "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
282                  RNS.log("The announce queue for this interface has been cleared.", RNS.LOG_ERROR)
283  
284      def final_init(self):
285          pass
286  
287      def detach(self):
288          pass
289  
290      @staticmethod
291      def get_config_obj(config_in):
292          if type(config_in) == ConfigObj:
293              return config_in
294          else:
295              try:
296                  return ConfigObj(config_in)
297              except Exception as e:
298                  RNS.log(f"Could not parse supplied configuration data. The contained exception was: {e}", RNS.LOG_ERROR)
299                  raise SystemError("Invalid configuration data supplied")