def _delete_rules(self, ipfw_list=None):
   if ipfw_list is None:
     ipfw_list = platformsettings.ipfw('list')
   existing_rules = set(
       r.split()[0].lstrip('0') for r in ipfw_list.splitlines())
   delete_rules = [r for r in (self._DOWNLOAD_RULE, self._UPLOAD_RULE)
                   if r in existing_rules]
   if delete_rules:
     platformsettings.ipfw('delete', *delete_rules)
  def __enter__(self):
    if self.use_loopback:
      platformsettings.setup_temporary_loopback_config()
    if self.init_cwnd != '0':
      platformsettings.set_temporary_tcp_init_cwnd(self.init_cwnd)
    try:
      ipfw_list = platformsettings.ipfw('list')
      if not ipfw_list.startswith('65535 '):
        logging.warn('ipfw has existing rules:\n%s', ipfw_list)
        self._delete_rules(ipfw_list)
    except:
      pass
    if (self.up_bandwidth == '0' and self.down_bandwidth == '0' and
        self.delay_ms == '0' and self.packet_loss_rate == '0'):
      logging.info('Skipped shaping traffic.')
      return
    if not self.ports:
      raise TrafficShaperException('No ports on which to shape traffic.')

    ports = ','.join(str(p) for p in self.ports)
    half_delay_ms = int(self.delay_ms) / 2  # split over up/down links

    try:
      # Configure upload shaping.
      platformsettings.ipfw(
          'pipe', self._UPLOAD_PIPE,
          'config',
          'bw', self.up_bandwidth,
          'delay', half_delay_ms,
          )
      platformsettings.ipfw(
          'queue', self._UPLOAD_QUEUE,
          'config',
          'pipe', self._UPLOAD_PIPE,
          'plr', self.packet_loss_rate,
          'queue', self._QUEUE_SLOTS,
          'mask', 'src-port', '0xffff',
          )
      platformsettings.ipfw(
          'add', self._UPLOAD_RULE,
          'queue', self._UPLOAD_QUEUE,
          'ip',
          'from', 'any',
          'to', self.host,
          self.use_loopback and 'out' or 'in',
          'dst-port', ports,
          )
      self.is_shaping = True

      # Configure download shaping.
      platformsettings.ipfw(
          'pipe', self._DOWNLOAD_PIPE,
          'config',
          'bw', self.down_bandwidth,
          'delay', half_delay_ms,
          )
      platformsettings.ipfw(
          'queue', self._DOWNLOAD_QUEUE,
          'config',
          'pipe', self._DOWNLOAD_PIPE,
          'plr', self.packet_loss_rate,
          'queue', self._QUEUE_SLOTS,
          'mask', 'dst-port', '0xffff',
          )
      platformsettings.ipfw(
          'add', self._DOWNLOAD_RULE,
          'queue', self._DOWNLOAD_QUEUE,
          'ip',
          'from', self.host,
          'to', 'any',
          'out',
          'src-port', ports,
          )
      logging.info('Started shaping traffic')
    except Exception:
      logging.error('Unable to shape traffic.')
      raise