termhub 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: termhub
3
+ Version: 0.1.0
4
+ Summary: Chat texte pour réseau local, dans le terminal. Zéro dépendance.
5
+ Author: nanaelie
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/nanaelie/termhub
8
+ Project-URL: Issues, https://github.com/nanaelie/termhub/issues
9
+ Keywords: chat,lan,terminal,wifi,formation,education
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Environment :: Console
14
+ Classifier: Topic :: Communications :: Chat
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # termhub
21
+
22
+ Chat texte en réseau local, dans le terminal. Python 3.8+, aucune dépendance.
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pipx install git+https://github.com/nanaelie/termhub.git # recommandé
28
+ # ou
29
+ pip install git+https://github.com/nanaelie/termhub.git
30
+ ```
31
+
32
+ Sans installer : `python termhub.py` (le fichier est autonome).
33
+ Mise à jour : `pipx upgrade termhub` — désinstallation : `pipx uninstall termhub`.
34
+
35
+ ## Utilisation
36
+
37
+ ```bash
38
+ termhub # cherche un salon ; s'il n'y en a pas, en démarre un
39
+ termhub start --max 20 # démarre un salon (vous êtes l'hôte/admin)
40
+ termhub start --password --name "Salle 1" # salon protégé par mot de passe
41
+ termhub start --headless # serveur seul, sans chat
42
+ termhub stop # arrête le serveur local
43
+ termhub scan # liste les salons du réseau
44
+ termhub join --host 192.168.1.10 --nick amina # connexion directe par IP
45
+ ```
46
+
47
+ Le premier qui lance `termhub` démarre le serveur, les suivants le trouvent
48
+ automatiquement (diffusion UDP sur le port 5599, chat sur le port TCP 5598).
49
+
50
+ ## Commandes dans le chat
51
+
52
+ | Commande | Effet |
53
+ |---|---|
54
+ | `/help` | aide |
55
+ | `/list` | qui est connecté |
56
+ | `/nick <nom>` | changer de pseudo |
57
+ | `/w <nom> <msg>` | message privé |
58
+ | `/me <action>` | action (`* nom action`) |
59
+ | `/q` | quitter |
60
+ | `/kick <nom>`, `/ban <nom>`, `/say <annonce>`, `/stop` | hôte uniquement |
61
+
62
+ ## Sécurité
63
+
64
+ - **Texte uniquement** : le protocole ne transporte que des messages ; rien n'est jamais exécuté, aucun fichier n'est échangé.
65
+ - **Nettoyage** : tous les caractères de contrôle (séquences ANSI, retours à la ligne, bidi) sont supprimés côté serveur *et* côté client.
66
+ - **Limites** : 500 caractères/message, ligne max 2 Ko, anti-flood (rafale de 5, puis 1 msg/s ; déconnexion après 10 refus), 3 connexions max par IP, `--max` connexions au total, délai de 10 s pour se présenter, déconnexion après 5 min d'inactivité.
67
+ - **Réseau local seulement** : les IP publiques sont refusées (sauf `--allow-public`, déconseillé).
68
+ - **Mot de passe optionnel** : preuve HMAC-SHA256 avec défi aléatoire, le mot de passe ne circule jamais en clair ; 5 échecs = bannissement de l'IP.
69
+ - **Pseudos** : 2-16 caractères `A-Za-z0-9_-`, uniques, noms réservés (`admin`, `server`…) interdits, donc pas d'usurpation.
70
+ - **Droits d'hôte** : seul un processus local connaissant le jeton secret (fichier `~/.termhub_admin`, droits 600) est admin. Aucun client distant ne peut le devenir.
71
+ - Les adresses IP ne sont visibles que de l'hôte (`/list`).
72
+
73
+ ## Limites connues
74
+
75
+ - Les messages **ne sont pas chiffrés** (comme sur n'importe quel chat LAN sans TLS) : ne pas y mettre de secrets.
76
+ - Si l'hôte quitte, le salon s'arrête. Pour un salon permanent : `start --headless` sur une machine dédiée.
77
+ - Certains WiFi bloquent la communication entre appareils (« isolation des clients ») : à désactiver sur la box/borne.
78
+ - Le pare-feu de l'hôte doit autoriser TCP 5598 et UDP 5599.
@@ -0,0 +1,7 @@
1
+ termhub.py,sha256=zmkmFbMa_eWSC_r7bwrG-JyL_EX6z_obbdR6UVRPPLo,26983
2
+ termhub-0.1.0.dist-info/licenses/LICENSE,sha256=zwVMYbx3PvjnRNhwFwpE4sH2VLQCEbQH99w8ZOKwmZs,1065
3
+ termhub-0.1.0.dist-info/METADATA,sha256=jLAvbxDl3rknb80tva1uWIbXstW_76r-C1adwkwimUQ,3667
4
+ termhub-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ termhub-0.1.0.dist-info/entry_points.txt,sha256=9vWYimzfRhKd9oJ62690jNM0sW_9JXWSfSn-KXo7tLc,41
6
+ termhub-0.1.0.dist-info/top_level.txt,sha256=LowiLdgZ12ae2dst5GVVT8dfZC3XfneULu4C_8PTR9g,8
7
+ termhub-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ termhub = termhub:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nanaelie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ termhub
termhub.py ADDED
@@ -0,0 +1,733 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ termhub - chat texte en reseau local, dans le terminal.
5
+ Python 3.8+, bibliotheque standard uniquement.
6
+
7
+ python termhub.py -> cherche un salon sur le reseau, sinon en demarre un
8
+ python termhub.py start --max 20 -> demarre un salon (vous en etes l'hote/admin)
9
+ python termhub.py start --headless-> serveur seul (sans chat)
10
+ python termhub.py stop -> arrete le serveur local
11
+ python termhub.py scan -> liste les salons du reseau
12
+ python termhub.py join --host IP -> se connecter directement a une IP
13
+ """
14
+ import argparse
15
+ import asyncio
16
+ import getpass
17
+ import hashlib
18
+ import hmac
19
+ import ipaddress
20
+ import json
21
+ import os
22
+ import random
23
+ import re
24
+ import secrets
25
+ import shutil
26
+ import socket
27
+ import sys
28
+ import threading
29
+ import time
30
+ import unicodedata
31
+ import _thread
32
+ from pathlib import Path
33
+
34
+ VERSION = "0.1.0"
35
+ TCP_PORT = 5598
36
+ DISC_PORT = 5599
37
+ MAGIC = b"TERMHUB_DISCOVER_V1"
38
+
39
+ MAX_LINE = 2048 # taille max d'une ligne recue par le serveur
40
+ MAX_MSG = 500 # taille max d'un message
41
+ MAX_PER_IP = 3 # connexions simultanees par IP (hors loopback)
42
+ DEFAULT_MAX = 30
43
+ RATE_BURST = 5 # rafale autorisee
44
+ RATE_PER_SEC = 1.0 # debit moyen (messages/seconde)
45
+ IDLE_TIMEOUT = 300 # secondes sans rien recevoir -> deconnexion
46
+ HANDSHAKE_TIMEOUT = 10
47
+ NICK_RE = re.compile(r"^[A-Za-z0-9_-]{2,16}$")
48
+ RESERVED = {"server", "serveur", "system", "admin", "root", "ctl", "termhub"}
49
+ ADMIN_FILE = Path.home() / ".termhub_admin"
50
+
51
+
52
+ # ----------------------------------------------------------------- utilitaires
53
+ def clean(s, limit):
54
+ """Supprime TOUS les caracteres de controle/format (ESC, \\n, bidi...) :
55
+ empeche l'injection de sequences ANSI ou le faux affichage dans le terminal."""
56
+ if not isinstance(s, str):
57
+ return ""
58
+ s = "".join(ch for ch in s if unicodedata.category(ch)[0] != "C")
59
+ return s.strip()[:limit]
60
+
61
+
62
+ def local_ip():
63
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
64
+ try:
65
+ s.connect(("10.255.255.255", 1))
66
+ return s.getsockname()[0]
67
+ except OSError:
68
+ return "127.0.0.1"
69
+ finally:
70
+ s.close()
71
+
72
+
73
+ def proof_for(password, nonce):
74
+ return hmac.new(password.encode(), nonce.encode(), hashlib.sha256).hexdigest()
75
+
76
+
77
+ def err(msg):
78
+ return {"t": "err", "m": msg}
79
+
80
+
81
+ # --------------------------------------------------------------------- SERVEUR
82
+ class Conn:
83
+ __slots__ = ("r", "w", "ip", "nick", "admin", "tokens", "last", "strikes")
84
+
85
+ def __init__(self, r, w, ip):
86
+ self.r, self.w, self.ip = r, w, ip
87
+ self.nick = None
88
+ self.admin = False
89
+ self.tokens = float(RATE_BURST)
90
+ self.last = time.monotonic()
91
+ self.strikes = 0
92
+
93
+
94
+ class Discovery(asyncio.DatagramProtocol):
95
+ def __init__(self, srv):
96
+ self.srv = srv
97
+ self.t = None
98
+
99
+ def connection_made(self, transport):
100
+ self.t = transport
101
+
102
+ def datagram_received(self, data, addr):
103
+ if data != MAGIC or not self.srv.ip_ok(addr[0]):
104
+ return
105
+ info = {"name": self.srv.name, "port": self.srv.port,
106
+ "auth": bool(self.srv.password),
107
+ "users": len(self.srv.users), "max": self.srv.max}
108
+ try:
109
+ self.t.sendto(json.dumps(info).encode(), addr)
110
+ except Exception:
111
+ pass
112
+
113
+
114
+ class Server:
115
+ def __init__(self, name, max_clients, password, bind, port, allow_public):
116
+ self.name = clean(name, 32) or "termhub"
117
+ self.max = max_clients
118
+ self.password = password or ""
119
+ self.bind, self.port, self.allow_public = bind, port, allow_public
120
+ self.users = {} # nick.lower() -> Conn
121
+ self.conns = set()
122
+ self.per_ip = {}
123
+ self.banned = set()
124
+ self.fails = {}
125
+ self.token = secrets.token_hex(16) # secret admin local
126
+ self.stop_ev = None
127
+ self.loop = None
128
+
129
+ # -- securite reseau
130
+ def ip_ok(self, ip):
131
+ if self.allow_public:
132
+ return True
133
+ try:
134
+ a = ipaddress.ip_address(ip.split("%")[0])
135
+ except ValueError:
136
+ return False
137
+ return a.is_private or a.is_loopback or a.is_link_local
138
+
139
+ # -- envoi
140
+ def send(self, c, obj):
141
+ try:
142
+ if c.w.transport.get_write_buffer_size() > 65536: # client trop lent
143
+ c.w.close()
144
+ return
145
+ c.w.write((json.dumps(obj, ensure_ascii=False) + "\n").encode("utf-8"))
146
+ except Exception:
147
+ pass
148
+
149
+ def broadcast(self, obj, skip=None):
150
+ for u in list(self.users.values()):
151
+ if u is not skip:
152
+ self.send(u, obj)
153
+
154
+ def sysmsg(self, text, skip=None):
155
+ self.broadcast({"t": "sys", "m": text}, skip)
156
+
157
+ def allow(self, c):
158
+ now = time.monotonic()
159
+ c.tokens = min(RATE_BURST, c.tokens + (now - c.last) * RATE_PER_SEC)
160
+ c.last = now
161
+ if c.tokens >= 1:
162
+ c.tokens -= 1
163
+ return True
164
+ c.strikes += 1
165
+ return False
166
+
167
+ def free_nick(self):
168
+ while True:
169
+ n = "user_%04d" % random.randint(0, 9999)
170
+ if n not in self.users:
171
+ return n
172
+
173
+ async def read(self, c, timeout):
174
+ try:
175
+ line = await asyncio.wait_for(c.r.readline(), timeout)
176
+ if not line:
177
+ return None
178
+ m = json.loads(line.decode("utf-8"))
179
+ return m if isinstance(m, dict) else None
180
+ except Exception: # timeout, ligne trop longue, JSON invalide...
181
+ return None
182
+
183
+ # -- connexion d'un client
184
+ async def handle(self, reader, writer):
185
+ peer = writer.get_extra_info("peername") or ("?", 0)
186
+ ip = peer[0]
187
+ c = Conn(reader, writer, ip)
188
+ loop_ip = ip in ("127.0.0.1", "::1")
189
+ counted = False
190
+ try:
191
+ if not self.ip_ok(ip):
192
+ return
193
+ if ip in self.banned:
194
+ self.send(c, err("Vous etes banni de ce salon."))
195
+ return
196
+ if len(self.conns) >= self.max + 10: # garde-fou avant authentification
197
+ self.send(c, err("Serveur occupe."))
198
+ return
199
+ if not loop_ip and self.per_ip.get(ip, 0) >= MAX_PER_IP:
200
+ self.send(c, err("Trop de connexions depuis votre machine."))
201
+ return
202
+ self.conns.add(c)
203
+ self.per_ip[ip] = self.per_ip.get(ip, 0) + 1
204
+ counted = True
205
+
206
+ nonce = secrets.token_hex(16)
207
+ self.send(c, {"t": "hello", "server": self.name, "v": VERSION,
208
+ "auth": bool(self.password), "nonce": nonce})
209
+ join = await self.read(c, HANDSHAKE_TIMEOUT)
210
+ if not join or join.get("t") != "join":
211
+ return
212
+
213
+ adm = join.get("admin")
214
+ admin = bool(loop_ip and isinstance(adm, str) and
215
+ hmac.compare_digest(adm.encode(), self.token.encode()))
216
+ if join.get("ctl") == "stop" and admin:
217
+ self.send(c, {"t": "sys", "m": "arret demande"})
218
+ self.stop_ev.set()
219
+ return
220
+
221
+ if self.password and not admin:
222
+ p = join.get("proof")
223
+ good = proof_for(self.password, nonce)
224
+ if not isinstance(p, str) or not hmac.compare_digest(p.encode(), good.encode()):
225
+ n = self.fails[ip] = self.fails.get(ip, 0) + 1
226
+ if n >= 5:
227
+ self.banned.add(ip)
228
+ await asyncio.sleep(1) # freine le brute-force
229
+ self.send(c, err("Mot de passe incorrect."))
230
+ return
231
+
232
+ if len(self.users) >= self.max: # pas d'await entre ce test et l'inscription
233
+ self.send(c, err("Salon plein."))
234
+ return
235
+
236
+ want, notice = join.get("nick"), None
237
+ if (isinstance(want, str) and NICK_RE.match(want)
238
+ and want.lower() not in RESERVED and want.lower() not in self.users):
239
+ nick = want
240
+ else:
241
+ nick = self.free_nick()
242
+ if want:
243
+ notice = "Pseudo invalide ou deja pris, vous etes %s." % nick
244
+ c.nick, c.admin = nick, admin
245
+ self.users[nick.lower()] = c
246
+ self.send(c, {"t": "welcome", "nick": nick, "server": self.name, "admin": admin,
247
+ "users": [u.nick for u in self.users.values()], "notice": notice})
248
+ self.sysmsg("%s a rejoint le salon" % nick, skip=c)
249
+
250
+ while True:
251
+ m = await self.read(c, IDLE_TIMEOUT)
252
+ if m is None or not self.dispatch(c, m):
253
+ break
254
+ except Exception:
255
+ pass
256
+ finally:
257
+ if c.nick and self.users.get(c.nick.lower()) is c:
258
+ del self.users[c.nick.lower()]
259
+ self.sysmsg("%s s'est deconnecte" % c.nick)
260
+ if counted:
261
+ self.conns.discard(c)
262
+ self.per_ip[ip] = max(0, self.per_ip.get(ip, 1) - 1)
263
+ try:
264
+ writer.close()
265
+ except Exception:
266
+ pass
267
+
268
+ # -- commandes (retourne False pour deconnecter)
269
+ def dispatch(self, c, m):
270
+ t = m.get("t")
271
+ if t == "ping":
272
+ return True
273
+ if t == "quit":
274
+ return False
275
+ if not self.allow(c):
276
+ if c.strikes >= 10:
277
+ self.send(c, err("Flood : vous etes deconnecte."))
278
+ return False
279
+ self.send(c, err("Doucement ! (limite de debit)"))
280
+ return True
281
+
282
+ text = clean(m.get("text"), MAX_MSG)
283
+ if t == "msg":
284
+ if text:
285
+ self.broadcast({"t": "msg", "from": c.nick, "text": text}, skip=c)
286
+ elif t == "me":
287
+ if text:
288
+ self.broadcast({"t": "me", "from": c.nick, "text": text}, skip=c)
289
+ elif t == "dm":
290
+ to = self.users.get(str(m.get("to", "")).lower())
291
+ if not text:
292
+ pass
293
+ elif not to or to is c:
294
+ self.send(c, err("Destinataire introuvable."))
295
+ else:
296
+ self.send(to, {"t": "dm", "from": c.nick, "text": text})
297
+ self.send(c, {"t": "sys", "m": "(prive -> %s) %s" % (to.nick, text)})
298
+ elif t == "nick":
299
+ new = m.get("nick")
300
+ if not isinstance(new, str) or not NICK_RE.match(new) or new.lower() in RESERVED:
301
+ self.send(c, err("Pseudo invalide (2-16 car. : lettres, chiffres, _ -)."))
302
+ elif new.lower() in self.users and self.users[new.lower()] is not c:
303
+ self.send(c, err("Pseudo deja pris."))
304
+ else:
305
+ old = c.nick
306
+ del self.users[old.lower()]
307
+ c.nick = new
308
+ self.users[new.lower()] = c
309
+ self.sysmsg("%s s'appelle maintenant %s" % (old, new))
310
+ elif t == "list":
311
+ names = ["%s (%s)" % (u.nick, u.ip) if c.admin else u.nick
312
+ for u in self.users.values()]
313
+ self.send(c, {"t": "users", "users": names})
314
+ elif t in ("kick", "ban", "say", "stop"):
315
+ if not c.admin:
316
+ self.send(c, err("Reserve a l'hote du salon."))
317
+ return True
318
+ if t == "say":
319
+ if text:
320
+ self.sysmsg("[ANNONCE] " + text)
321
+ elif t == "stop":
322
+ self.sysmsg("Le serveur va s'arreter.")
323
+ self.stop_ev.set()
324
+ else:
325
+ target = self.users.get(str(m.get("to", "")).lower())
326
+ if not target:
327
+ self.send(c, err("Utilisateur introuvable."))
328
+ elif target.admin:
329
+ self.send(c, err("Impossible sur l'hote."))
330
+ else:
331
+ if t == "ban":
332
+ self.banned.add(target.ip)
333
+ self.send(target, err("Vous avez ete %s." % ("banni" if t == "ban" else "expulse")))
334
+ self.sysmsg("%s a ete %s" % (target.nick, "banni" if t == "ban" else "expulse"))
335
+ target.w.close()
336
+ else:
337
+ self.send(c, err("Commande inconnue."))
338
+ return True
339
+
340
+ async def run(self, ready=None):
341
+ self.loop = asyncio.get_running_loop()
342
+ self.stop_ev = asyncio.Event()
343
+ server = await asyncio.start_server(self.handle, self.bind, self.port, limit=MAX_LINE)
344
+ transport = None
345
+ try:
346
+ transport, _ = await self.loop.create_datagram_endpoint(
347
+ lambda: Discovery(self), local_addr=(self.bind, DISC_PORT), allow_broadcast=True)
348
+ except Exception as e:
349
+ # decouverte indisponible : la connexion par --host reste possible
350
+ print("(decouverte automatique indisponible : %s)" % e)
351
+ try:
352
+ fd = os.open(str(ADMIN_FILE), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
353
+ os.write(fd, json.dumps({"token": self.token, "port": self.port}).encode())
354
+ os.close(fd)
355
+ except OSError:
356
+ pass
357
+ if ready:
358
+ ready.set()
359
+ await self.stop_ev.wait()
360
+ await asyncio.sleep(0.4)
361
+ server.close()
362
+ for c in list(self.conns):
363
+ try:
364
+ c.w.close()
365
+ except Exception:
366
+ pass
367
+ if transport:
368
+ transport.close()
369
+ try:
370
+ ADMIN_FILE.unlink()
371
+ except OSError:
372
+ pass
373
+
374
+
375
+ # ---------------------------------------------------------------- DECOUVERTE
376
+ def discover(wait=1.5):
377
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
378
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
379
+ s.settimeout(0.25)
380
+ targets = {"255.255.255.255", "127.0.0.1"}
381
+ ip = local_ip()
382
+ if ip != "127.0.0.1":
383
+ targets.add(".".join(ip.split(".")[:3] + ["255"]))
384
+ for t in targets:
385
+ try:
386
+ s.sendto(MAGIC, (t, DISC_PORT))
387
+ except OSError:
388
+ pass
389
+ found, end = {}, time.time() + wait
390
+ while time.time() < end:
391
+ try:
392
+ data, addr = s.recvfrom(2048)
393
+ except socket.timeout:
394
+ continue
395
+ except OSError:
396
+ break
397
+ try:
398
+ info = json.loads(data.decode("utf-8"))
399
+ port = int(info["port"])
400
+ if not 1 <= port <= 65535:
401
+ continue
402
+ found[(addr[0], port)] = {"name": clean(info.get("name"), 32) or "?",
403
+ "auth": bool(info.get("auth")),
404
+ "users": int(info.get("users", 0)),
405
+ "max": int(info.get("max", 0))}
406
+ except Exception:
407
+ continue
408
+ s.close()
409
+ return found
410
+
411
+
412
+ # -------------------------------------------------------------------- CLIENT
413
+ class Chat:
414
+ def __init__(self, host, port, nick="", password=None, admin=None, ctl=None):
415
+ self.host, self.port, self.nick = host, port, nick or ""
416
+ self.password, self.admin, self.ctl = password, admin, ctl
417
+ self.alive = False
418
+ self.is_admin = False
419
+ self.slock = threading.Lock()
420
+ self.plock = threading.Lock()
421
+
422
+ def recv(self):
423
+ line = self.rf.readline(16384)
424
+ if not line or not line.endswith(b"\n"):
425
+ return None
426
+ try:
427
+ m = json.loads(line.decode("utf-8"))
428
+ return m if isinstance(m, dict) else None
429
+ except ValueError:
430
+ return None
431
+
432
+ def send(self, obj):
433
+ data = (json.dumps(obj, ensure_ascii=False) + "\n").encode("utf-8")
434
+ with self.slock:
435
+ self.sock.sendall(data)
436
+
437
+ def connect(self):
438
+ self.sock = socket.create_connection((self.host, self.port), timeout=5)
439
+ self.sock.settimeout(None)
440
+ self.rf = self.sock.makefile("rb")
441
+ hello = self.recv()
442
+ if not hello:
443
+ raise ConnectionError("pas de reponse du serveur")
444
+ if hello.get("t") == "err":
445
+ raise ConnectionError(clean(hello.get("m"), 200))
446
+ if hello.get("t") != "hello":
447
+ raise ConnectionError("serveur incompatible")
448
+ self.server_name = clean(hello.get("server"), 32)
449
+ join = {"t": "join", "nick": self.nick}
450
+ if self.admin:
451
+ join["admin"] = self.admin
452
+ if self.ctl:
453
+ join["ctl"] = self.ctl
454
+ elif hello.get("auth") and not self.admin:
455
+ if self.password is None:
456
+ self.password = getpass.getpass("Mot de passe du salon : ")
457
+ join["proof"] = proof_for(self.password, str(hello.get("nonce", "")))
458
+ self.send(join)
459
+ if self.ctl:
460
+ self.recv()
461
+ self.sock.close()
462
+ return
463
+ w = self.recv()
464
+ if not w:
465
+ raise ConnectionError("connexion fermee par le serveur")
466
+ if w.get("t") == "err":
467
+ raise ConnectionError(clean(w.get("m"), 200))
468
+ self.nick = clean(w.get("nick"), 16)
469
+ self.is_admin = bool(w.get("admin"))
470
+ self.alive = True
471
+ if w.get("notice"):
472
+ print("!! " + clean(w["notice"], 200))
473
+ users = [clean(u, 16) for u in w.get("users", []) if isinstance(u, str)]
474
+ print("Connecte a '%s' en tant que [%s]. Utilisateurs : %s"
475
+ % (self.server_name, self.nick, ", ".join(users)))
476
+
477
+ def show(self, text):
478
+ with self.plock:
479
+ cols = shutil.get_terminal_size((80, 20)).columns - 1
480
+ line = time.strftime("%H:%M ") + text
481
+ sys.stdout.write("\r" + line + " " * max(0, cols - len(line)) + "\n> ")
482
+ sys.stdout.flush()
483
+
484
+ def reader(self):
485
+ while self.alive:
486
+ m = self.recv()
487
+ if m is None:
488
+ break
489
+ t = m.get("t")
490
+ if t == "msg":
491
+ self.show("[%s]: %s" % (clean(m.get("from"), 16), clean(m.get("text"), MAX_MSG)))
492
+ elif t == "me":
493
+ self.show("* %s %s" % (clean(m.get("from"), 16), clean(m.get("text"), MAX_MSG)))
494
+ elif t == "dm":
495
+ self.show("[%s -> vous]: %s" % (clean(m.get("from"), 16), clean(m.get("text"), MAX_MSG)))
496
+ elif t == "sys":
497
+ self.show("** " + clean(m.get("m"), 300))
498
+ elif t == "err":
499
+ self.show("!! " + clean(m.get("m"), 300))
500
+ elif t == "users":
501
+ us = [clean(u, 40) for u in m.get("users", []) if isinstance(u, str)]
502
+ self.show("Connectes (%d) : %s" % (len(us), ", ".join(us)))
503
+ if self.alive:
504
+ self.alive = False
505
+ print("\nConnexion perdue. (appuyez sur Entree si le terminal ne se ferme pas)")
506
+ _thread.interrupt_main()
507
+
508
+ def pinger(self):
509
+ while self.alive:
510
+ time.sleep(60)
511
+ try:
512
+ self.send({"t": "ping"})
513
+ except OSError:
514
+ return
515
+
516
+ def help(self):
517
+ print("Commandes :\n"
518
+ " /help cette aide\n"
519
+ " /list qui est connecte\n"
520
+ " /nick <nom> changer de pseudo\n"
521
+ " /w <nom> <msg> message prive\n"
522
+ " /me <action> action ('* nom action')\n"
523
+ " /q quitter")
524
+ if self.is_admin:
525
+ print("Hote :\n /kick <nom> /ban <nom> /say <annonce> /stop")
526
+
527
+ def command(self, line):
528
+ cmd, _, rest = line[1:].partition(" ")
529
+ cmd, rest = cmd.lower(), rest.strip()
530
+ if cmd in ("q", "quit", "exit"):
531
+ return False
532
+ if cmd in ("help", "h", "?"):
533
+ self.help()
534
+ elif cmd in ("list", "who", "users"):
535
+ self.send({"t": "list"})
536
+ elif cmd == "nick":
537
+ self.send({"t": "nick", "nick": rest})
538
+ elif cmd == "me":
539
+ self.send({"t": "me", "text": rest})
540
+ elif cmd in ("w", "msg", "dm"):
541
+ to, _, text = rest.partition(" ")
542
+ self.send({"t": "dm", "to": to, "text": text})
543
+ elif cmd in ("kick", "ban"):
544
+ self.send({"t": cmd, "to": rest})
545
+ elif cmd == "say":
546
+ self.send({"t": "say", "text": rest})
547
+ elif cmd == "stop":
548
+ self.send({"t": "stop"})
549
+ else:
550
+ print("!! Commande inconnue. Tapez /help")
551
+ return True
552
+
553
+ def run(self):
554
+ threading.Thread(target=self.reader, daemon=True).start()
555
+ threading.Thread(target=self.pinger, daemon=True).start()
556
+ print("Tapez /help pour les commandes, /q pour quitter.")
557
+ try:
558
+ while self.alive:
559
+ try:
560
+ line = input("> ")
561
+ except EOFError:
562
+ break
563
+ line = line.strip()
564
+ if not line:
565
+ continue
566
+ if line.startswith("/"):
567
+ if not self.command(line):
568
+ break
569
+ else:
570
+ self.send({"t": "msg", "text": line})
571
+ except (KeyboardInterrupt, OSError):
572
+ pass
573
+ finally:
574
+ was = self.alive
575
+ self.alive = False
576
+ try:
577
+ if was:
578
+ self.send({"t": "quit"})
579
+ self.sock.close()
580
+ except OSError:
581
+ pass
582
+ print("Deconnecte.")
583
+
584
+
585
+ # ----------------------------------------------------------------------- CLI
586
+ def start_host(max_clients=DEFAULT_MAX, name=None, ask_password=False, port=TCP_PORT,
587
+ bind="0.0.0.0", allow_public=False, nick="", headless=False):
588
+ password = os.environ.get("TERMHUB_PASSWORD") or None
589
+ if ask_password:
590
+ password = getpass.getpass("Mot de passe du salon (vide = aucun) : ") or None
591
+ srv = Server(name or (socket.gethostname() + "-hub"), max_clients, password,
592
+ bind, port, allow_public)
593
+ ready, errs = threading.Event(), []
594
+
595
+ def runner():
596
+ try:
597
+ asyncio.run(srv.run(ready))
598
+ except Exception as e:
599
+ errs.append(e)
600
+ ready.set()
601
+
602
+ t = threading.Thread(target=runner, daemon=True)
603
+ t.start()
604
+ ready.wait(10)
605
+ if errs:
606
+ raise errs[0]
607
+ ip = local_ip()
608
+ print("Salon '%s' demarre (max %d) sur %s:%d%s" % (
609
+ srv.name, max_clients, ip, port, " [protege par mot de passe]" if password else ""))
610
+ print("Les autres lancent simplement : termhub (ou termhub join --host %s)" % ip)
611
+ if headless:
612
+ print("Mode serveur seul. Ctrl+C ou 'python termhub.py stop' pour arreter.")
613
+ try:
614
+ t.join()
615
+ except KeyboardInterrupt:
616
+ srv.loop.call_soon_threadsafe(srv.stop_ev.set)
617
+ t.join(3)
618
+ return 0
619
+ chat = Chat("127.0.0.1", port, nick, admin=srv.token)
620
+ chat.connect()
621
+ chat.run()
622
+ if not srv.stop_ev.is_set():
623
+ srv.loop.call_soon_threadsafe(srv.stop_ev.set)
624
+ t.join(3)
625
+ return 0
626
+
627
+
628
+ def cmd_start(a):
629
+ try:
630
+ return start_host(a.max, a.name, a.password, a.port, a.bind,
631
+ a.allow_public, a.nick, a.headless)
632
+ except OSError as e:
633
+ print("Impossible de demarrer le serveur (%s). Un salon tourne peut-etre deja ici." % e)
634
+ return 1
635
+
636
+
637
+ def cmd_scan(a):
638
+ found = discover()
639
+ if not found:
640
+ print("Aucun salon trouve.")
641
+ return 1
642
+ for (ip, port), i in found.items():
643
+ print("%s:%d '%s' %d/%d%s" % (ip, port, i["name"], i["users"], i["max"],
644
+ " [mot de passe]" if i["auth"] else ""))
645
+ return 0
646
+
647
+
648
+ def cmd_stop(a):
649
+ try:
650
+ info = json.loads(ADMIN_FILE.read_text())
651
+ Chat("127.0.0.1", int(info["port"]), admin=info["token"], ctl="stop").connect()
652
+ print("Serveur arrete.")
653
+ return 0
654
+ except Exception:
655
+ print("Aucun serveur termhub local a arreter.")
656
+ return 1
657
+
658
+
659
+ def cmd_join(a):
660
+ host, port = a.host, a.port
661
+ if not host:
662
+ found = discover()
663
+ if not found:
664
+ if a.no_host:
665
+ print("Aucun salon trouve.")
666
+ return 1
667
+ print("Aucun salon trouve : demarrage d'un nouveau salon...")
668
+ try:
669
+ return start_host(nick=a.nick)
670
+ except OSError:
671
+ found = discover() # quelqu'un vient de le demarrer
672
+ if not found:
673
+ print("Impossible de demarrer ou rejoindre un salon.")
674
+ return 1
675
+ keys = list(found)
676
+ if len(keys) == 1:
677
+ host, port = keys[0]
678
+ else:
679
+ for n, (ip, p) in enumerate(keys, 1):
680
+ i = found[(ip, p)]
681
+ print("%d) %s (%s:%d) %d/%d" % (n, i["name"], ip, p, i["users"], i["max"]))
682
+ try:
683
+ host, port = keys[int(input("Numero du salon : ")) - 1]
684
+ except (ValueError, IndexError, EOFError):
685
+ print("Choix invalide.")
686
+ return 1
687
+ try:
688
+ chat = Chat(host, port, a.nick)
689
+ chat.connect()
690
+ except (OSError, ConnectionError) as e:
691
+ print("Connexion impossible : %s" % e)
692
+ return 1
693
+ chat.run()
694
+ return 0
695
+
696
+
697
+ def main():
698
+ ap = argparse.ArgumentParser(prog="termhub", description="Chat LAN dans le terminal.")
699
+ sub = ap.add_subparsers(dest="cmd")
700
+
701
+ j = sub.add_parser("join", help="rejoindre un salon (defaut)")
702
+ j.add_argument("--host", help="IP du serveur (sinon decouverte auto)")
703
+ j.add_argument("--port", type=int, default=TCP_PORT)
704
+ j.add_argument("--nick", default="")
705
+ j.add_argument("--no-host", action="store_true", help="ne pas demarrer de salon si aucun trouve")
706
+ j.set_defaults(fn=cmd_join)
707
+
708
+ s = sub.add_parser("start", help="demarrer un salon")
709
+ s.add_argument("--max", type=int, default=DEFAULT_MAX, help="connexions max (1-500)")
710
+ s.add_argument("--name", help="nom du salon")
711
+ s.add_argument("--password", action="store_true", help="demande un mot de passe (ou TERMHUB_PASSWORD)")
712
+ s.add_argument("--port", type=int, default=TCP_PORT)
713
+ s.add_argument("--bind", default="0.0.0.0")
714
+ s.add_argument("--allow-public", action="store_true",
715
+ help="accepter aussi les IP publiques (deconseille)")
716
+ s.add_argument("--headless", action="store_true", help="serveur seul, sans chat")
717
+ s.add_argument("--nick", default="")
718
+ s.set_defaults(fn=cmd_start)
719
+
720
+ sub.add_parser("stop", help="arreter le serveur local").set_defaults(fn=cmd_stop)
721
+ sub.add_parser("scan", help="lister les salons du reseau").set_defaults(fn=cmd_scan)
722
+
723
+ argv = sys.argv[1:]
724
+ if not argv or argv[0] not in ("join", "start", "stop", "scan", "-h", "--help"):
725
+ argv = ["join"] + argv
726
+ a = ap.parse_args(argv)
727
+ if a.cmd == "start" and not 1 <= a.max <= 500:
728
+ ap.error("--max doit etre entre 1 et 500")
729
+ sys.exit(a.fn(a))
730
+
731
+
732
+ if __name__ == "__main__":
733
+ main()