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

Issue:
Accept bytearray in place of bytes
#### Brief description

Currently, scapy does not accept `bytearray`s for payload data, likely among other things:

    from scapy.all import *
    pkt = Ether() / bytearray(10)

results in

    AttributeError: 'bytearray' object has no attribute '__rdiv__'

Manually casting to `bytes` works fine, but IMO `bytes` and `bytearray` should be interchangeable, not to mention other objects can implement `__bytes__`, so perhaps revisiting the implementation of `Packet.__div__` to either accept `bytearray`s in addition to `bytes`, or to attempt to cast the argument to `bytes` and only call `__rdiv__` if that fails.  

#### Environment

-   Scapy version: `2.4.3`
-   Python version: `3.9.0`
-   Operating System: `Arch`

#### How to reproduce

    from scapy.all import *
    Ether() / bytearray(10)

#### Actual result

    AttributeError: 'bytearray' object has no attribute '__rdiv__'

#### Expected result

    <Ether  |<Raw  load='\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>



Discussion:

Resolving patch:
diff --git a/scapy/packet.py b/scapy/packet.py
--- a/scapy/packet.py
+++ b/scapy/packet.py
@@ -577,7 +577,7 @@ def __div__(self, other):
             cloneB = other.copy()
             cloneA.add_payload(cloneB)
             return cloneA
-        elif isinstance(other, (bytes, str)):
+        elif isinstance(other, (bytes, str, bytearray)):
             return self / conf.raw_layer(load=other)
         else:
             return other.__rdiv__(self)  # type: ignore
@@ -585,7 +585,7 @@ def __div__(self, other):
 
     def __rdiv__(self, other):
         # type: (Any) -> Packet
-        if isinstance(other, (bytes, str)):
+        if isinstance(other, (bytes, str, bytearray)):
             return conf.raw_layer(load=other) / self
         else:
             raise TypeError


Test patch:
diff --git a/test/regression.uts b/test/regression.uts
--- a/test/regression.uts
+++ b/test/regression.uts
@@ -995,6 +995,11 @@ a
 assert(a.copy().time == a.time)
 a=3
 
+= Bind string array as payload
+~ basic
+assert bytes(Raw("sca")/"py") == b"scapy"
+assert bytes(Raw("sca")/b"py") == b"scapy"
+assert bytes(Raw("sca")/bytearray(b"py")) == b"scapy"
 
 = Checking overloads
 ~ basic IP TCP Ether
Repository: secdev/scapy

Issue:
Outdated Automotive Documentation
Reminder for myself.

Outdated:
https://github.com/secdev/scapy/blob/1aa0d8a849f7b102d18a3f65986e272aec5f518a/doc/scapy/layers/automotive.rst#L75-L85

SOME/IP:
https://github.com/secdev/scapy/blob/1aa0d8a849f7b102d18a3f65986e272aec5f518a/doc/scapy/layers/automotive.rst#L1011-L1030
Mentioned by @WebLabInt via gitter:
```Hi, I m having a problem creating a basic SOME IP service discovery following the example provided https://scapy.readthedocs.io/en/latest/layers/automotive.html?highlight=some%20ip#creating-a-some-ip-sd-message. The SOME IP package is working perfectly, however, the SD packet is not formed correctly thus not recognized as a SD packet by Wireshark and the SOME IP version is not correct. I did a capture with Wireshark reporting those issues http://fuiing.com/share/SD%20prob.png . I will be great if you can support me on this issue, thank you for making Scapy open source, it's really a great tool, have a great day ```


Discussion:

Resolving patch:
diff --git a/doc/scapy/conf.py b/doc/scapy/conf.py
--- a/doc/scapy/conf.py
+++ b/doc/scapy/conf.py
@@ -97,6 +97,9 @@
 # If true, `todo` and `todoList` produce output, else they produce nothing.
 todo_include_todos = False
 
+# Enable codeauthor and sectionauthor directives
+show_authors = True
+
 
 # -- Options for HTML output ----------------------------------------------
 


Test patch:
Repository: secdev/scapy

Issue:
Threading related deprecations in Python 3.10
#### Brief description

Camelcase aliases related to threading module have been deprecated in Python 3.10

Ref : python/cpython#25174 

#### Environment

-   Scapy version: `scapy version and/or commit-hash`
-   Python version: 3.10
-   Operating System: 

#### How to reproduce

```
scapy/automaton.py
745:        _t.setDaemon(True)
751:            self.threadid = threading.currentThread().ident

scapy/sendrecv.py
177:                snd_thread.setDaemon(True)
1018:        self.thread.setDaemon(True)

scapy/pipetool.py
149:            _t.setDaemon(True)
```

#### Actual result

The deprecated methods should be changed to use correct APIs.

#### Expected result

setDaemon -> set daemon attribute directly
currentThread -> Use current_thread


Discussion:

Resolving patch:
diff --git a/scapy/automaton.py b/scapy/automaton.py
--- a/scapy/automaton.py
+++ b/scapy/automaton.py
@@ -742,13 +742,13 @@ def _do_start(self, *args, **kargs):
             kwargs=kargs,
             name="scapy.automaton _do_start"
         )
-        _t.setDaemon(True)
+        _t.daemon = True
         _t.start()
         ready.wait()
 
     def _do_control(self, ready, *args, **kargs):
         with self.started:
-            self.threadid = threading.currentThread().ident
+            self.threadid = threading.current_thread().ident
 
             # Update default parameters
             a = args + self.init_args[len(args):]
diff --git a/scapy/pipetool.py b/scapy/pipetool.py
--- a/scapy/pipetool.py
+++ b/scapy/pipetool.py
@@ -146,7 +146,7 @@ def run(self):
     def start(self):
         if self.thread_lock.acquire(0):
             _t = Thread(target=self.run, name="scapy.pipetool.PipeEngine")
-            _t.setDaemon(True)
+            _t.daemon = True
             _t.start()
             self.thread = _t
         else:
diff --git a/scapy/sendrecv.py b/scapy/sendrecv.py
--- a/scapy/sendrecv.py
+++ b/scapy/sendrecv.py
@@ -174,7 +174,7 @@ def __init__(self,
                 snd_thread = Thread(
                     target=self._sndrcv_snd
                 )
-                snd_thread.setDaemon(True)
+                snd_thread.daemon = True
 
                 # Start routine with callback
                 self._sndrcv_rcv(snd_thread.start)
@@ -1015,7 +1015,7 @@ def _setup_thread(self):
             kwargs=self.kwargs,
             name="AsyncSniffer"
         )
-        self.thread.setDaemon(True)
+        self.thread.daemon = True
 
     def _run(self,
              count=0,  # type: int


Test patch:
Repository: secdev/scapy

Issue:
[UTscapy] xunit output format is undocumented and broken
### Brief description

The code for 'xunit' output format is present in UTscapy but is not documented in '--help' output and is broken under py3.

### Scapy version

2.4.5

### Python version

3.9

### Operating system

Ubuntu 21.04

### Additional environment information

GNU/Linux, scapy installed via pip3.

### How to reproduce

python3 -m scapy.tools.UTscapy -c test.utsc -f xunit -o utscapy.xml -N
python3 -m scapy.tools.UTscapy -h

### Actual result

...
output += ' <testcase classname="%s"\n' % testset.name.encode("string_escape").replace('"', ' ')  # noqa: E501
LookupError: unknown encoding: string_escape

### Expected result

...
✓ All campaigns executed. Writing output...
UTscapy ended successfully


### Related resources

The string_escape encoder is absent in python 3 because the strings are always utf. Simply dropping the .encode() call fixes it. It would still be nice to get the supported format properly documented though.


Discussion:

Resolving patch:
diff --git a/scapy/tools/UTscapy.py b/scapy/tools/UTscapy.py
--- a/scapy/tools/UTscapy.py
+++ b/scapy/tools/UTscapy.py
@@ -676,8 +676,8 @@ def campaign_to_xUNIT(test_campaign):
     output = '<?xml version="1.0" encoding="UTF-8" ?>\n<testsuite>\n'
     for testset in test_campaign:
         for t in testset:
-            output += ' <testcase classname="%s"\n' % testset.name.encode("string_escape").replace('"', ' ')  # noqa: E501
-            output += '           name="%s"\n' % t.name.encode("string_escape").replace('"', ' ')  # noqa: E501
+            output += ' <testcase classname="%s"\n' % testset.name.replace('"', ' ')  # noqa: E501
+            output += '           name="%s"\n' % t.name.replace('"', ' ')  # noqa: E501
             output += '           duration="0">\n' % t
             if not t:
                 output += '<error><![CDATA[%(output)s]]></error>\n' % t
@@ -820,7 +820,7 @@ def campaign_to_LATEX(test_campaign):
 # USAGE #
 
 def usage():
-    print("""Usage: UTscapy [-m module] [-f {text|ansi|HTML|LaTeX|live}] [-o output_file]
+    print("""Usage: UTscapy [-m module] [-f {text|ansi|HTML|LaTeX|xUnit|live}] [-o output_file]
                [-t testfile] [-T testfile] [-k keywords [-k ...]] [-K keywords [-K ...]]
                [-l] [-b] [-d|-D] [-F] [-q[q]] [-i] [-P preexecute_python_code]
                [-c configfile]


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/scada/iec104/iec104_information_elements.py b/scapy/contrib/scada/iec104/iec104_information_elements.py
--- a/scapy/contrib/scada/iec104/iec104_information_elements.py
+++ b/scapy/contrib/scada/iec104/iec104_information_elements.py
@@ -219,7 +219,7 @@ class IEC104_IE_QDP(IEC104_IE_CommonQualityFlags):
         # blocked
         BitEnumField('ei', 0, 1, IEC104_IE_CommonQualityFlags.EI_FLAGS),
         # blocked
-        BitField('reserved', 0, 3)
+        BitField('reserved_qdp', 0, 3)
     ]
 
 
@@ -605,7 +605,7 @@ class IEC104_IE_CP56TIME2A(IEC104_IE_CommonQualityFlags):
 
     informantion_element_fields = [
         LEShortField('sec_milli', 0),
-        BitEnumField('iv', 0, 1, IEC104_IE_CommonQualityFlags.IV_FLAGS),
+        BitEnumField('iv_time', 0, 1, IEC104_IE_CommonQualityFlags.IV_FLAGS),
         BitEnumField('gen', 0, 1, GEN_FLAGS),
         # only valid in monitor direction ToDo: special treatment needed?
         BitField('minutes', 0, 6),


Test patch:
Repository: secdev/scapy

Issue:
L2TP post_build is broken
### Brief description

l2tp.py post_build is supposed to update the length. However, it only does this if current length is None, and the length field is initialized to 0, not None, resulting in the length never being updated. 

### Scapy version

2.4.5

### Python version

3.8

### Operating system

Ubuntu 20.04

### Additional environment information

_No response_

### How to reproduce

print( (L2TP(header=['control', 'length'], version=2) / 'blahblah').build() )


### Actual result

b'\xc0\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00blahblah'

### Expected result

b'\xc0\x02\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00blahblah'

### Related resources

_No response_


Discussion:

Resolving patch:
diff --git a/scapy/layers/l2tp.py b/scapy/layers/l2tp.py
--- a/scapy/layers/l2tp.py
+++ b/scapy/layers/l2tp.py
@@ -25,7 +25,7 @@ class L2TP(Packet):
                                   'res06', 'sequence', 'res08', 'res09', 'length', 'control']),  # noqa: E501
         BitEnumField("version", 2, 4, {2: 'L2TPv2'}),
 
-        ConditionalField(ShortField("len", 0),
+        ConditionalField(ShortField("len", None),
                          lambda pkt: pkt.hdr & 'control+length'),
         ShortField("tunnel_id", 0),
         ShortField("session_id", 0),


Test patch:
diff --git a/test/scapy/layers/l2tp.uts b/test/scapy/layers/l2tp.uts
--- a/test/scapy/layers/l2tp.uts
+++ b/test/scapy/layers/l2tp.uts
@@ -8,6 +8,9 @@
 s = raw(IP(src="127.0.0.1", dst="127.0.0.1")/UDP()/L2TP())
 s == b'E\x00\x00"\x00\x01\x00\x00@\x11|\xc8\x7f\x00\x00\x01\x7f\x00\x00\x01\x06\xa5\x06\xa5\x00\x0e\xf4\x83\x00\x02\x00\x00\x00\x00'
 
+= L2TP - build with computed length
+assert bytes(L2TP(hdr="control+length", tunnel_id=1, session_id=2)) == b'\xc0\x02\x00\x0c\x00\x01\x00\x02\x00\x00\x00\x00'
+
 = L2TP - dissection
 p = IP(s)
 L2TP in p and len(p[L2TP]) == 6 and p.tunnel_id == 0 and p.session_id == 0 and p[UDP].chksum == 0xf483
Repository: secdev/scapy

Issue:
sendpfast loop option does not support 0
### Brief description

Giving option loop=0 to sendpfast ignores the option, however the underlying tcpreplay tool sets infinite loop when given --loop 0. 

### Scapy version

2.4.5

### Python version

3.8.10

### Operating system

Linux 5.14.0

### Additional environment information

_No response_

### How to reproduce

Run sendpfast(packets, iface='someiface', loop=0)

### Actual result

Packet list sent once

### Expected result

Packet list sent in infinite loop

### Related resources

_No response_


Discussion:

Resolving patch:
diff --git a/scapy/sendrecv.py b/scapy/sendrecv.py
--- a/scapy/sendrecv.py
+++ b/scapy/sendrecv.py
@@ -489,7 +489,7 @@ def sendpfast(x,  # type: _PacketIterable
               pps=None,  # type: Optional[float]
               mbps=None,  # type: Optional[float]
               realtime=False,  # type: bool
-              loop=0,  # type: int
+              loop=None,  # type: Optional[int]
               file_cache=False,  # type: bool
               iface=None,  # type: Optional[_GlobInterfaceType]
               replay_args=None,  # type: Optional[List[str]]
@@ -501,7 +501,8 @@ def sendpfast(x,  # type: _PacketIterable
     :param pps:  packets per second
     :param mbps: MBits per second
     :param realtime: use packet's timestamp, bending time with real-time value
-    :param loop: number of times to process the packet list
+    :param loop: number of times to process the packet list. 0 implies
+        infinite loop
     :param file_cache: cache packets in RAM instead of reading from
         disk at each iteration
     :param iface: output interface
@@ -522,7 +523,7 @@ def sendpfast(x,  # type: _PacketIterable
     else:
         argv.append("--topspeed")
 
-    if loop:
+    if loop is not None:
         argv.append("--loop=%i" % loop)
     if file_cache:
         argv.append("--preload-pcap")


Test patch:
Repository: secdev/scapy

Issue:
Accept bytearray as a valid Packet() parameter ?
While experimenting with Scapy, a colleague discovered the following issue while passing a `bytearray`  to the `Ether` constructor.

```
>>> raw(Ether(bytearray(b"\x00" * 14)))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-92197f130b79> in <module>
----> 1 raw(Ether(bytearray(b"\x00" * 14)))

~/Projects/Scapy/scapy.git/scapy/compat.py in raw(x)
    292         This function is and will always be cross-version compatible
    293         """
--> 294         return bytes(x)
    295 
    296     def bytes_encode(x):

TypeError: __bytes__ returned non-bytes (type bytearray)
```

Here is the expected result:
```
>>> raw(Ether(bytearray(b"\x00" * 14)))
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
```

Shall we modify Scapy to accept such type as a valid input for the constructor ?


Discussion:
I think a more general issue is that you cannot cast an Ether packet created from a bytearray as bytes:

1-line example:

`` import scapy.all; bytes(scapy.all.Ether(bytearray(bytes(scapy.all.Ether()))))``

returns

> WARNING: Mac address to reach destination not found. Using broadcast.
> \---------------------------------------------------------------------------
> TypeError                                 Traceback (most recent call last)
> ~/test/ipython.py in <module>
> \----> 1 import scapy.all; bytes(scapy.all.Ether(bytearray(bytes(scapy.all.Ether()))))
> 
> TypeError: __bytes__ returned non-bytes (type bytearray)

Is this really worth it? You could just convert it back to bytes:
```python
Ether(bytes(bytearray(b"\0"*14)))
```

Resolving patch:
diff --git a/scapy/packet.py b/scapy/packet.py
--- a/scapy/packet.py
+++ b/scapy/packet.py
@@ -128,7 +128,7 @@ def lower_bonds(self):
             print("%-20s  %s" % (lower.__name__, ", ".join("%-12s" % ("%s=%r" % i) for i in six.iteritems(fval))))  # noqa: E501
 
     def __init__(self,
-                 _pkt=b"",  # type: bytes
+                 _pkt=b"",  # type: Union[bytes, bytearray]
                  post_transform=None,  # type: Any
                  _internal=0,  # type: int
                  _underlayer=None,  # type: Optional[Packet]
@@ -151,6 +151,8 @@ def __init__(self,
         self.init_fields()
         self.underlayer = _underlayer
         self.parent = _parent
+        if isinstance(_pkt, bytearray):
+            _pkt = bytes(_pkt)
         self.original = _pkt
         self.explicit = 0
         self.raw_packet_cache = None  # type: Optional[bytes]


Test patch:
Repository: secdev/scapy

Issue:
lsc description lost
I just noticed that some commands lost their description in the `lsc()` output such as `corrupt_bits` and `corrupt_ bytes`:
```
>>> lsc()
IPID_count          : Identify IP id values classes in a list of packets
arpcachepoison      : Poison target's cache with (your MAC,victim's IP) couple
arping              : Send ARP who-has requests to determine which hosts are up
arpleak             : Exploit ARP leak flaws, like NetBSD-SA2017-002.
bind_layers         : Bind 2 layers on some specific fields' values.
bridge_and_sniff    : Forward traffic between interfaces if1 and if2, sniff and return
chexdump            : Build a per byte hexadecimal representation
computeNIGroupAddr  : Compute the NI group Address. Can take a FQDN as input parameter
corrupt_bits        : 
corrupt_bytes       : 
defrag              : defrag(plist) -> ([not fragmented], [defragmented],
```



Discussion:
This patch fixes the issue:
```
diff --git a/scapy/config.py b/scapy/config.py
index 544cbff..759dd2f 100755
--- a/scapy/config.py
+++ b/scapy/config.py
@@ -326,7 +326,9 @@ class CommandsList(List[Callable[..., Any]]):
         # type: () -> str
         s = []
         for li in sorted(self, key=lambda x: x.__name__):
-            doc = li.__doc__.split("\n")[0] if li.__doc__ else "--"
+            doc = li.__doc__ if li.__doc__ else "--"
+            doc = doc.lstrip('\n').lstrip()
+            doc = doc.split("\n")[0]
             s.append("%-20s: %s" % (li.__name__, doc))
         return "\n".join(s)
```

Resolving patch:
diff --git a/scapy/config.py b/scapy/config.py
--- a/scapy/config.py
+++ b/scapy/config.py
@@ -326,8 +326,9 @@ def __repr__(self):
         # type: () -> str
         s = []
         for li in sorted(self, key=lambda x: x.__name__):
-            doc = li.__doc__.split("\n")[0] if li.__doc__ else "--"
-            s.append("%-20s: %s" % (li.__name__, doc))
+            doc = li.__doc__ if li.__doc__ else "--"
+            doc = doc.lstrip().split('\n', 1)[0]
+            s.append("%-22s: %s" % (li.__name__, doc))
         return "\n".join(s)
 
     def register(self, cmd):


Test patch:
Repository: secdev/scapy

Issue:
defragmented IP Packet has wrong packet.time
### Brief description

When I use sniff() with session option to parse a pcapng file which has some fragmented IP packets, I found that the defragmented packets give the wrong time. It's the current time, not the arrival time in Wireshark.
I don't know if this is a bug, but it's annoying me. Maybe we could assign packet.time to defragmented_packet before returning defragmented_packet?

### Scapy version

2.4.5

### Python version

3.8

### Operating system

Windows 11 x64

### Additional environment information

_No response_

### How to reproduce

Use Wireshark to capture some packets including fragmented IP packets, and use the sniff function with the IPSession option to parse these packets, then print packets time.

### Actual result

_No response_

### Expected result

_No response_

### Related resources

_No response_


Discussion:
This would probably make sense, yes. The only question is: which time value would you then use? The one from the first packet? From the last one? From one in the middle? A mean or median value of all packets? I would chose either the first one or the last one.
> This would probably make sense, yes. The only question is: which time value would you then use? The one from the first packet? From the last one? From one in the middle? A mean or median value of all packets? I would chose either the first one or the last one.

Maybe the last packet time is a good choice, for the last packet time suggests that all fragments has been received and the full datagram has been fully reassembled.

Resolving patch:
diff --git a/scapy/sessions.py b/scapy/sessions.py
--- a/scapy/sessions.py
+++ b/scapy/sessions.py
@@ -140,6 +140,7 @@ def _ip_process_packet(self, packet):
                         defragmented_packet = defragmented_packet.__class__(
                             raw(defragmented_packet)
                         )
+                        defragmented_packet.time = packet.time
                         return defragmented_packet
                 finally:
                     del self.fragments[uniq]


Test patch: