1+ import socket
2+ import threading
3+ from typing import Callable , Optional
4+
5+ from core .session_manager import SessionManager
6+ from interface .colors import Colors
7+
8+ BIND_HOST = '0.0.0.0'
9+
10+
11+ class Listener (threading .Thread ):
12+ def __init__ (
13+ self ,
14+ host : str ,
15+ port : int ,
16+ session_manager : SessionManager ,
17+ on_connect : Optional [Callable [[int , str , int ], None ]] = None ,
18+ ):
19+ super ().__init__ (daemon = True )
20+ self .host = host
21+ self .port = port
22+ self .session_manager = session_manager
23+ self .on_connect = on_connect
24+ self ._running = False
25+ self ._server_socket : Optional [socket .socket ] = None
26+
27+ def run (self ) -> None :
28+ self ._running = True
29+ self ._server_socket = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
30+ self ._server_socket .setsockopt (socket .SOL_SOCKET , socket .SO_REUSEADDR , 1 )
31+
32+ try :
33+ self ._server_socket .bind ((BIND_HOST , self .port ))
34+ self ._server_socket .listen (10 )
35+ print (
36+ f"\n { Colors .success (f'[*] Listener started — binding { BIND_HOST } :{ self .port } , payload LHOST: { self .host } ' )} "
37+ )
38+ print (Colors .dim (f" Waiting for incoming connections...\n " ))
39+
40+ while self ._running :
41+ try :
42+ self ._server_socket .settimeout (1.0 )
43+ conn , addr = self ._server_socket .accept ()
44+ session_id = self .session_manager .add_session (conn , addr )
45+ print (
46+ f"\n { Colors .bold (Colors .GREEN + '[+]' + Colors .ENDC )} "
47+ f"New connection from { Colors .info (addr [0 ])} :{ Colors .warn (str (addr [1 ]))} "
48+ f"— { Colors .bold ('Session ID:' )} { Colors .success (str (session_id ))} "
49+ )
50+ if self .on_connect :
51+ self .on_connect (session_id , addr [0 ], addr [1 ])
52+ except socket .timeout :
53+ continue
54+ except OSError :
55+ break
56+ except Exception as exc :
57+ print (Colors .error (f"[!] Listener error: { exc } " ))
58+ finally :
59+ if self ._server_socket :
60+ try :
61+ self ._server_socket .close ()
62+ except Exception :
63+ pass
64+
65+ def stop (self ) -> None :
66+ self ._running = False
67+ if self ._server_socket :
68+ try :
69+ self ._server_socket .close ()
70+ except Exception :
71+ pass
72+
73+ @property
74+ def is_running (self ) -> bool :
75+ return self ._running and self .is_alive ()
0 commit comments