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

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

1075 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# Copyright (C) Philippe Biondi <phil@secdev.org> 

5# Copyright (C) Gabriel Potter 

6 

7""" 

8Automata with states, transitions and actions. 

9 

10TODO: 

11 - add documentation for ioevent, as_supersocket... 

12""" 

13 

14import copy 

15import itertools 

16import logging 

17import os 

18import random 

19import socket 

20import sys 

21import threading 

22import time 

23import traceback 

24import types 

25 

26import select 

27from collections import deque 

28 

29from scapy.config import conf 

30from scapy.consts import WINDOWS 

31from scapy.data import MTU 

32from scapy.error import log_runtime, warning 

33from scapy.interfaces import _GlobInterfaceType 

34from scapy.packet import Packet 

35from scapy.plist import PacketList 

36from scapy.supersocket import SuperSocket, StreamSocket 

37from scapy.utils import do_graph 

38 

39# Typing imports 

40from typing import ( 

41 Any, 

42 Callable, 

43 Deque, 

44 Dict, 

45 Generic, 

46 Iterable, 

47 Iterator, 

48 List, 

49 Optional, 

50 Set, 

51 Tuple, 

52 Type, 

53 TYPE_CHECKING, 

54 TypeVar, 

55 Union, 

56 cast, 

57) 

58from scapy.compat import DecoratorCallable, Self 

59 

60if WINDOWS or TYPE_CHECKING: 

61 import ctypes 

62 

63 

64# winsock.h 

65FD_READ = 0x00000001 

66 

67 

68def select_objects(inputs, remain): 

69 # type: (Iterable[Any], Union[float, int, None]) -> List[Any] 

70 """ 

71 Select objects. Same than: 

72 ``select.select(inputs, [], [], remain)`` 

73 

74 But also works on Windows, only on objects whose fileno() returns 

75 a Windows event. For simplicity, just use `ObjectPipe()` as a queue 

76 that you can select on whatever the platform is. 

77 

78 If you want an object to be always included in the output of 

79 select_objects (i.e. it's not selectable), just make fileno() 

80 return a strictly negative value. 

81 

82 Example: 

83 

84 >>> a, b = ObjectPipe("a"), ObjectPipe("b") 

85 >>> b.send("test") 

86 >>> select_objects([a, b], 1) 

87 [b] 

88 

89 :param inputs: objects to process 

90 :param remain: timeout. If 0, poll. If None, block. 

91 """ 

92 if not WINDOWS: 

93 return select.select(inputs, [], [], remain)[0] 

94 inputs = list(inputs) 

95 events = [] 

96 events_to_inputs = [] 

97 created = [] 

98 results = set() 

99 try: 

100 for i in inputs: 

101 fno = i.fileno() 

102 if fno < 0: 

103 # Special case: On Windows, we consider that an object that returns 

104 # a negative fileno (impossible), is always readable. This is used 

105 # in very few places but important (e.g. PcapReader), where we have 

106 # no valid fileno (and will stop on EOFError). 

107 results.add(i) 

108 remain = 0 

109 continue 

110 if getattr(i, "__selectable_force_select__", False): 

111 # Native socket.socket object. We would normally use select.select. 

112 evt = ctypes.windll.ws2_32.WSACreateEvent() 

113 created.append(evt) 

114 res = ctypes.windll.ws2_32.WSAEventSelect( 

115 ctypes.c_void_p(fno), 

116 evt, 

117 FD_READ 

118 ) 

119 if res == 0: 

120 # Was a socket 

121 event = evt 

122 else: 

123 # Fallback to normal event 

124 event = fno 

125 else: 

126 event = fno 

127 events.append(event) 

128 events_to_inputs.append(i) 

129 if events: 

130 # 0xFFFFFFFF = INFINITE 

131 remainms = int(remain * 1000 if remain is not None else 0xFFFFFFFF) 

132 if len(events) == 1: 

133 res = ctypes.windll.kernel32.WaitForSingleObject( 

134 ctypes.c_void_p(events[0]), 

135 remainms 

136 ) 

137 else: 

138 # Sadly, the only way to emulate select() is to first check 

139 # if any object is available using WaitForMultipleObjects 

140 # then poll the others. 

141 res = ctypes.windll.kernel32.WaitForMultipleObjects( 

142 len(events), 

143 (ctypes.c_void_p * len(events))( 

144 *events 

145 ), 

146 False, 

147 remainms 

148 ) 

149 # ctypes' default signed c_int restype returns WAIT_FAILED as -1. 

150 if res == -1 or res == 0xFFFFFFFF: 

151 raise ctypes.WinError() 

152 if res != 0x00000102: # Timeout 

153 results.add(events_to_inputs[res]) 

154 if len(events) > 1: 

155 # Now poll the others, if any 

156 for i, evt in enumerate(events): 

157 res = ctypes.windll.kernel32.WaitForSingleObject( 

158 ctypes.c_void_p(evt), 

159 0 # poll: don't wait 

160 ) 

161 if res == -1 or res == 0xFFFFFFFF: 

162 raise ctypes.WinError() 

163 if res == 0: 

164 results.add(events_to_inputs[i]) 

165 finally: 

166 # Cleanup created events, if any 

167 for evt in created: 

168 ctypes.windll.ws2_32.WSACloseEvent(evt) 

169 return list(results) 

170 

171 

172_T = TypeVar("_T") 

173 

174 

175class ObjectPipe(Generic[_T]): 

176 def __init__(self, name=None): 

177 # type: (Optional[str]) -> None 

178 self.name = name or "ObjectPipe" 

179 self.closed = False 

180 self.__rd, self.__wr = os.pipe() 

181 self.__queue = deque() # type: Deque[_T] 

182 if WINDOWS: 

183 self._wincreate() 

184 

185 if WINDOWS: 

186 def _wincreate(self): 

187 # type: () -> None 

188 self._fd = cast(int, ctypes.windll.kernel32.CreateEventA( 

189 None, True, False, 

190 ctypes.create_string_buffer(b"ObjectPipe %f" % random.random()) 

191 )) 

192 

193 def _winset(self): 

194 # type: () -> None 

195 if ctypes.windll.kernel32.SetEvent(ctypes.c_void_p(self._fd)) == 0: 

196 warning(ctypes.FormatError(ctypes.GetLastError())) 

197 

198 def _winreset(self): 

199 # type: () -> None 

200 if ctypes.windll.kernel32.ResetEvent(ctypes.c_void_p(self._fd)) == 0: 

201 warning(ctypes.FormatError(ctypes.GetLastError())) 

202 

203 def _winclose(self): 

204 # type: () -> None 

205 if ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(self._fd)) == 0: 

206 warning(ctypes.FormatError(ctypes.GetLastError())) 

207 

208 def fileno(self): 

209 # type: () -> int 

210 if WINDOWS: 

211 return self._fd 

212 return self.__rd 

213 

214 def send(self, obj): 

215 # type: (_T) -> int 

216 self.__queue.append(obj) 

217 if WINDOWS: 

218 self._winset() 

219 os.write(self.__wr, b"X") 

220 return 1 

221 

222 def write(self, obj): 

223 # type: (_T) -> None 

224 self.send(obj) 

225 

226 def empty(self): 

227 # type: () -> bool 

228 return not bool(self.__queue) 

229 

230 def flush(self): 

231 # type: () -> None 

232 pass 

233 

234 def recv(self, n=0, options=socket.MsgFlag(0)): 

235 # type: (Optional[int], socket.MsgFlag) -> Optional[_T] 

236 if self.closed: 

237 raise EOFError 

238 if options & socket.MSG_PEEK: 

239 if self.__queue: 

240 return self.__queue[0] 

241 return None 

242 os.read(self.__rd, 1) 

243 elt = self.__queue.popleft() 

244 if WINDOWS and not self.__queue: 

245 self._winreset() 

246 return elt 

247 

248 def read(self, n=0): 

249 # type: (Optional[int]) -> Optional[_T] 

250 return self.recv(n) 

251 

252 def clear(self): 

253 # type: () -> None 

254 if not self.closed: 

255 while not self.empty(): 

256 self.recv() 

257 

258 def close(self): 

259 # type: () -> None 

260 if not self.closed: 

261 self.closed = True 

262 os.close(self.__rd) 

263 os.close(self.__wr) 

264 if WINDOWS: 

265 try: 

266 self._winclose() 

267 except ImportError: 

268 # Python is shutting down 

269 pass 

270 

271 def __repr__(self): 

272 # type: () -> str 

273 return "<%s at %s>" % (self.name, id(self)) 

274 

275 def __del__(self): 

276 # type: () -> None 

277 self.close() 

278 

279 @staticmethod 

280 def select(sockets, remain=conf.recv_poll_rate): 

281 # type: (List[SuperSocket], Optional[float]) -> List[SuperSocket] 

282 # Only handle ObjectPipes 

283 results = [] 

284 for s in sockets: 

285 if s.closed: # allow read to trigger EOF 

286 results.append(s) 

287 if results: 

288 return results 

289 return select_objects(sockets, remain) 

290 

291 

292class Message: 

293 type = None # type: str 

294 pkt = None # type: Packet 

295 result = None # type: str 

296 state = None # type: Message 

297 exc_info = None # type: Union[Tuple[None, None, None], Tuple[BaseException, Exception, types.TracebackType]] # noqa: E501 

298 

299 def __init__(self, **args): 

300 # type: (Any) -> None 

301 self.__dict__.update(args) 

302 

303 def __repr__(self): 

304 # type: () -> str 

305 return "<Message %s>" % " ".join( 

306 "%s=%r" % (k, v) 

307 for k, v in self.__dict__.items() 

308 if not k.startswith("_") 

309 ) 

310 

311 

312class Timer(): 

313 def __init__(self, time, prio=0, autoreload=False): 

314 # type: (Union[int, float], int, bool) -> None 

315 self._timeout = float(time) # type: float 

316 self._time = 0 # type: float 

317 self._just_expired = True 

318 self._expired = True 

319 self._prio = prio 

320 self._func = _StateWrapper() 

321 self._autoreload = autoreload 

322 

323 def get(self): 

324 # type: () -> float 

325 return self._timeout 

326 

327 def set(self, val): 

328 # type: (float) -> None 

329 self._timeout = val 

330 

331 def _reset(self): 

332 # type: () -> None 

333 self._time = self._timeout 

334 self._expired = False 

335 self._just_expired = False 

336 

337 def _reset_just_expired(self): 

338 # type: () -> None 

339 self._just_expired = False 

340 

341 def _running(self): 

342 # type: () -> bool 

343 return self._time > 0 

344 

345 def _remaining(self): 

346 # type: () -> float 

347 return max(self._time, 0) 

348 

349 def _decrement(self, time): 

350 # type: (float) -> None 

351 self._time -= time 

352 if self._time <= 0: 

353 if not self._expired: 

354 self._just_expired = True 

355 if self._autoreload: 

356 # take overshoot into account 

357 self._time = self._timeout + self._time 

358 else: 

359 self._expired = True 

360 self._time = 0 

361 

362 def __lt__(self, obj): 

363 # type: (Timer) -> bool 

364 return ((self._time < obj._time) if self._time != obj._time 

365 else (self._prio < obj._prio)) 

366 

367 def __gt__(self, obj): 

368 # type: (Timer) -> bool 

369 return ((self._time > obj._time) if self._time != obj._time 

370 else (self._prio > obj._prio)) 

371 

372 def __eq__(self, obj): 

373 # type: (Any) -> bool 

374 if not isinstance(obj, Timer): 

375 raise NotImplementedError() 

376 return (self._time == obj._time) and (self._prio == obj._prio) 

377 

378 def __repr__(self): 

379 # type: () -> str 

380 return "<Timer %f(%f)>" % (self._time, self._timeout) 

381 

382 

383class _TimerList(): 

384 def __init__(self, other: Optional[Self] = None) -> None: 

385 self.timers = [] # type: list[Timer] 

386 if other is not None: 

387 self.timers.extend([copy.copy(t) for t in other.timers]) 

388 

389 def add_timer(self, timer): 

390 # type: (Timer) -> None 

391 self.timers.append(timer) 

392 

393 def reset(self): 

394 # type: () -> None 

395 for t in self.timers: 

396 t._reset() 

397 

398 def decrement(self, time): 

399 # type: (float) -> None 

400 for t in self.timers: 

401 t._decrement(time) 

402 

403 def expired(self): 

404 # type: () -> list[Timer] 

405 lst = [t for t in self.timers if t._just_expired] 

406 lst.sort(key=lambda x: x._prio, reverse=True) 

407 for t in lst: 

408 t._reset_just_expired() 

409 return lst 

410 

411 def until_next(self): 

412 # type: () -> Optional[float] 

413 try: 

414 return min([t._remaining() for t in self.timers if t._running()]) 

415 except ValueError: 

416 return None # None means blocking 

417 

418 def count(self): 

419 # type: () -> int 

420 return len(self.timers) 

421 

422 def __iter__(self): 

423 # type: () -> Iterator[Timer] 

424 return self.timers.__iter__() 

425 

426 def __repr__(self): 

427 # type: () -> str 

428 return self.timers.__repr__() 

429 

430 

431class _instance_state: 

432 def __init__(self, instance): 

433 # type: (Any) -> None 

434 self.__self__ = instance.__self__ 

435 self.__func__ = instance.__func__ 

436 self.__self__.__class__ = instance.__self__.__class__ 

437 

438 def __getattr__(self, attr): 

439 # type: (str) -> Any 

440 return getattr(self.__func__, attr) 

441 

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

443 # type: (Any, Any) -> Any 

444 return self.__func__(self.__self__, *args, **kargs) 

445 

446 def breaks(self): 

447 # type: () -> Any 

448 return self.__self__.add_breakpoints(self.__func__) 

449 

450 def intercepts(self): 

451 # type: () -> Any 

452 return self.__self__.add_interception_points(self.__func__) 

453 

454 def unbreaks(self): 

455 # type: () -> Any 

456 return self.__self__.remove_breakpoints(self.__func__) 

457 

458 def unintercepts(self): 

459 # type: () -> Any 

460 return self.__self__.remove_interception_points(self.__func__) 

461 

462 

463############## 

464# Automata # 

465############## 

466 

467class _StateWrapper: 

468 __name__ = None # type: str 

469 atmt_type = None # type: str 

470 atmt_state = None # type: str 

471 atmt_initial = None # type: int 

472 atmt_final = None # type: int 

473 atmt_stop = None # type: int 

474 atmt_error = None # type: int 

475 atmt_origfunc = None # type: _StateWrapper 

476 atmt_prio = None # type: int 

477 atmt_as_supersocket = None # type: Optional[str] 

478 atmt_condname = None # type: str 

479 atmt_ioname = None # type: str 

480 atmt_timeout = None # type: Timer 

481 atmt_cond = None # type: Dict[str, int] 

482 __code__ = None # type: types.CodeType 

483 __call__ = None # type: Callable[..., ATMT.NewStateRequested] 

484 

485 

486class ATMT: 

487 STATE = "State" 

488 ACTION = "Action" 

489 CONDITION = "Condition" 

490 RECV = "Receive condition" 

491 TIMEOUT = "Timeout condition" 

492 EOF = "EOF condition" 

493 IOEVENT = "I/O event" 

494 

495 class NewStateRequested(Exception): 

496 def __init__(self, state_func, automaton, *args, **kargs): 

497 # type: (Any, ATMT, Any, Any) -> None 

498 self.func = state_func 

499 self.state = state_func.atmt_state 

500 self.initial = state_func.atmt_initial 

501 self.error = state_func.atmt_error 

502 self.stop = state_func.atmt_stop 

503 self.final = state_func.atmt_final 

504 Exception.__init__(self, "Request state [%s]" % self.state) 

505 self.automaton = automaton 

506 self.args = args 

507 self.kargs = kargs 

508 self.action_parameters() # init action parameters 

509 

510 def action_parameters(self, *args, **kargs): 

511 # type: (Any, Any) -> ATMT.NewStateRequested 

512 self.action_args = args 

513 self.action_kargs = kargs 

514 return self 

515 

516 def run(self): 

517 # type: () -> Any 

518 return self.func(self.automaton, *self.args, **self.kargs) 

519 

520 def __repr__(self): 

521 # type: () -> str 

522 return "NewStateRequested(%s)" % self.state 

523 

524 @staticmethod 

525 def state(initial=0, # type: int 

526 final=0, # type: int 

527 stop=0, # type: int 

528 error=0 # type: int 

529 ): 

530 # type: (...) -> Callable[[DecoratorCallable], DecoratorCallable] 

531 def deco(f, initial=initial, final=final): 

532 # type: (_StateWrapper, int, int) -> _StateWrapper 

533 f.atmt_type = ATMT.STATE 

534 f.atmt_state = f.__name__ 

535 f.atmt_initial = initial 

536 f.atmt_final = final 

537 f.atmt_stop = stop 

538 f.atmt_error = error 

539 

540 def _state_wrapper(self, *args, **kargs): 

541 # type: (ATMT, Any, Any) -> ATMT.NewStateRequested 

542 return ATMT.NewStateRequested(f, self, *args, **kargs) 

543 

544 state_wrapper = cast(_StateWrapper, _state_wrapper) 

545 state_wrapper.__name__ = "%s_wrapper" % f.__name__ 

546 state_wrapper.atmt_type = ATMT.STATE 

547 state_wrapper.atmt_state = f.__name__ 

548 state_wrapper.atmt_initial = initial 

549 state_wrapper.atmt_final = final 

550 state_wrapper.atmt_stop = stop 

551 state_wrapper.atmt_error = error 

552 state_wrapper.atmt_origfunc = f 

553 return state_wrapper 

554 return deco # type: ignore 

555 

556 @staticmethod 

557 def action(cond, prio=0): 

558 # type: (Any, int) -> Callable[[_StateWrapper, _StateWrapper], _StateWrapper] # noqa: E501 

559 def deco(f, cond=cond): 

560 # type: (_StateWrapper, _StateWrapper) -> _StateWrapper 

561 if not hasattr(f, "atmt_type"): 

562 f.atmt_cond = {} 

563 f.atmt_type = ATMT.ACTION 

564 f.atmt_cond[cond.atmt_condname] = prio 

565 return f 

566 return deco 

567 

568 @staticmethod 

569 def condition(state, prio=0): 

570 # type: (Any, int) -> Callable[[_StateWrapper, _StateWrapper], _StateWrapper] # noqa: E501 

571 def deco(f, state=state): 

572 # type: (_StateWrapper, _StateWrapper) -> Any 

573 f.atmt_type = ATMT.CONDITION 

574 f.atmt_state = state.atmt_state 

575 f.atmt_condname = f.__name__ 

576 f.atmt_prio = prio 

577 return f 

578 return deco 

579 

580 @staticmethod 

581 def receive_condition(state, prio=0): 

582 # type: (_StateWrapper, int) -> Callable[[_StateWrapper, _StateWrapper], _StateWrapper] # noqa: E501 

583 def deco(f, state=state): 

584 # type: (_StateWrapper, _StateWrapper) -> _StateWrapper 

585 f.atmt_type = ATMT.RECV 

586 f.atmt_state = state.atmt_state 

587 f.atmt_condname = f.__name__ 

588 f.atmt_prio = prio 

589 return f 

590 return deco 

591 

592 @staticmethod 

593 def ioevent(state, # type: _StateWrapper 

594 name, # type: str 

595 prio=0, # type: int 

596 as_supersocket=None # type: Optional[str] 

597 ): 

598 # type: (...) -> Callable[[_StateWrapper, _StateWrapper], _StateWrapper] # noqa: E501 

599 def deco(f, state=state): 

600 # type: (_StateWrapper, _StateWrapper) -> _StateWrapper 

601 f.atmt_type = ATMT.IOEVENT 

602 f.atmt_state = state.atmt_state 

603 f.atmt_condname = f.__name__ 

604 f.atmt_ioname = name 

605 f.atmt_prio = prio 

606 f.atmt_as_supersocket = as_supersocket 

607 return f 

608 return deco 

609 

610 @staticmethod 

611 def timeout(state, timeout): 

612 # type: (_StateWrapper, Union[int, float]) -> Callable[[_StateWrapper, _StateWrapper, Timer], _StateWrapper] # noqa: E501 

613 def deco(f, state=state, timeout=Timer(timeout)): 

614 # type: (_StateWrapper, _StateWrapper, Timer) -> _StateWrapper 

615 f.atmt_type = ATMT.TIMEOUT 

616 f.atmt_state = state.atmt_state 

617 f.atmt_timeout = timeout 

618 f.atmt_timeout._func = f 

619 f.atmt_condname = f.__name__ 

620 return f 

621 return deco 

622 

623 @staticmethod 

624 def timer(state, timeout, prio=0): 

625 # type: (_StateWrapper, Union[float, int], int) -> Callable[[_StateWrapper, _StateWrapper, Timer], _StateWrapper] # noqa: E501 

626 def deco(f, state=state, timeout=Timer(timeout, prio=prio, autoreload=True)): 

627 # type: (_StateWrapper, _StateWrapper, Timer) -> _StateWrapper 

628 f.atmt_type = ATMT.TIMEOUT 

629 f.atmt_state = state.atmt_state 

630 f.atmt_timeout = timeout 

631 f.atmt_timeout._func = f 

632 f.atmt_condname = f.__name__ 

633 return f 

634 return deco 

635 

636 @staticmethod 

637 def eof(state): 

638 # type: (_StateWrapper) -> Callable[[_StateWrapper, _StateWrapper], _StateWrapper] # noqa: E501 

639 def deco(f, state=state): 

640 # type: (_StateWrapper, _StateWrapper) -> _StateWrapper 

641 f.atmt_type = ATMT.EOF 

642 f.atmt_state = state.atmt_state 

643 f.atmt_condname = f.__name__ 

644 return f 

645 return deco 

646 

647 

648class _ATMT_Command: 

649 RUN = "RUN" 

650 NEXT = "NEXT" 

651 FREEZE = "FREEZE" 

652 STOP = "STOP" 

653 FORCESTOP = "FORCESTOP" 

654 END = "END" 

655 EXCEPTION = "EXCEPTION" 

656 SINGLESTEP = "SINGLESTEP" 

657 BREAKPOINT = "BREAKPOINT" 

658 INTERCEPT = "INTERCEPT" 

659 ACCEPT = "ACCEPT" 

660 REPLACE = "REPLACE" 

661 REJECT = "REJECT" 

662 

663 

664class _ATMT_supersocket(SuperSocket): 

665 def __init__(self, 

666 name, # type: str 

667 ioevent, # type: str 

668 automaton, # type: Type[Automaton] 

669 proto, # type: Callable[[bytes], Any] 

670 *args, # type: Any 

671 **kargs # type: Any 

672 ): 

673 # type: (...) -> None 

674 self.name = name 

675 self.ioevent = ioevent 

676 self.proto = proto 

677 # write, read 

678 self.spa, self.spb = ObjectPipe[Any]("spa"), \ 

679 ObjectPipe[Any]("spb") 

680 kargs["external_fd"] = {ioevent: (self.spa, self.spb)} 

681 kargs["is_atmt_socket"] = True 

682 kargs["atmt_socket"] = self.name 

683 self.atmt = automaton(*args, **kargs) 

684 self.atmt.runbg() 

685 

686 def send(self, s): 

687 # type: (Any) -> int 

688 return self.spa.send(s) 

689 

690 def fileno(self): 

691 # type: () -> int 

692 return self.spb.fileno() 

693 

694 # note: _ATMT_supersocket may return bytes in certain cases, which 

695 # is expected. We cheat on typing. 

696 def recv(self, n=MTU, **kwargs): # type: ignore 

697 # type: (int, **Any) -> Any 

698 r = self.spb.recv(n) 

699 if self.proto is not None and r is not None: 

700 r = self.proto(r, **kwargs) 

701 if self.atmt.atmt_session is not None: 

702 # Apply session if provided 

703 r = self.atmt.atmt_session.process(r) 

704 return r 

705 

706 def close(self): 

707 # type: () -> None 

708 if not self.closed: 

709 self.atmt.stop() 

710 self.atmt.destroy() 

711 self.spa.close() 

712 self.spb.close() 

713 self.closed = True 

714 

715 @staticmethod 

716 def select(sockets, remain=conf.recv_poll_rate): 

717 # type: (List[SuperSocket], Optional[float]) -> List[SuperSocket] 

718 return select_objects(sockets, remain) 

719 

720 

721class _ATMT_to_supersocket: 

722 def __init__(self, name, ioevent, automaton): 

723 # type: (str, str, Type[Automaton]) -> None 

724 self.name = name 

725 self.ioevent = ioevent 

726 self.automaton = automaton 

727 

728 def __call__(self, proto, *args, **kargs): 

729 # type: (Callable[[bytes], Any], Any, Any) -> _ATMT_supersocket 

730 return _ATMT_supersocket( 

731 self.name, self.ioevent, self.automaton, 

732 proto, *args, **kargs 

733 ) 

734 

735 

736class Automaton_metaclass(type): 

737 def __new__(cls, name, bases, dct): 

738 # type: (str, Tuple[Any], Dict[str, Any]) -> Type[Automaton] 

739 cls = super(Automaton_metaclass, cls).__new__( # type: ignore 

740 cls, name, bases, dct 

741 ) 

742 cls.states = {} 

743 cls.recv_conditions = {} # type: Dict[str, List[_StateWrapper]] 

744 cls.conditions = {} # type: Dict[str, List[_StateWrapper]] 

745 cls.ioevents = {} # type: Dict[str, List[_StateWrapper]] 

746 cls.timeout = {} # type: Dict[str, _TimerList] 

747 cls.eofs = {} # type: Dict[str, _StateWrapper] 

748 cls.actions = {} # type: Dict[str, List[_StateWrapper]] 

749 cls.initial_states = [] # type: List[_StateWrapper] 

750 cls.stop_state = None # type: Optional[_StateWrapper] 

751 cls.ionames = [] 

752 cls.iosupersockets = [] 

753 

754 members = {} 

755 classes = [cls] 

756 while classes: 

757 c = classes.pop(0) # order is important to avoid breaking method overloading # noqa: E501 

758 classes += list(c.__bases__) 

759 for k, v in c.__dict__.items(): # type: ignore 

760 if k not in members: 

761 members[k] = v 

762 

763 decorated = [v for v in members.values() 

764 if hasattr(v, "atmt_type")] 

765 

766 for m in decorated: 

767 if m.atmt_type == ATMT.STATE: 

768 s = m.atmt_state 

769 cls.states[s] = m 

770 cls.recv_conditions[s] = [] 

771 cls.ioevents[s] = [] 

772 cls.conditions[s] = [] 

773 cls.timeout[s] = _TimerList() 

774 if m.atmt_initial: 

775 cls.initial_states.append(m) 

776 if m.atmt_stop: 

777 if cls.stop_state is not None: 

778 raise ValueError("There can only be a single stop state !") 

779 cls.stop_state = m 

780 elif m.atmt_type in [ATMT.CONDITION, ATMT.RECV, ATMT.TIMEOUT, ATMT.IOEVENT, ATMT.EOF]: # noqa: E501 

781 cls.actions[m.atmt_condname] = [] 

782 

783 for m in decorated: 

784 if m.atmt_type == ATMT.CONDITION: 

785 cls.conditions[m.atmt_state].append(m) 

786 elif m.atmt_type == ATMT.RECV: 

787 cls.recv_conditions[m.atmt_state].append(m) 

788 elif m.atmt_type == ATMT.EOF: 

789 cls.eofs[m.atmt_state] = m 

790 elif m.atmt_type == ATMT.IOEVENT: 

791 cls.ioevents[m.atmt_state].append(m) 

792 cls.ionames.append(m.atmt_ioname) 

793 if m.atmt_as_supersocket is not None: 

794 cls.iosupersockets.append(m) 

795 elif m.atmt_type == ATMT.TIMEOUT: 

796 cls.timeout[m.atmt_state].add_timer(m.atmt_timeout) 

797 elif m.atmt_type == ATMT.ACTION: 

798 for co in m.atmt_cond: 

799 cls.actions[co].append(m) 

800 

801 for v in itertools.chain( 

802 cls.conditions.values(), 

803 cls.recv_conditions.values(), 

804 cls.ioevents.values() 

805 ): 

806 v.sort(key=lambda x: x.atmt_prio) 

807 for condname, actlst in cls.actions.items(): 

808 actlst.sort(key=lambda x: x.atmt_cond[condname]) 

809 

810 for ioev in cls.iosupersockets: 

811 setattr(cls, ioev.atmt_as_supersocket, 

812 _ATMT_to_supersocket( 

813 ioev.atmt_as_supersocket, 

814 ioev.atmt_ioname, 

815 cast(Type["Automaton"], cls))) 

816 

817 # Inject signature 

818 try: 

819 import inspect 

820 cls.__signature__ = inspect.signature(cls.parse_args) # type: ignore # noqa: E501 

821 except (ImportError, AttributeError): 

822 pass 

823 

824 return cast(Type["Automaton"], cls) 

825 

826 def build_graph(self): 

827 # type: () -> str 

828 s = 'digraph "%s" {\n' % self.__class__.__name__ 

829 

830 se = "" # Keep initial nodes at the beginning for better rendering 

831 for st in self.states.values(): 

832 if st.atmt_initial: 

833 se = ('\t"%s" [ style=filled, fillcolor=blue, shape=box, root=true];\n' % st.atmt_state) + se # noqa: E501 

834 elif st.atmt_final: 

835 se += '\t"%s" [ style=filled, fillcolor=green, shape=octagon ];\n' % st.atmt_state # noqa: E501 

836 elif st.atmt_error: 

837 se += '\t"%s" [ style=filled, fillcolor=red, shape=octagon ];\n' % st.atmt_state # noqa: E501 

838 elif st.atmt_stop: 

839 se += '\t"%s" [ style=filled, fillcolor=orange, shape=box, root=true ];\n' % st.atmt_state # noqa: E501 

840 s += se 

841 

842 for st in self.states.values(): 

843 names = list( 

844 st.atmt_origfunc.__code__.co_names + 

845 st.atmt_origfunc.__code__.co_consts 

846 ) 

847 while names: 

848 n = names.pop() 

849 if n in self.states: 

850 s += '\t"%s" -> "%s" [ color=green ];\n' % (st.atmt_state, n) 

851 elif n in self.__dict__: 

852 # function indirection 

853 if callable(self.__dict__[n]): 

854 names.extend(self.__dict__[n].__code__.co_names) 

855 names.extend(self.__dict__[n].__code__.co_consts) 

856 

857 for c, sty, k, v in ( 

858 [("purple", "solid", k, v) for k, v in self.conditions.items()] + 

859 [("red", "solid", k, v) for k, v in self.recv_conditions.items()] + 

860 [("orange", "solid", k, v) for k, v in self.ioevents.items()] + 

861 [("black", "dashed", k, [v]) for k, v in self.eofs.items()] 

862 ): 

863 for f in v: 

864 names = list(f.__code__.co_names + f.__code__.co_consts) 

865 while names: 

866 n = names.pop() 

867 if n in self.states: 

868 line = f.atmt_condname 

869 for x in self.actions[f.atmt_condname]: 

870 line += "\\l>[%s]" % x.__name__ 

871 s += '\t"%s" -> "%s" [label="%s", color=%s, style=%s];\n' % ( 

872 k, 

873 n, 

874 line, 

875 c, 

876 sty, 

877 ) 

878 elif n in self.__dict__: 

879 # function indirection 

880 if callable(self.__dict__[n]) and hasattr(self.__dict__[n], "__code__"): # noqa: E501 

881 names.extend(self.__dict__[n].__code__.co_names) 

882 names.extend(self.__dict__[n].__code__.co_consts) 

883 for k, timers in self.timeout.items(): 

884 for timer in timers: 

885 for n in (timer._func.__code__.co_names + 

886 timer._func.__code__.co_consts): 

887 if n in self.states: 

888 line = "%s/%.1fs" % (timer._func.atmt_condname, 

889 timer.get()) 

890 for x in self.actions[timer._func.atmt_condname]: 

891 line += "\\l>[%s]" % x.__name__ 

892 s += '\t"%s" -> "%s" [label="%s",color=blue];\n' % (k, n, line) # noqa: E501 

893 s += "}\n" 

894 return s 

895 

896 def graph(self, **kargs): 

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

898 s = self.build_graph() 

899 return do_graph(s, **kargs) 

900 

901 

902class Automaton(metaclass=Automaton_metaclass): 

903 states = {} # type: Dict[str, _StateWrapper] 

904 state = None # type: ATMT.NewStateRequested 

905 recv_conditions = {} # type: Dict[str, List[_StateWrapper]] 

906 conditions = {} # type: Dict[str, List[_StateWrapper]] 

907 eofs = {} # type: Dict[str, _StateWrapper] 

908 ioevents = {} # type: Dict[str, List[_StateWrapper]] 

909 timeout = {} # type: Dict[str, _TimerList] 

910 actions = {} # type: Dict[str, List[_StateWrapper]] 

911 initial_states = [] # type: List[_StateWrapper] 

912 stop_state = None # type: Optional[_StateWrapper] 

913 ionames = [] # type: List[str] 

914 iosupersockets = [] # type: List[SuperSocket] 

915 

916 # used for spawn() 

917 pkt_cls = conf.raw_layer 

918 socketcls = StreamSocket 

919 

920 # Internals 

921 def __init__(self, *args, **kargs): 

922 # type: (Any, Any) -> None 

923 external_fd = kargs.pop("external_fd", {}) 

924 if "sock" in kargs: 

925 # We use a bi-directional sock 

926 self.sock = kargs["sock"] 

927 else: 

928 # Separate sockets 

929 self.sock = None 

930 self.send_sock_class = kargs.pop("ll", conf.L3socket) 

931 self.recv_sock_class = kargs.pop("recvsock", conf.L2listen) 

932 self.listen_sock = None # type: Optional[SuperSocket] 

933 self.send_sock = None # type: Optional[SuperSocket] 

934 self.is_atmt_socket = kargs.pop("is_atmt_socket", False) 

935 self.atmt_socket = kargs.pop("atmt_socket", None) 

936 self.started = threading.Lock() 

937 self.threadid = None # type: Optional[int] 

938 self.breakpointed = None 

939 self.breakpoints = set() # type: Set[_StateWrapper] 

940 self.interception_points = set() # type: Set[_StateWrapper] 

941 self.intercepted_packet = None # type: Union[None, Packet] 

942 self.debug_level = 0 

943 self.init_args = args 

944 self.init_kargs = kargs 

945 self.io = type.__new__(type, "IOnamespace", (), {}) 

946 self.oi = type.__new__(type, "IOnamespace", (), {}) 

947 self.cmdin = ObjectPipe[Message]("cmdin") 

948 self.cmdout = ObjectPipe[Message]("cmdout") 

949 self.ioin = {} 

950 self.ioout = {} 

951 self.packets = PacketList() # type: PacketList 

952 self.atmt_session = kargs.pop("session", None) 

953 for n in self.__class__.ionames: 

954 extfd = external_fd.get(n) 

955 if not isinstance(extfd, tuple): 

956 extfd = (extfd, extfd) 

957 ioin, ioout = extfd 

958 if ioin is None: 

959 ioin = ObjectPipe("ioin") 

960 else: 

961 ioin = self._IO_fdwrapper(ioin, None) 

962 if ioout is None: 

963 ioout = ObjectPipe("ioout") 

964 else: 

965 ioout = self._IO_fdwrapper(None, ioout) 

966 

967 self.ioin[n] = ioin 

968 self.ioout[n] = ioout 

969 ioin.ioname = n 

970 ioout.ioname = n 

971 setattr(self.io, n, self._IO_mixer(ioout, ioin)) 

972 setattr(self.oi, n, self._IO_mixer(ioin, ioout)) 

973 

974 for stname in self.states: 

975 setattr(self, stname, 

976 _instance_state(getattr(self, stname))) 

977 

978 self.start() 

979 

980 def parse_args(self, debug=0, store=0, session=None, **kargs): 

981 # type: (int, int, Any, Any) -> None 

982 self.debug_level = debug 

983 if debug: 

984 conf.logLevel = logging.DEBUG 

985 if session: 

986 self.atmt_session = session 

987 self.socket_kargs = kargs 

988 self.store_packets = store 

989 

990 @classmethod 

991 def spawn(cls, 

992 port: int, 

993 iface: Optional[_GlobInterfaceType] = None, 

994 local_ip: Optional[str] = None, 

995 bg: bool = False, 

996 **kwargs: Any) -> Optional[socket.socket]: 

997 """ 

998 Spawn a TCP server that listens for connections and start the automaton 

999 for each new client. 

1000 

1001 :param port: the port to listen to 

1002 :param bg: background mode? (default: False) 

1003 

1004 Note that in background mode, you shall close the TCP server as such:: 

1005 

1006 srv = MyAutomaton.spawn(8080, bg=True) 

1007 srv.shutdown(socket.SHUT_RDWR) # important 

1008 srv.close() 

1009 """ 

1010 from scapy.arch import get_if_addr 

1011 # create server sock and bind it 

1012 ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

1013 if local_ip is None: 

1014 local_ip = get_if_addr(iface or conf.iface) 

1015 try: 

1016 ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

1017 except OSError: 

1018 pass 

1019 ssock.bind((local_ip, port)) 

1020 ssock.listen(5) 

1021 clients = [] 

1022 if kwargs.get("verb", True): 

1023 print(conf.color_theme.green( 

1024 "Server %s started listening on %s" % ( 

1025 cls.__name__, 

1026 (local_ip, port), 

1027 ) 

1028 )) 

1029 

1030 def _run() -> None: 

1031 # Wait for clients forever 

1032 try: 

1033 while True: 

1034 atmt_server = None 

1035 clientsocket, address = ssock.accept() 

1036 if kwargs.get("verb", True): 

1037 print(conf.color_theme.gold( 

1038 "\u2503 Connection received from %s" % repr(address) 

1039 )) 

1040 try: 

1041 # Start atmt class with socket 

1042 if cls.socketcls is not None: 

1043 sock = cls.socketcls(clientsocket, cls.pkt_cls) 

1044 else: 

1045 sock = clientsocket 

1046 atmt_server = cls( 

1047 sock=sock, 

1048 iface=iface, **kwargs 

1049 ) 

1050 except OSError: 

1051 if atmt_server is not None: 

1052 atmt_server.destroy() 

1053 if kwargs.get("verb", True): 

1054 print("X Connection aborted.") 

1055 if kwargs.get("debug", 0) > 0: 

1056 traceback.print_exc() 

1057 continue 

1058 clients.append((atmt_server, clientsocket)) 

1059 # start atmt 

1060 atmt_server.runbg() 

1061 # housekeeping 

1062 for atmt, clientsocket in clients[:]: 

1063 if not atmt.isrunning(): 

1064 atmt.destroy() 

1065 clients.remove((atmt, clientsocket)) 

1066 except KeyboardInterrupt: 

1067 print("X Exiting.") 

1068 ssock.shutdown(socket.SHUT_RDWR) 

1069 except OSError: 

1070 print("X Server closed.") 

1071 if kwargs.get("debug", 0) > 0: 

1072 traceback.print_exc() 

1073 finally: 

1074 for atmt, clientsocket in clients: 

1075 try: 

1076 atmt.forcestop(wait=False) 

1077 atmt.destroy() 

1078 except Exception: 

1079 pass 

1080 try: 

1081 clientsocket.shutdown(socket.SHUT_RDWR) 

1082 clientsocket.close() 

1083 except Exception: 

1084 pass 

1085 ssock.close() 

1086 if bg: 

1087 # Background 

1088 threading.Thread(target=_run).start() 

1089 return ssock 

1090 else: 

1091 # Non-background 

1092 _run() 

1093 return None 

1094 

1095 def master_filter(self, pkt): 

1096 # type: (Packet) -> bool 

1097 return True 

1098 

1099 def my_send(self, pkt, **kwargs): 

1100 # type: (Packet, **Any) -> None 

1101 if not self.send_sock: 

1102 raise ValueError("send_sock is None !") 

1103 self.send_sock.send(pkt, **kwargs) 

1104 

1105 def update_sock(self, sock): 

1106 # type: (SuperSocket) -> None 

1107 """ 

1108 Update the socket used by the automata. 

1109 Typically used in an eof event to reconnect. 

1110 """ 

1111 self.sock = sock 

1112 if self.listen_sock is not None: 

1113 self.listen_sock = self.sock 

1114 if self.send_sock: 

1115 self.send_sock = self.sock 

1116 

1117 def timer_by_name(self, name): 

1118 # type: (str) -> Optional[Timer] 

1119 for _, timers in self.timeout.items(): 

1120 for timer in timers: # type: Timer 

1121 if timer._func.atmt_condname == name: 

1122 return timer 

1123 return None 

1124 

1125 # Utility classes and exceptions 

1126 class _IO_fdwrapper: 

1127 def __init__(self, 

1128 rd, # type: Union[int, ObjectPipe[bytes], None] 

1129 wr # type: Union[int, ObjectPipe[bytes], None] 

1130 ): 

1131 # type: (...) -> None 

1132 self.rd = rd 

1133 self.wr = wr 

1134 if isinstance(self.rd, socket.socket): 

1135 self.__selectable_force_select__ = True 

1136 

1137 def fileno(self): 

1138 # type: () -> int 

1139 if isinstance(self.rd, int): 

1140 return self.rd 

1141 elif self.rd: 

1142 return self.rd.fileno() 

1143 return 0 

1144 

1145 def read(self, n=65535): 

1146 # type: (int) -> Optional[bytes] 

1147 if isinstance(self.rd, int): 

1148 return os.read(self.rd, n) 

1149 elif self.rd: 

1150 return self.rd.recv(n) 

1151 return None 

1152 

1153 def write(self, msg): 

1154 # type: (bytes) -> int 

1155 if isinstance(self.wr, int): 

1156 return os.write(self.wr, msg) 

1157 elif self.wr: 

1158 return self.wr.send(msg) 

1159 return 0 

1160 

1161 def recv(self, n=65535): 

1162 # type: (int) -> Optional[bytes] 

1163 return self.read(n) 

1164 

1165 def send(self, msg): 

1166 # type: (bytes) -> int 

1167 return self.write(msg) 

1168 

1169 class _IO_mixer: 

1170 def __init__(self, 

1171 rd, # type: ObjectPipe[Any] 

1172 wr, # type: ObjectPipe[Any] 

1173 ): 

1174 # type: (...) -> None 

1175 self.rd = rd 

1176 self.wr = wr 

1177 

1178 def fileno(self): 

1179 # type: () -> Any 

1180 if isinstance(self.rd, ObjectPipe): 

1181 return self.rd.fileno() 

1182 return self.rd 

1183 

1184 def recv(self, n=None): 

1185 # type: (Optional[int]) -> Any 

1186 return self.rd.recv(n) 

1187 

1188 def read(self, n=None): 

1189 # type: (Optional[int]) -> Any 

1190 return self.recv(n) 

1191 

1192 def send(self, msg): 

1193 # type: (str) -> int 

1194 return self.wr.send(msg) 

1195 

1196 def write(self, msg): 

1197 # type: (str) -> int 

1198 return self.send(msg) 

1199 

1200 class AutomatonException(Exception): 

1201 def __init__(self, msg, state=None, result=None): 

1202 # type: (str, Optional[Message], Optional[str]) -> None 

1203 Exception.__init__(self, msg) 

1204 self.state = state 

1205 self.result = result 

1206 

1207 class AutomatonError(AutomatonException): 

1208 pass 

1209 

1210 class ErrorState(AutomatonException): 

1211 pass 

1212 

1213 class Stuck(AutomatonException): 

1214 pass 

1215 

1216 class AutomatonStopped(AutomatonException): 

1217 pass 

1218 

1219 class Breakpoint(AutomatonStopped): 

1220 pass 

1221 

1222 class Singlestep(AutomatonStopped): 

1223 pass 

1224 

1225 class InterceptionPoint(AutomatonStopped): 

1226 def __init__(self, msg, state=None, result=None, packet=None): 

1227 # type: (str, Optional[Message], Optional[str], Optional[Packet]) -> None 

1228 Automaton.AutomatonStopped.__init__(self, msg, state=state, result=result) 

1229 self.packet = packet 

1230 

1231 class CommandMessage(AutomatonException): 

1232 pass 

1233 

1234 # Services 

1235 def debug(self, lvl, msg): 

1236 # type: (int, str) -> None 

1237 if self.debug_level >= lvl: 

1238 log_runtime.debug(msg) 

1239 

1240 def isrunning(self): 

1241 # type: () -> bool 

1242 return self.started.locked() 

1243 

1244 def send(self, pkt, **kwargs): 

1245 # type: (Packet, **Any) -> None 

1246 if self.state.state in self.interception_points: 

1247 self.debug(3, "INTERCEPT: packet intercepted: %s" % pkt.summary()) 

1248 self.intercepted_packet = pkt 

1249 self.cmdout.send( 

1250 Message(type=_ATMT_Command.INTERCEPT, 

1251 state=self.state, pkt=pkt) 

1252 ) 

1253 cmd = self.cmdin.recv() 

1254 if not cmd: 

1255 self.debug(3, "CANCELLED") 

1256 return 

1257 self.intercepted_packet = None 

1258 if cmd.type == _ATMT_Command.REJECT: 

1259 self.debug(3, "INTERCEPT: packet rejected") 

1260 return 

1261 elif cmd.type == _ATMT_Command.REPLACE: 

1262 pkt = cmd.pkt 

1263 self.debug(3, "INTERCEPT: packet replaced by: %s" % pkt.summary()) # noqa: E501 

1264 elif cmd.type == _ATMT_Command.ACCEPT: 

1265 self.debug(3, "INTERCEPT: packet accepted") 

1266 else: 

1267 raise self.AutomatonError("INTERCEPT: unknown verdict: %r" % cmd.type) # noqa: E501 

1268 self.my_send(pkt, **kwargs) 

1269 self.debug(3, "SENT : %s" % pkt.summary()) 

1270 

1271 if self.store_packets: 

1272 self.packets.append(pkt.copy()) 

1273 

1274 def __iter__(self): 

1275 # type: () -> Automaton 

1276 return self 

1277 

1278 def __del__(self): 

1279 # type: () -> None 

1280 self.destroy(force=True) 

1281 

1282 def _run_condition(self, cond, *args, **kargs): 

1283 # type: (_StateWrapper, Any, Any) -> None 

1284 try: 

1285 self.debug(5, "Trying %s [%s]" % (cond.atmt_type, cond.atmt_condname)) # noqa: E501 

1286 cond(self, *args, **kargs) 

1287 except ATMT.NewStateRequested as state_req: 

1288 self.debug(2, "%s [%s] taken to state [%s]" % (cond.atmt_type, cond.atmt_condname, state_req.state)) # noqa: E501 

1289 if cond.atmt_type == ATMT.RECV: 

1290 if self.store_packets: 

1291 self.packets.append(args[0]) 

1292 for action in self.actions[cond.atmt_condname]: 

1293 self.debug(2, " + Running action [%s]" % action.__name__) 

1294 action(self, *state_req.action_args, **state_req.action_kargs) 

1295 raise 

1296 except Exception as e: 

1297 self.debug(2, "%s [%s] raised exception [%s]" % (cond.atmt_type, cond.atmt_condname, e)) # noqa: E501 

1298 raise 

1299 else: 

1300 self.debug(2, "%s [%s] not taken" % (cond.atmt_type, cond.atmt_condname)) # noqa: E501 

1301 

1302 def _do_start(self, *args, **kargs): 

1303 # type: (Any, Any) -> None 

1304 ready = threading.Event() 

1305 _t = threading.Thread( 

1306 target=self._do_control, 

1307 args=(ready,) + (args), 

1308 kwargs=kargs, 

1309 name="scapy.automaton _do_control" 

1310 ) 

1311 _t.daemon = True 

1312 _t.start() 

1313 ready.wait() 

1314 

1315 def _transfer_error(self, ex: Exception, exc_info: Any) -> None: 

1316 """ 

1317 This transfers the error to the main thread. 

1318 """ 

1319 self.debug(3, "Transferring exception from tid=%i:\n%s" % ( 

1320 self.threadid or 0, 

1321 "".join(traceback.format_exception(*exc_info)) 

1322 )) 

1323 m = Message( 

1324 type=_ATMT_Command.EXCEPTION, 

1325 exception=ex, 

1326 exc_info=exc_info, 

1327 ) 

1328 self.cmdout.send(m) 

1329 

1330 def _do_control(self, ready, *args, **kargs): 

1331 # type: (threading.Event, Any, Any) -> None 

1332 with self.started: 

1333 self.threadid = threading.current_thread().ident 

1334 if self.threadid is None: 

1335 self.threadid = 0 

1336 

1337 # Update default parameters 

1338 a = args + self.init_args[len(args):] 

1339 k = self.init_kargs.copy() 

1340 k.update(kargs) 

1341 

1342 # Initialize the automaton 

1343 self.packets = PacketList(name="session[%s]" % self.__class__.__name__) 

1344 try: 

1345 self.parse_args(*a, **k) 

1346 self.state = self.initial_states[0](self) 

1347 self.send_sock = self.sock or self.send_sock_class(**self.socket_kargs) 

1348 if self.recv_conditions: 

1349 # Only start a receiving socket if we have at least one 

1350 # recv_conditions 

1351 self.listen_sock = self.sock or self.recv_sock_class(**self.socket_kargs) # noqa: E501 

1352 # Timers are class attributes but their expiry state is per run: copy 

1353 # them so concurrently started instances do not consume each other's 

1354 # one-shot timeouts. (After parse_args() above, which can reconfigure 

1355 # them by name.) 

1356 self.timeout: Dict[str, _TimerList] = { 

1357 state: _TimerList(timerlist) 

1358 for state, timerlist in type(self).timeout.items() 

1359 } 

1360 except Exception as e: 

1361 self._transfer_error(e, sys.exc_info()) 

1362 ready.set() 

1363 return 

1364 

1365 # Main loop of the control thread 

1366 singlestep = True 

1367 iterator = self._do_iter() 

1368 self.debug(3, "Starting control thread [tid=%i]" % self.threadid) 

1369 ready.set() 

1370 try: 

1371 while True: 

1372 c = self.cmdin.recv() 

1373 if c is None: 

1374 return None 

1375 self.debug(5, "Received command %s" % c.type) 

1376 if c.type == _ATMT_Command.RUN: 

1377 singlestep = False 

1378 elif c.type == _ATMT_Command.NEXT: 

1379 singlestep = True 

1380 elif c.type == _ATMT_Command.FREEZE: 

1381 continue 

1382 elif c.type == _ATMT_Command.STOP: 

1383 if self.stop_state: 

1384 # There is a stop state 

1385 self.state = self.stop_state() 

1386 iterator = self._do_iter() 

1387 else: 

1388 # Act as FORCESTOP 

1389 break 

1390 elif c.type == _ATMT_Command.FORCESTOP: 

1391 break 

1392 while True: 

1393 state = next(iterator) 

1394 if isinstance(state, self.CommandMessage): 

1395 break 

1396 elif isinstance(state, self.Breakpoint): 

1397 c = Message(type=_ATMT_Command.BREAKPOINT, state=state) # noqa: E501 

1398 self.cmdout.send(c) 

1399 break 

1400 if singlestep: 

1401 c = Message(type=_ATMT_Command.SINGLESTEP, state=state) # noqa: E501 

1402 self.cmdout.send(c) 

1403 break 

1404 except (StopIteration, RuntimeError): 

1405 c = Message(type=_ATMT_Command.END, 

1406 result=self.final_state_output) 

1407 self.cmdout.send(c) 

1408 except Exception as e: 

1409 self._transfer_error(e, sys.exc_info()) 

1410 self.debug(3, "Stopping control thread (tid=%i)" % self.threadid) 

1411 self.threadid = None 

1412 if self.listen_sock: 

1413 self.listen_sock.close() 

1414 if self.send_sock: 

1415 self.send_sock.close() 

1416 

1417 def _do_iter(self): 

1418 # type: () -> Iterator[Union[Automaton.AutomatonException, Automaton.AutomatonStopped, ATMT.NewStateRequested, None]] # noqa: E501 

1419 while True: 

1420 try: 

1421 self.debug(1, "## state=[%s]" % self.state.state) 

1422 

1423 # Entering a new state. First, call new state function 

1424 if self.state.state in self.breakpoints and self.state.state != self.breakpointed: # noqa: E501 

1425 self.breakpointed = self.state.state 

1426 yield self.Breakpoint("breakpoint triggered on state %s" % self.state.state, # noqa: E501 

1427 state=self.state.state) 

1428 self.breakpointed = None 

1429 state_output = self.state.run() 

1430 if self.state.error: 

1431 raise self.ErrorState("Reached %s: [%r]" % (self.state.state, state_output), # noqa: E501 

1432 result=state_output, state=self.state.state) # noqa: E501 

1433 if self.state.final: 

1434 self.final_state_output = state_output 

1435 return 

1436 

1437 if state_output is None: 

1438 state_output = () 

1439 elif not isinstance(state_output, list): 

1440 state_output = state_output, 

1441 

1442 timers = self.timeout[self.state.state] 

1443 # If there are commandMessage, we should skip immediate 

1444 # conditions. 

1445 if not select_objects([self.cmdin], 0): 

1446 # Then check immediate conditions 

1447 for cond in self.conditions[self.state.state]: 

1448 self._run_condition(cond, *state_output) 

1449 

1450 # If still there and no conditions left, we are stuck! 

1451 if (len(self.recv_conditions[self.state.state]) == 0 and 

1452 len(self.ioevents[self.state.state]) == 0 and 

1453 timers.count() == 0): 

1454 raise self.Stuck("stuck in [%s]" % self.state.state, 

1455 state=self.state.state, 

1456 result=state_output) 

1457 

1458 # Finally listen and pay attention to timeouts 

1459 timers.reset() 

1460 time_previous = time.time() 

1461 

1462 fds = [self.cmdin] # type: List[Union[SuperSocket, ObjectPipe[Any]]] 

1463 select_func = select_objects 

1464 if self.listen_sock and self.recv_conditions[self.state.state]: 

1465 fds.append(self.listen_sock) 

1466 select_func = self.listen_sock.select # type: ignore 

1467 for ioev in self.ioevents[self.state.state]: 

1468 fds.append(self.ioin[ioev.atmt_ioname]) 

1469 while True: 

1470 time_current = time.time() 

1471 timers.decrement(time_current - time_previous) 

1472 time_previous = time_current 

1473 for timer in timers.expired(): 

1474 self._run_condition(timer._func, *state_output) 

1475 remain = timers.until_next() 

1476 

1477 self.debug(5, "Select on %r" % fds) 

1478 r = select_func(fds, remain) 

1479 self.debug(5, "Selected %r" % r) 

1480 for fd in r: 

1481 self.debug(5, "Looking at %r" % fd) 

1482 if fd == self.cmdin: 

1483 yield self.CommandMessage("Received command message") # noqa: E501 

1484 elif fd == self.listen_sock: 

1485 try: 

1486 pkt = self.listen_sock.recv() 

1487 except EOFError: 

1488 # Socket was closed abruptly. This will likely only 

1489 # ever happen when a client socket is passed to the 

1490 # automaton (not the case when the automaton is 

1491 # listening on a promiscuous conf.L2sniff) 

1492 self.listen_sock.close() 

1493 # False so that it is still reset by update_sock 

1494 self.listen_sock = False # type: ignore 

1495 fds.remove(fd) 

1496 if self.state.state in self.eofs: 

1497 # There is an eof state 

1498 eof = self.eofs[self.state.state] 

1499 self.debug(2, "Condition EOF [%s] taken" % eof.__name__) # noqa: E501 

1500 raise self.eofs[self.state.state](self) 

1501 else: 

1502 # There isn't. Therefore, it's a closing condition. 

1503 raise EOFError("Socket ended arbruptly.") 

1504 if self.atmt_session is not None: 

1505 # Apply session if provided 

1506 pkt = self.atmt_session.process(pkt) 

1507 if pkt is not None: 

1508 if self.master_filter(pkt): 

1509 self.debug(3, "RECVD: %s" % pkt.summary()) # noqa: E501 

1510 for rcvcond in self.recv_conditions[self.state.state]: # noqa: E501 

1511 self._run_condition(rcvcond, pkt, *state_output) # noqa: E501 

1512 else: 

1513 self.debug(4, "FILTR: %s" % pkt.summary()) # noqa: E501 

1514 else: 

1515 self.debug(3, "IOEVENT on %s" % fd.ioname) 

1516 for ioevt in self.ioevents[self.state.state]: 

1517 if ioevt.atmt_ioname == fd.ioname: 

1518 self._run_condition(ioevt, fd, *state_output) # noqa: E501 

1519 

1520 except ATMT.NewStateRequested as state_req: 

1521 self.debug(2, "switching from [%s] to [%s]" % (self.state.state, state_req.state)) # noqa: E501 

1522 self.state = state_req 

1523 yield state_req 

1524 

1525 def __repr__(self): 

1526 # type: () -> str 

1527 return "<Automaton %s [%s]>" % ( 

1528 self.__class__.__name__, 

1529 ["HALTED", "RUNNING"][self.isrunning()] 

1530 ) 

1531 

1532 # Public API 

1533 def add_interception_points(self, *ipts): 

1534 # type: (Any) -> None 

1535 for ipt in ipts: 

1536 if hasattr(ipt, "atmt_state"): 

1537 ipt = ipt.atmt_state 

1538 self.interception_points.add(ipt) 

1539 

1540 def remove_interception_points(self, *ipts): 

1541 # type: (Any) -> None 

1542 for ipt in ipts: 

1543 if hasattr(ipt, "atmt_state"): 

1544 ipt = ipt.atmt_state 

1545 self.interception_points.discard(ipt) 

1546 

1547 def add_breakpoints(self, *bps): 

1548 # type: (Any) -> None 

1549 for bp in bps: 

1550 if hasattr(bp, "atmt_state"): 

1551 bp = bp.atmt_state 

1552 self.breakpoints.add(bp) 

1553 

1554 def remove_breakpoints(self, *bps): 

1555 # type: (Any) -> None 

1556 for bp in bps: 

1557 if hasattr(bp, "atmt_state"): 

1558 bp = bp.atmt_state 

1559 self.breakpoints.discard(bp) 

1560 

1561 def start(self, *args, **kargs): 

1562 # type: (Any, Any) -> None 

1563 if self.isrunning(): 

1564 raise ValueError("Already started") 

1565 # Start the control thread 

1566 self._do_start(*args, **kargs) 

1567 

1568 def run(self, 

1569 resume=None, # type: Optional[Message] 

1570 wait=True # type: Optional[bool] 

1571 ): 

1572 # type: (...) -> Any 

1573 if resume is None: 

1574 resume = Message(type=_ATMT_Command.RUN) 

1575 self.cmdin.send(resume) 

1576 if wait: 

1577 try: 

1578 c = self.cmdout.recv() 

1579 if c is None: 

1580 return None 

1581 except KeyboardInterrupt: 

1582 self.cmdin.send(Message(type=_ATMT_Command.FREEZE)) 

1583 return None 

1584 if c.type == _ATMT_Command.END: 

1585 return c.result 

1586 elif c.type == _ATMT_Command.INTERCEPT: 

1587 raise self.InterceptionPoint("packet intercepted", state=c.state.state, packet=c.pkt) # noqa: E501 

1588 elif c.type == _ATMT_Command.SINGLESTEP: 

1589 raise self.Singlestep("singlestep state=[%s]" % c.state.state, state=c.state.state) # noqa: E501 

1590 elif c.type == _ATMT_Command.BREAKPOINT: 

1591 raise self.Breakpoint("breakpoint triggered on state [%s]" % c.state.state, state=c.state.state) # noqa: E501 

1592 elif c.type == _ATMT_Command.EXCEPTION: 

1593 # this code comes from the `six` module (`.reraise()`) 

1594 # to raise an exception with specified exc_info. 

1595 value = c.exc_info[0]() if c.exc_info[1] is None else c.exc_info[1] # type: ignore # noqa: E501 

1596 if value.__traceback__ is not c.exc_info[2]: 

1597 raise value.with_traceback(c.exc_info[2]) 

1598 raise value 

1599 return None 

1600 

1601 def runbg(self, resume=None, wait=False): 

1602 # type: (Optional[Message], Optional[bool]) -> None 

1603 self.run(resume, wait) 

1604 

1605 def __next__(self): 

1606 # type: () -> Any 

1607 return self.run(resume=Message(type=_ATMT_Command.NEXT)) 

1608 

1609 def _flush_inout(self): 

1610 # type: () -> None 

1611 # Flush command pipes 

1612 for cmd in [self.cmdin, self.cmdout]: 

1613 cmd.clear() 

1614 

1615 def destroy(self, force=False): 

1616 # type: (bool) -> None 

1617 """ 

1618 Destroys a stopped Automaton: this cleanups all opened file descriptors. 

1619 The automaton will not be able to be restarted. 

1620 

1621 Required on PyPy for instance where the garbage collector behaves differently. 

1622 """ 

1623 if not hasattr(self, "started"): 

1624 return # was never started. 

1625 if not force and self.isrunning(): 

1626 raise ValueError("Can't close running Automaton ! Call stop() beforehand") 

1627 # Close command pipes 

1628 self.cmdin.close() 

1629 self.cmdout.close() 

1630 self._flush_inout() 

1631 # Close opened ioins/ioouts 

1632 for i in itertools.chain(self.ioin.values(), self.ioout.values()): 

1633 if isinstance(i, ObjectPipe): 

1634 i.close() 

1635 

1636 def stop(self, wait=True): 

1637 # type: (bool) -> None 

1638 try: 

1639 self.cmdin.send(Message(type=_ATMT_Command.STOP)) 

1640 except OSError: 

1641 pass 

1642 if wait: 

1643 with self.started: 

1644 self._flush_inout() 

1645 

1646 def forcestop(self, wait=True): 

1647 # type: (bool) -> None 

1648 try: 

1649 self.cmdin.send(Message(type=_ATMT_Command.FORCESTOP)) 

1650 except OSError: 

1651 pass 

1652 if wait: 

1653 with self.started: 

1654 self._flush_inout() 

1655 

1656 def restart(self, *args, **kargs): 

1657 # type: (Any, Any) -> None 

1658 self.stop() 

1659 self.start(*args, **kargs) 

1660 

1661 def accept_packet(self, 

1662 pkt=None, # type: Optional[Packet] 

1663 wait=False # type: Optional[bool] 

1664 ): 

1665 # type: (...) -> Any 

1666 rsm = Message() 

1667 if pkt is None: 

1668 rsm.type = _ATMT_Command.ACCEPT 

1669 else: 

1670 rsm.type = _ATMT_Command.REPLACE 

1671 rsm.pkt = pkt 

1672 return self.run(resume=rsm, wait=wait) 

1673 

1674 def reject_packet(self, 

1675 wait=False # type: Optional[bool] 

1676 ): 

1677 # type: (...) -> Any 

1678 rsm = Message(type=_ATMT_Command.REJECT) 

1679 return self.run(resume=rsm, wait=wait)