internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: secdev/scapy

Issue:
Interface routing issue with `send` on layer 3
I setup my UDP server by python code below.
```python
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('192.168.8.104', 9999))

print('Bind UDP on 9999...')

while True:
    data, addr = s.recvfrom(1024)
    print('Received from %s ---> %s' % (addr, data.decode("utf-8")))
```
and then,I try to send UPD package by scapy.
```python
send(IP(src="192.168.8.110",dst="192.168.8.104")/UDP(dport=9999,sport=5678)/"Hello scapy udp")
```
result is `Sent 1 packets.in terminal`.But I can't see anything in my udp server logout.

and then,I try to use another way to send UPD package like this:
```python
sr1(IP(src="192.168.8.110",dst="192.168.8.104")/UDP(dport=9999,sport=5678)/"Hello scapy udp")
```
IT WORKED(I mean that i can see logout in my UDP server)!!!WHY?????Can somebody answer for me.

**I asked this question on StackOverflow.com but nobody answer for me.So,if you see this,please help me.Thank you for your waste time watch this.**


Discussion:

Resolving patch:
diff --git a/scapy/sendrecv.py b/scapy/sendrecv.py
--- a/scapy/sendrecv.py
+++ b/scapy/sendrecv.py
@@ -306,9 +306,8 @@ def __gen_send(s, x, inter=0, loop=0, count=None, verbose=None, realtime=None, r
 
 
 @conf.commands.register
-def send(x, inter=0, loop=0, count=None,
-         verbose=None, realtime=None,
-         return_packets=False, socket=None, *args, **kargs):
+def send(x, inter=0, loop=0, count=None, verbose=None, realtime=None,
+         return_packets=False, socket=None, iface=None, *args, **kargs):
     """
     Send packets at layer 3
 
@@ -325,6 +324,7 @@ def send(x, inter=0, loop=0, count=None,
     :returns: None
     """
     need_closing = socket is None
+    kargs["iface"] = _interface_selection(iface, x)
     socket = socket or conf.L3socket(*args, **kargs)
     results = __gen_send(socket, x, inter=inter, loop=loop,
                          count=count, verbose=verbose,


Test patch:
Repository: secdev/scapy

Issue:
Getting "Exception ignored in: <bound method SuperSocket.__del__ of ... >"
#### Brief description

Using `sniff` method with unreal `iface` parameter leads to `Ignored exception ...`

#### Environment

-   Scapy version: `Version 2.4.3`
-   Python version: `Python 3.6.9`
-   Operating System: `Linux 5.3.0-28-generic #30~18.04.1-Ubuntu x86_64 GNU/Linux`


#### How to reproduce
```
# (module name : sample.py)
import scapy.all as scapy


def main():
    try:
        pkts = scapy.sniff(iface="mocked")
    except Exception as e:
        print("===========================================")
        print(str(e))
        print("===========================================")
        exit()


if __name__ == "__main__":
    main()
```

Ran from terminal as:
`$ sudo python ./sample.py`

#### Actual result

```
$ sudo python ./sample.py 
===========================================
[Errno 19] No such device
===========================================
Exception ignored in: <bound method SuperSocket.__del__ of <scapy.arch.linux.L2ListenSocket object at 0x7f7ca13086a0>>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/scapy/supersocket.py", line 134, in __del__
    self.close()
  File "/usr/local/lib/python3.6/dist-packages/scapy/arch/linux.py", line 514, in close
    set_promisc(self.ins, self.iface, 0)
  File "/usr/local/lib/python3.6/dist-packages/scapy/arch/linux.py", line 165, in set_promisc
    mreq = struct.pack("IHH8s", get_if_index(iff), PACKET_MR_PROMISC, 0, b"")
  File "/usr/local/lib/python3.6/dist-packages/scapy/arch/linux.py", line 380, in get_if_index
    return int(struct.unpack("I", get_if(iff, SIOCGIFINDEX)[16:20])[0])
  File "/usr/local/lib/python3.6/dist-packages/scapy/arch/common.py", line 59, in get_if
    ifreq = ioctl(sck, cmd, struct.pack("16s16x", iff.encode("utf8")))
OSError: [Errno 19] No such device
```
#### Expected result

Just a successful exit from a program without additional std::err output.

#### Related resources

<!-- traces / sample pcaps (stripped to the relevant frames), related standards, RFCs or other resources -->



Discussion:

Resolving patch:
diff --git a/scapy/arch/linux.py b/scapy/arch/linux.py
--- a/scapy/arch/linux.py
+++ b/scapy/arch/linux.py
@@ -494,7 +494,7 @@ def close(self):
         try:
             if self.promisc and self.ins:
                 set_promisc(self.ins, self.iface, 0)
-        except AttributeError:
+        except (AttributeError, OSError):
             pass
         SuperSocket.close(self)
 


Test patch:
Repository: secdev/scapy

Issue:
can_isotp kernel module changed ioctl
Hi, 
I just found out, that a change in Hartkopps Kernel module, which I need for NativeISOTPSockets, broke the `get_last_packet_timestamp` function.

The following change removed the support of ioctl for the kernel module, on recent Kernels:
https://github.com/hartkopp/can-isotp/commit/ff85005831d472e2e2a3b444abad58c915193ca7

Do you know, how this can be fixed?


Discussion:
At least, I assume that this is the problem, why the unit tests are failing. 
Is it possible to call this function `sock_gettstamp` from python?
I have to investigate the changes closer. This might not be the problem.
See #2482 
To fix that you probably just need to split the try/catch in two. Something like
```python
try:
    self.ins.setsockopt(SOL_PACKET, PACKET_AUXDATA, 1)
    self.auxdata_available = True
except OSError:
    pass

try:
    self.ins.setsockopt(
        socket.SOL_SOCKET,
        SO_TIMESTAMPNS,
        1
    )
    self.auxdata_available = True
except OSError:
    pass
if not self.auxdata_available:
    warning("...")
```

If you get the time, feel free to try it out and/or submit a PR.

Resolving patch:
diff --git a/scapy/contrib/isotp.py b/scapy/contrib/isotp.py
--- a/scapy/contrib/isotp.py
+++ b/scapy/contrib/isotp.py
@@ -1583,6 +1583,7 @@ class ISOTPNativeSocket(SuperSocket):
         can_isotp_fc_options_fmt = "@3B"
         can_isotp_ll_options_fmt = "@3B"
         sockaddr_can_fmt = "@H3I"
+        auxdata_available = True
 
         def __build_can_isotp_options(
                 self,


Test patch:
Repository: secdev/scapy

Issue:
plain_str not consistent between Py2 and Py3
**Python 2 (expected result)**
```python
>>> plain_str(b'\x3e\xb4\xef\x2c\x11')
'>\xb4\xef,\x11'
```

**Python 3 (unexpected result)**
```python
>>> plain_str(b'\x3e\xb4\xef\x2c\x11')                                                                                                                                             
'>,\x11'
```

**Cause** is `errors="ignore"`
```python
def plain_str(x):                          
    """Convert basic byte objects to str"""
    if isinstance(x, bytes):               
        return x.decode(errors="ignore")   
    return str(x)       
```

It just ignores values that are not in a valid range for the codec.

**Possible fix**
```python
def plain_str(x):                          
    """Convert basic byte objects to str"""
    if isinstance(x, bytes):               
        return x.decode(errors="backslashreplace")   
    return str(x)       
```        
But this breaks compatibility for Python 3.4




Discussion:

Resolving patch:
diff --git a/scapy/compat.py b/scapy/compat.py
--- a/scapy/compat.py
+++ b/scapy/compat.py
@@ -59,11 +59,19 @@ def bytes_encode(x):
             return x.encode()
         return bytes(x)
 
-    def plain_str(x):
-        """Convert basic byte objects to str"""
-        if isinstance(x, bytes):
-            return x.decode(errors="ignore")
-        return str(x)
+    if six.PY34:
+        def plain_str(x):
+            """Convert basic byte objects to str"""
+            if isinstance(x, bytes):
+                return x.decode(errors="ignore")
+            return str(x)
+    else:
+        # Python 3.5+
+        def plain_str(x):
+            """Convert basic byte objects to str"""
+            if isinstance(x, bytes):
+                return x.decode(errors="backslashreplace")
+            return str(x)
 
     def chb(x):
         """Same than chr() but encode as bytes."""


Test patch:
Repository: secdev/scapy

Issue:
Sessions can crash Scapy
Loading a Python3 session on a Python2 Scapy, will crash it.

```
./run_scapy -3 -s crash.session
./run_scapy -2 -s crash.session
[..]
Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/home/guedou/Projects/Scapy/scapy-issues/scapy/__main__.py", line 15, in <module>
    interact()
  File "scapy/main.py", line 573, in interact
    init_session(session_name, mydict)
  File "scapy/main.py", line 420, in init_session
    "rb"))
ValueError: unsupported pickle protocol: 4
```



Discussion:
Well we could pin a pickle protocol version that is python2 & 3 compatible (protocol 2), but newer protocols are much more effective..
Displaying an message saying that the session cannot be loaded is a good compromise.

Resolving patch:
diff --git a/scapy/main.py b/scapy/main.py
--- a/scapy/main.py
+++ b/scapy/main.py
@@ -418,6 +418,9 @@ def init_session(session_name,  # type: Optional[Union[str, None]]
                 except IOError:
                     SESSION = six.moves.cPickle.load(open(session_name, "rb"))
                 log_loading.info("Using session [%s]" % session_name)
+            except ValueError:
+                msg = "Error opening Python3 pickled session on Python2 [%s]"
+                log_loading.error(msg % session_name)
             except EOFError:
                 log_loading.error("Error opening session [%s]" % session_name)
             except AttributeError:


Test patch:
Repository: secdev/scapy

Issue:
Use nextproto property instead of nextprotocol
This is just a checklist to guide you. You can remove it safely.

**Checklist:**

-   [x ] If you are new to Scapy: I have checked <https://github.com/secdev/scapy/blob/master/CONTRIBUTING.md> (esp. section submitting-pull-requests)
-   [ ] I squashed commits belonging together
-   [ ] I added unit tests or explained why they are not relevant
-   [ ] I executed the regression tests for Python2 and Python3 (using `tox` or, `cd test && ./run_tests_py2, cd test && ./run_tests_py3`)
-   [ ] If the PR is still not finished, please create a [Draft Pull Request](https://github.blog/2019-02-14-introducing-draft-pull-requests/)

> brief description what this PR will do, e.g. fixes broken dissection of XXX
Fix wrong property in `bind_layers` function of NSH protocol. In the NSH class, it defines `nextproto` for next protocol property. 

I changed from `nextprotocol` to `nextproto` in `bind_layers`  functions.

> if required - short explanation why you fixed something in a way that may look more complicated as it actually is

> if required - outline impacts on other parts of the library



Discussion:

Resolving patch:
diff --git a/scapy/contrib/nsh.py b/scapy/contrib/nsh.py
--- a/scapy/contrib/nsh.py
+++ b/scapy/contrib/nsh.py
@@ -85,11 +85,11 @@ def mysummary(self):
 
 
 bind_layers(Ether, NSH, {'type': 0x894F}, type=0x894F)
-bind_layers(VXLAN, NSH, {'flags': 0xC, 'nextprotocol': 4}, nextprotocol=4)
+bind_layers(VXLAN, NSH, {'flags': 0xC, 'nextproto': 4}, nextproto=4)
 bind_layers(GRE, NSH, {'proto': 0x894F}, proto=0x894F)
 
-bind_layers(NSH, IP, {'nextprotocol': 1}, nextprotocol=1)
-bind_layers(NSH, IPv6, {'nextprotocol': 2}, nextprotocol=2)
-bind_layers(NSH, Ether, {'nextprotocol': 3}, nextprotocol=3)
-bind_layers(NSH, NSH, {'nextprotocol': 4}, nextprotocol=4)
-bind_layers(NSH, MPLS, {'nextprotocol': 5}, nextprotocol=5)
+bind_layers(NSH, IP, nextproto=1)
+bind_layers(NSH, IPv6, nextproto=2)
+bind_layers(NSH, Ether, nextproto=3)
+bind_layers(NSH, NSH, nextproto=4)
+bind_layers(NSH, MPLS, nextproto=5)


Test patch:
diff --git a/test/contrib/nsh.uts b/test/contrib/nsh.uts
--- a/test/contrib/nsh.uts
+++ b/test/contrib/nsh.uts
@@ -1,7 +1,7 @@
 + Basic Layer Tests
 
 = Build a NSH over NSH packet with SPI=42, and SI=1
-raw(NSH(spi=42, si=1)/NSH()) == b'\x0f\xc6\x01\x03\x00\x00*\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\xc6\x01\x03\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
+raw(NSH(spi=42, si=1)/NSH()) == b'\x0f\xc6\x01\x04\x00\x00*\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\xc6\x01\x03\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
 
 = Build a NSH with Fixed context headers
 raw(NSH(ttl=25, spi=55, si=34, context_header=b"\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\xff\xff\xff\xff")) == b'\x06F\x01\x03\x00\x007"\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\xff\xff\xff\xff'
Repository: secdev/scapy

Issue:
Typo  "paylod"
 find . -type f | xargs grep paylod
./scapy/packet.py:        """Used to iter through the paylods of a Packet.



Discussion:

Resolving patch:
diff --git a/scapy/packet.py b/scapy/packet.py
--- a/scapy/packet.py
+++ b/scapy/packet.py
@@ -1027,7 +1027,7 @@ def is_valid_gen_tuple(x):
         return length
 
     def iterpayloads(self):
-        """Used to iter through the paylods of a Packet.
+        """Used to iter through the payloads of a Packet.
         Useful for DNS or 802.11 for instance.
         """
         yield self


Test patch:
Repository: secdev/scapy

Issue:
Scapy should stop parsing SSID values once it found one
As a follow up to https://github.com/secdev/scapy/issues/2683,
scapy parses the information element tags one by one, and updates the SSID every time it finds an SSID element.
But: The SSID element is always the first and should be only one instance of it per frame. So it doesn't make sense to update the SSID once it was already set.
The bug described in https://github.com/secdev/scapy/issues/2683, an incorrect parsing of an information element, resulting in a wrong SSID, could have been prevented (the SSID parsing issue, not the RSN parsing issue) if scapy wouldn't have overridden the SSID after it was set.


Discussion:

Resolving patch:
diff --git a/scapy/layers/dot11.py b/scapy/layers/dot11.py
--- a/scapy/layers/dot11.py
+++ b/scapy/layers/dot11.py
@@ -604,7 +604,10 @@ def network_stats(self):
         crypto = set()
         p = self.payload
         while isinstance(p, Dot11Elt):
-            if p.ID == 0:
+            # Avoid overriding already-set SSID values because it is not part
+            # of the standard and it protects from parsing bugs,
+            # see https://github.com/secdev/scapy/issues/2683
+            if p.ID == 0 and "ssid" not in summary:
                 summary["ssid"] = plain_str(p.info)
             elif p.ID == 3:
                 summary["channel"] = ord(p.info)


Test patch:
diff --git a/test/pcaps/bad_rsn_parsing_overrides_ssid.pcap b/test/pcaps/bad_rsn_parsing_overrides_ssid.pcap
new file mode 100644
Binary files /dev/null and b/test/pcaps/bad_rsn_parsing_overrides_ssid.pcap differ
diff --git a/test/regression.uts b/test/regression.uts
--- a/test/regression.uts
+++ b/test/regression.uts
@@ -1433,6 +1433,27 @@ raw(RandASN1Object())
 random.seed(1873503288)
 raw(RandASN1Object())
 
+= SSID is parsed properly even with the presence of RSN Information
+~ SSID RSN Information
+# A regression test for https://github.com/secdev/scapy/pull/2685.
+# https://github.com/secdev/scapy/issues/2683 describes a packet with
+# RSN Information that isn't parsed properly,
+# causing the SSID to be overridden.
+# This test checks the SSID is parsed properly.
+print(os.path.dirname(__file__))
+filename = os.path.abspath(
+    os.path.join(
+        os.path.dirname(__file__),
+        "..",
+        "test",
+        "pcaps",
+        "bad_rsn_parsing_overrides_ssid.pcap"
+    ))
+frame = rdpcap(filename)[0]
+beacon = frame.getlayer(5)
+ssid = beacon.network_stats()['ssid']
+assert ssid == "ROUTE-821E295"
+
 
 ############
 ############
Repository: secdev/scapy

Issue:
Python error during Scapy import if ipv6 is unchecked in the wifi card properties
#### Brief description

A Python error is displayed during a `from scapy.all import sniff`, if the ipv6 is deactivated in the wifi card properties, on Windows.

The same error seems to appear during any import from scapy.all.

#### Environment

-   Scapy version: `2.4.3rc3.dev621`
-   Python version: `3.8.3`
-   Operating System: `Windows 10`

#### How to reproduce

These two lines are enough to reproduce the error:

```
#! /usr/local/bin/python3.8

from scapy.all import sniff
```

#### Actual result

```
C:\Users\rgerg\Desktop>python scapy_error.py
Traceback (most recent call last):
  File "scapy_error.py", line 3, in <module>
    from scapy.all import sniff
  File "C:\Python38\lib\site-packages\scapy-git_archive.dev31bf7cea2b-py3.8.egg\scapy\all.py", line 16, in <module>
    from scapy.arch import *
  File "C:\Python38\lib\site-packages\scapy-git_archive.dev31bf7cea2b-py3.8.egg\scapy\arch\__init__.py", line 66, in <module>
    from scapy.arch.windows import *  # noqa F403
  File "C:\Python38\lib\site-packages\scapy-git_archive.dev31bf7cea2b-py3.8.egg\scapy\arch\windows\__init__.py", line 760, in <module>
    IFACES.load()
  File "C:\Python38\lib\site-packages\scapy-git_archive.dev31bf7cea2b-py3.8.egg\scapy\arch\windows\__init__.py", line 686, in load
    self.data[guid] = NetworkInterface(data)
  File "C:\Python38\lib\site-packages\scapy-git_archive.dev31bf7cea2b-py3.8.egg\scapy\arch\windows\__init__.py", line 332, in __init__
    self.update(data)
  File "C:\Python38\lib\site-packages\scapy-git_archive.dev31bf7cea2b-py3.8.egg\scapy\arch\windows\__init__.py", line 369, in update
    self.ip6 = next(x for x in self.ips if ":" in x)
StopIteration

C:\Users\rgerg\Desktop>
```

#### Expected result

As soon as the ipv6 box is checked in my wifi card settings, everything works fine, and i'm able to manipulate the packets.


Discussion:

Resolving patch:
diff --git a/scapy/arch/windows/__init__.py b/scapy/arch/windows/__init__.py
--- a/scapy/arch/windows/__init__.py
+++ b/scapy/arch/windows/__init__.py
@@ -367,7 +367,7 @@ def update(self, data):
                 pass
             try:
                 self.ip6 = next(x for x in self.ips if ":" in x)
-            except IndexError:
+            except StopIteration:
                 pass
             if not self.ip and not self.ip6:
                 self.invalid = True


Test patch:
Repository: secdev/scapy

Issue:
Remove duplicated names from Contrib modules
### Motivation

Creating a packet with fields having a duplicated name has always been very buggy (especially with fields like `ConditionalField`), and not recommended. Starting with 2.5.0, we will throw a `SyntaxWarning` when such a packet is created (https://github.com/secdev/scapy/pull/2857). All packets in `scapy/layers` have already been checked to this new enforcement, however there are still some packets in `scapy/contribs` that have duplicated field names. Ideally we would have fixed all of them by 2.5.0.

### Contrib files with duplicated fields in a `Packet`

This issue therefore lists the contrib files that suffer from duplicated fields.

- [x] `automotive.gm.gmlan` https://github.com/secdev/scapy/pull/2866
- [x] `bp`
- [x] `gtp`
- [x] `gtp_v2` https://github.com/secdev/scapy/pull/2877
- [x] `homeplugav`
- [x] `loraphy2wan`
- [x] `ltp` https://github.com/secdev/scapy/pull/2871
- [x] `opc_da`
- [x] `pfcp` https://github.com/secdev/scapy/pull/2899
- [x] `pnio_dcp`
- [x] `rpl_metrics`
- [x] `scada.iec104.__init__` https://github.com/secdev/scapy/pull/3387
- [x] `vqp`

## What to do?

1. ✏️  Pick a file you want to work on
2. ➡️ Open a Scapy shell, run `load_contrib("the_contrib_layer")`. For instance: `load_contrib("gtp")`
3. ⚠️ Scapy will throw SyntaxWarnings for each duplication.
4. ✏️ Fix them all one by one. Usually, the duplicated fields are reserved/spare bits, just use `res1`, `res2`... instead of `res`, `res`...
5. 🥇 Submit a PR ! 😄 

## Detection

```python
# While running this, ignore the hard errors (related to CAN for instance)
lays = [x['name'] for x in list_contrib(ret=True)]
warnings.simplefilter("always")
WARNINGS = {}
for i in lays:
    with warnings.catch_warnings(record=True) as w:
        load_contrib(i)
        if len(w):
            WARNINGS[i] = w[-1].category

for m,e in WARNINGS.items():
    if e == SyntaxWarning:
        print("- `%s`" % m)
```


Discussion:

Resolving patch:
diff --git a/scapy/contrib/rpl_metrics.py b/scapy/contrib/rpl_metrics.py
--- a/scapy/contrib/rpl_metrics.py
+++ b/scapy/contrib/rpl_metrics.py
@@ -123,8 +123,8 @@ class RPLDAGMCNSA(DAGMCObj):
                    # NSA Object Body Format
                    ByteField("res", 0),
                    BitField("flags", 0, 6),
-                   BitField("A", 0, 1),
-                   BitField("O", 0, 1)]
+                   BitField("A2", 0, 1),
+                   BitField("O2", 0, 1)]
 
 
 class RPLDAGMCNodeEnergy(DAGMCObj):


Test patch:
Repository: secdev/scapy

Issue:
TLS1.3 Extension for SignatureAlgorithmsCert is using wrong Type value
**Brief description**
"Type" is set to 0x31 (PostHandshakeAuth), should be using 0x32 (SignatureAlgorithmsCert).

https://github.com/secdev/scapy/blob/e79833e46ec33be0880447a1983e3840676302fe/scapy/layers/tls/extensions.py#L658-L667





Discussion:
This is, according to https://tools.ietf.org/html/rfc8446#section-4.2, very correct. Thanks for the report

Resolving patch:
diff --git a/scapy/layers/tls/extensions.py b/scapy/layers/tls/extensions.py
--- a/scapy/layers/tls/extensions.py
+++ b/scapy/layers/tls/extensions.py
@@ -657,7 +657,7 @@ class TLS_Ext_PostHandshakeAuth(TLS_Ext_Unknown):                   # RFC 8446
 
 class TLS_Ext_SignatureAlgorithmsCert(TLS_Ext_Unknown):    # RFC 8446
     name = "TLS Extension - Signature Algorithms Cert"
-    fields_desc = [ShortEnumField("type", 0x31, _tls_ext),
+    fields_desc = [ShortEnumField("type", 0x32, _tls_ext),
                    ShortField("len", None),
                    SigAndHashAlgsLenField("sig_algs_len", None,
                                           length_of="sig_algs"),


Test patch: