Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/compat.py: 58%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

71 statements  

1# SPDX-License-Identifier: GPL-2.0-only 

2# This file is part of Scapy 

3# See https://scapy.net/ for more information 

4 

5""" 

6Compatibility module to various older versions of Python 

7""" 

8 

9import base64 

10import binascii 

11import enum 

12import ntpath 

13import pathlib 

14import struct 

15import sys 

16 

17from scapy.consts import WINDOWS 

18 

19from typing import ( 

20 Any, 

21 AnyStr, 

22 Callable, 

23 Optional, 

24 TypeVar, 

25 Union, 

26 TYPE_CHECKING, 

27) 

28 

29# Very important: will issue typing errors otherwise 

30__all__ = [ 

31 # typing 

32 'DecoratorCallable', 

33 'Self', 

34 'UserDict', 

35 # compat 

36 'base64_bytes', 

37 'bytes_base64', 

38 'bytes_encode', 

39 'bytes_hex', 

40 'chb', 

41 'hex_bytes', 

42 'isreserved', 

43 'plain_str', 

44 'raw', 

45 'StrEnum', 

46] 

47 

48# Typing compatibility 

49 

50# Note: 

51# supporting typing on multiple python versions is a nightmare. 

52# we provide a FakeType class to be able to use types added on 

53# later Python versions (since we run mypy on 3.14), on older 

54# ones. 

55 

56 

57# Import or create fake types 

58 

59def _FakeType(name, cls=object): 

60 # type: (str, Optional[type]) -> Any 

61 class _FT(object): 

62 def __init__(self, name): 

63 # type: (str) -> None 

64 self.name = name 

65 

66 # make the objects subscriptable indefinitely 

67 def __getitem__(self, item): # type: ignore 

68 return cls 

69 

70 def __call__(self, *args, **kargs): 

71 # type: (*Any, **Any) -> Any 

72 if isinstance(args[0], str): 

73 self.name = args[0] 

74 return self 

75 

76 def __repr__(self): 

77 # type: () -> str 

78 return "<Fake typing.%s>" % self.name 

79 return _FT(name) 

80 

81 

82# Python 3.9 Only 

83if sys.version_info >= (3, 9): 

84 from collections import UserDict 

85else: 

86 from collections import UserDict as _UserDict 

87 UserDict = _FakeType("_UserDict", _UserDict) 

88 

89 

90# Python 3.11 Only 

91if sys.version_info >= (3, 11): 

92 from typing import Self 

93else: 

94 Self = _FakeType("Self") 

95 

96 

97# Python 3.11 Only 

98if sys.version_info >= (3, 11): 

99 from enum import StrEnum 

100else: 

101 class StrEnum(str, enum.Enum): 

102 pass 

103 

104 

105########### 

106# Python3 # 

107########### 

108 

109# https://mypy.readthedocs.io/en/stable/generics.html#declaring-decorators 

110DecoratorCallable = TypeVar("DecoratorCallable", bound=Callable[..., Any]) 

111 

112 

113# This is ugly, but we don't want to move raw() out of compat.py 

114# and it makes it much clearer 

115if TYPE_CHECKING: 

116 from scapy.packet import Packet 

117 

118 

119def raw(x): 

120 # type: (Packet) -> bytes 

121 """ 

122 Builds a packet and returns its bytes representation. 

123 This function is and will always be cross-version compatible 

124 """ 

125 return bytes(x) 

126 

127 

128def bytes_encode(x): 

129 # type: (Any) -> bytes 

130 """Ensure that the given object is bytes. If the parameter is a 

131 packet, raw() should be preferred. 

132 

133 """ 

134 if isinstance(x, str): 

135 return x.encode() 

136 return bytes(x) 

137 

138 

139def plain_str(x): 

140 # type: (Any) -> str 

141 """Convert basic byte objects to str""" 

142 if isinstance(x, bytes): 

143 return x.decode(errors="backslashreplace") 

144 return str(x) 

145 

146 

147def chb(x): 

148 # type: (int) -> bytes 

149 """Same than chr() but encode as bytes.""" 

150 return struct.pack("!B", x) 

151 

152 

153def bytes_hex(x): 

154 # type: (AnyStr) -> bytes 

155 """Hexify a str or a bytes object""" 

156 return binascii.b2a_hex(bytes_encode(x)) 

157 

158 

159def hex_bytes(x): 

160 # type: (AnyStr) -> bytes 

161 """De-hexify a str or a byte object""" 

162 return binascii.a2b_hex(bytes_encode(x)) 

163 

164 

165def int_bytes(x, size): 

166 # type: (int, int) -> bytes 

167 """Convert an int to an arbitrary sized bytes string""" 

168 return x.to_bytes(size, byteorder='big') 

169 

170 

171def bytes_int(x): 

172 # type: (bytes) -> int 

173 """Convert an arbitrary sized bytes string to an int""" 

174 return int.from_bytes(x, "big") 

175 

176 

177def base64_bytes(x): 

178 # type: (AnyStr) -> bytes 

179 """Turn base64 into bytes""" 

180 return base64.decodebytes(bytes_encode(x)) 

181 

182 

183def bytes_base64(x): 

184 # type: (AnyStr) -> bytes 

185 """Turn bytes into base64""" 

186 return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'') 

187 

188 

189if not WINDOWS: 

190 def isreserved(path: Union[str, pathlib.PurePath]) -> bool: 

191 """Reserved names (e.g. NUL) only exist on Windows""" 

192 return False 

193elif sys.version_info >= (3, 13): 

194 def isreserved(path: Union[str, pathlib.PurePath]) -> bool: 

195 """Return True if path is a reserved name on Windows (e.g. NUL)""" 

196 return ntpath.isreserved(path) 

197else: 

198 # PurePath.is_reserved() is deprecated since Python 3.13 and was removed 

199 # in 3.15 

200 def isreserved(path: Union[str, pathlib.PurePath]) -> bool: 

201 """Return True if path is a reserved name on Windows (e.g. NUL)""" 

202 return pathlib.PureWindowsPath(path).is_reserved()