| 314 | |
| 315 | |
| 316 | class L3PacketSocket(L2Socket): |
| 317 | desc = "read/write packets at layer 3 using Linux PF_PACKET sockets" |
| 318 | |
| 319 | def __init__(self, |
| 320 | iface=None, # type: Optional[Union[str, NetworkInterface]] |
| 321 | type=ETH_P_ALL, # type: int |
| 322 | promisc=None, # type: Optional[Any] |
| 323 | filter=None, # type: Optional[Any] |
| 324 | nofilter=0, # type: int |
| 325 | monitor=None, # type: Optional[Any] |
| 326 | ): |
| 327 | self.send_socks = {} |
| 328 | super(L3PacketSocket, self).__init__( |
| 329 | iface=iface, |
| 330 | type=type, |
| 331 | promisc=promisc, |
| 332 | filter=filter, |
| 333 | nofilter=nofilter, |
| 334 | monitor=monitor, |
| 335 | ) |
| 336 | self.filter = filter |
| 337 | self.send_socks = {network_name(self.iface): self} |
| 338 | |
| 339 | def recv(self, x=MTU, **kwargs): |
| 340 | # type: (int, **Any) -> Optional[Packet] |
| 341 | pkt = SuperSocket.recv(self, x, **kwargs) |
| 342 | if pkt and self.lvl == 2: |
| 343 | pkt.payload.time = pkt.time |
| 344 | return pkt.payload |
| 345 | return pkt |
| 346 | |
| 347 | def send(self, x): |
| 348 | # type: (Packet) -> int |
| 349 | # Select the file descriptor to send the packet on. |
| 350 | iff = x.route()[0] |
| 351 | if iff is None: |
| 352 | iff = network_name(conf.iface) |
| 353 | type_x = type(x) |
| 354 | if iff not in self.send_socks: |
| 355 | self.send_socks[iff] = L3PacketSocket( |
| 356 | iface=iff, |
| 357 | type=conf.l3types.layer2num.get(type_x, self.type), |
| 358 | filter=self.filter, |
| 359 | promisc=self.promisc, |
| 360 | ) |
| 361 | sock = self.send_socks[iff] |
| 362 | fd = sock.outs |
| 363 | if sock.lvl == 3: |
| 364 | if not issubclass(sock.LL, type_x): |
| 365 | warning("Incompatible L3 types detected using %s instead of %s !", |
| 366 | type_x, sock.LL) |
| 367 | sock.LL = type_x |
| 368 | if sock.lvl == 2: |
| 369 | sx = bytes(sock.LL() / x) |
| 370 | else: |
| 371 | sx = bytes(x) |
| 372 | # Now send. |
| 373 | try: |