v3.0.0: Standalone release of ChaosCryptChat

Separate the encrypted messaging application into its own repository, with
documentation written specifically for it.

The application code is byte-for-byte identical to the version previously
shipped inside the ChaosCrypt repository. No functional changes.

Contents
- qtmain.py: PyQt5 client together with the complete backend (cipher core,
  account and history databases, peer-to-peer networking, relay client, GUI)
- server.py: optional central relay server, using only the standard library
  so it can be deployed on a bare machine

Documentation
- README: architecture, component map, wire protocol, requirements,
  installation, running, data locations, security properties, troubleshooting
- SECURITY: threat model, protected properties, cryptographic building
  blocks, and known limitations including metadata exposure, plaintext local
  storage, P2P host trust, best-effort withdrawal, and the absence of a
  ratchet
- LICENSE: MIT
- CHANGELOG: release history
- .gitignore: excludes application data, session tokens, local databases and
  media from version control

Security notice
Unaudited. Intended for learning, experimentation and personal use; not for
production deployment or for confidentiality obligations that carry a
regulatory, contractual or safety dimension.
This commit is contained in:
dvs
2026-09-27 17:11:06 +08:00
commit faf60fd2e5
7 changed files with 5307 additions and 0 deletions
+62
View File
@@ -0,0 +1,62 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
*.so
# Virtual environments
venv/
.venv/
env/
ENV/
# Application data — MUST NOT be committed
# These hold account databases, chat history and session tokens.
data/
server_data/
*.db
*.db-journal
*.db-wal
*.db-shm
*.sqlite
*.sqlite3
# Session tokens and credentials
*.dat
session.dat
*_cred*
*credential*
*secret*
# Media cache (voice notes, images, files received or sent)
media/
Documents/ChaosChat/
# Keys
*.key
*.pem
# Packaging / build
build/
dist/
*.egg-info/
.eggs/
wheels/
# Test / coverage
.pytest_cache/
.coverage
htmlcov/
.tox/
# Editors / IDEs
.idea/
.vscode/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
desktop.ini
+67
View File
@@ -0,0 +1,67 @@
# Changelog
All notable changes to this project are documented in this file.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/).
---
## [3.0.0] — 2026-09-27
First release as a standalone repository. The application code is unchanged
from the version previously distributed inside the ChaosCrypt repository; this
release separates it into its own project with its own documentation and
licence.
### Added
- `README.md` — overview, architecture, installation, running instructions,
data locations, security properties and troubleshooting.
- `SECURITY.md` — threat model, protected properties, cryptographic building
blocks, and a detailed list of known limitations.
- `LICENSE` — MIT.
- `.gitignore` — excludes application data, session tokens, local databases
and media from version control.
### Changed
- Distributed as its own repository rather than a subdirectory of ChaosCrypt.
- Documentation written specifically for this application, rather than
inheriting the cipher's documentation.
### Structure
| File | Role |
|---|---|
| `qtmain.py` | PyQt5 client together with the complete backend |
| `server.py` | Optional central relay server, standard library only |
### Notes
The application code is byte-for-byte identical to the version shipped with
ChaosCrypt 2.0.0. No functional changes were made in this release.
---
## [2.0.0] — 2026-08-26
Released as part of the ChaosCrypt project.
### Added
- End-to-end encrypted chat on top of the ChaosCrypt cipher.
- Two group modes: direct peer-to-peer, and a central relay for NAT traversal.
- Voice messages: record, encrypt, transmit, decrypt, play.
- Image and arbitrary file transfer, encrypted like any other payload.
- Group management: create, join, rename, announcements, kicking members,
join approval.
- Message withdrawal within a time window.
- Per-user keys for member authentication, preventing impersonation.
- SQLite-backed history that survives restarts.
- HMAC integrity checking on every message.
- PyQt5 interface with rounded, adaptive message bubbles.
- Account and history storage in SQLite, with salted password hashing.
[3.0.0]: https://git.dvscloud.net/dvs/ChaosCryptChat/releases/tag/v3.0.0
[2.0.0]: https://git.dvscloud.net/dvs/ChaosCrypt/releases/tag/v2.0.0
+44
View File
@@ -0,0 +1,44 @@
MIT License
Copyright (c) 2026 Dvs (DvsXT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---------------------------------------------------------------------------
ADDITIONAL NOTICE / 附加声明
ChaosCryptChat is an end-to-end encrypted messaging application built on the
ChaosCrypt cipher. Neither the cipher nor the application has been
independently audited, and the cipher is not a standardised construction.
The software is intended for learning, experimentation and personal use. It is
not intended for production deployment or for any use where confidentiality is
subject to regulatory or contractual guarantees.
The authors accept no liability for any loss, disclosure or damage arising
from use of this software.
ChaosCryptChat 是基于 ChaosCrypt 加密内核的端到端加密通讯应用。加密内核与
本应用均未经独立审计,且加密内核并非标准化算法。
本项目供学习、实验与个人使用,不适用于生产部署,也不适用于任何对保密性有
监管或合同要求的场景。
因使用本软件造成的任何损失、泄露或损害,作者不承担责任。
+273
View File
@@ -0,0 +1,273 @@
# ChaosCryptChat
**End-to-end encrypted messaging built on the ChaosCrypt cipher.**
A desktop chat application with a PyQt5 client and an optional relay server.
Messages are encrypted on the client; the server only relays ciphertext and
never holds group keys.
| | |
|---|---|
| **Version** | 3.0.0 |
| **Default branch** | `chat` |
| **Licence** | MIT |
| **Python** | 3.8+ |
---
## Scope
ChaosCryptChat is an experiment in building a complete encrypted messaging
application on top of a non-standard cipher. It is intended for **learning,
experimentation and personal use**.
It has **not** been independently audited. It is not a replacement for
Signal, Matrix or any audited secure messenger, and it should not be relied on
where confidentiality carries regulatory, contractual or safety obligations.
The underlying cipher is documented separately in the
[ChaosCrypt](https://git.dvscloud.net/dvs/ChaosCrypt) repository, including
its full design and threat analysis. That analysis applies here too: the
construction is substantially stronger than its lack of audit suggests, but
the scope is deliberately narrow.
---
## What it does
- **End-to-end encryption.** The group key exists only on clients. The server
relays ciphertext and cannot decrypt anything.
- **Two group modes.**
- **End-to-end (P2P)** — peers connect directly; no server involved.
- **Central server** — a relay handles NAT traversal when direct
connections are not possible.
- **Text, images, files and voice messages.** All payload types are encrypted
the same way; binary data is handled losslessly.
- **Group management.** Create, join, rename, set announcements, kick members,
approve join requests.
- **Per-user key authentication.** Each member is issued a key used to sign
their messages, so one member cannot impersonate another.
- **Message integrity.** Each message carries an HMAC; a modified ciphertext
fails verification and is rejected.
- **Message withdrawal.** Sent messages can be recalled within a time window.
- **Local history.** Chat history is stored per account in SQLite and survives
restarts.
---
## Architecture
```
ChaosCryptChat/
├── qtmain.py PyQt5 client + the entire backend
└── server.py optional central relay server (standard library only)
```
`qtmain.py` is a single-file application: it contains the cryptographic core,
the account and history databases, the peer-to-peer networking layer, the
relay client, and the graphical interface. Running it directly starts the
client.
`server.py` is deliberately independent and uses **only the Python standard
library**, so it can be deployed on a bare server without installing anything.
### Components in `qtmain.py`
| Component | Responsibility |
|---|---|
| `ChaosCryptCore` | The cipher: key generation, substitution, XOR layers |
| `SecureSession` | Per-session key handling, encryption and HMAC |
| `AccountDB` | Local accounts: salted password hashes |
| `HistoryDB` | Local message history per account and group |
| `ServerDB` | Local cache of relay state and issued user keys |
| `VoiceManager` | Audio recording and playback |
| `Message` | Message record and serialisation |
| `ChatServer` | Peer-to-peer listener (for P2P groups) |
| `ChatClient` | Peer-to-peer sender |
| `ServerConnection` | Client side of the central-relay protocol |
| `MessageItem` / `MessageList` | Message bubbles and the scrollable list |
| `LoginDialog` / `MainWindow` | Login and main window |
### Components in `server.py`
| Component | Responsibility |
|---|---|
| `ServerDB` | Users, groups, membership and announcements |
| `CentralServer` | Accept loop, authentication, group management, relay |
### Wire protocol
Messages are length-prefixed JSON frames:
```
uint32 big-endian length || UTF-8 JSON payload
```
Both ends implement the same framing, so the protocol is symmetric. The
handshake and command set are visible in the `_dispatch` methods of
`ChatClient`, `ServerConnection` and `CentralServer`.
---
## Requirements
### Client (`qtmain.py`)
| Package | Purpose |
|---|---|
| `PyQt5` | Graphical interface |
| `Pillow` | Image handling |
| `numpy` | Fast buffer operations for audio and media |
| `pygame` | Audio playback |
| `sounddevice` | Audio recording |
| `pyaudio` | Alternative audio backend |
| `qrcode` | Group-key QR sharing |
Optional, depending on which features you use — the application degrades
gracefully when they are absent.
### Server (`server.py`)
None. The server uses only the standard library.
---
## Installation
```bash
git clone https://git.dvscloud.net/dvs/ChaosCryptChat.git
cd ChaosCryptChat
pip install PyQt5 Pillow numpy pygame sounddevice pyAudio qrcode
```
On Linux you may also need the system audio and Qt libraries:
```bash
sudo apt install python3-pyqt5 portaudio19-dev libsndfile1
```
---
## Running
### Start a P2P chat
```bash
python qtmain.py
```
Create an account, then create a group in **end-to-end** mode. Share the group
key with the people you want to talk to — they need it to decrypt messages.
### Start the relay server
On a machine with a reachable address:
```bash
python server.py # listens on 0.0.0.0:8666
python server.py 9000 # or choose a port
```
Clients then create a group in **central server** mode and point it at that
address. The server relays ciphertext; it never receives the group key.
> **Share group keys over a channel you already trust.** Anyone holding the
> group key can read the group's messages. The application cannot verify how
> you transmitted it.
---
## Where data lives
| Path | Contents |
|---|---|
| `data/users.db` | Local accounts (salted password hashes) |
| `data/chat_history.db` | Message history per account and group |
| `data/session.dat` | Session token, so you stay logged in |
| `data/server_state.db` | Cached relay state and issued user keys |
| `server_data/server.db` | Server-side users, groups, membership |
| `~/Documents/ChaosChat/media/` | Received and sent media |
| `~/Downloads/ChaosChat/` | Downloaded files |
The media cache can be cleared from the application's interface; clearing it
deletes the stored media permanently.
> **These files are not encrypted at rest.** The databases and the media cache
> hold plaintext. Protect the machine, or store the directories on an
> encrypted volume.
---
## Security properties
What the design does provide:
- **The server cannot read messages.** Group keys never leave clients. An
attacker who fully controls the relay obtains membership metadata and
traffic patterns, but not message contents.
- **Account passwords are not stored in plaintext.** They are hashed with a
random per-account salt.
- **Message tampering is detected.** Every message carries an HMAC over its
contents; verification failures are rejected rather than displayed.
- **Impersonation between members is prevented.** Each member's messages are
signed with a key issued to that member.
What to be aware of:
- **No independent audit.** The cipher, the protocol and this application have
not been reviewed by a third party.
- **Metadata is exposed to the relay.** Who is in a group, who talks to whom,
and when — none of that is hidden.
- **Keys are shared out of band.** If the group key is intercepted during
sharing, the group is compromised.
- **In P2P mode, the host is also a participant.** If the host's machine is
compromised, that group is compromised.
- **Local data is not encrypted.** See the table above.
- **Withdrawal is best-effort.** A recall marks a message as withdrawn and
notifies the server; members who are offline may still see the original.
- **Media handling depends on third-party libraries.** Audio and image
processing rely on `pygame`, `sounddevice` and `Pillow`, whose own security
is outside this project's scope.
For the cipher's own analysis — key space, resistance to differential, linear
and algebraic cryptanalysis, and behaviour under quantum algorithms — see the
`SECURITY.md` in the [ChaosCrypt](https://git.dvscloud.net/dvs/ChaosCrypt)
repository.
---
## Troubleshooting
| Symptom | Likely cause |
|---|---|
| `ModuleNotFoundError: PyQt5` | Client dependencies not installed |
| No audio devices listed | `sounddevice` or PortAudio missing |
| Peers cannot connect in P2P mode | Firewall blocking the port, or NAT; use the relay |
| Cannot join a group | The group key does not match, or the host has not approved you |
| Messages appear as failures | HMAC verification failed — wrong key or altered data |
| Relay unreachable | `server.py` not running, or the port is blocked |
---
## Repository layout
```
.
├── README.md this file
├── SECURITY.md security model and known limitations
├── LICENSE MIT
├── CHANGELOG.md release history
├── .gitignore
├── qtmain.py client and backend
└── server.py relay server
```
---
## Licence
[MIT](LICENSE). Provided as-is, without warranty of any kind.
The authors accept no liability for any loss, disclosure or damage arising
from use of this software.
+296
View File
@@ -0,0 +1,296 @@
# Security Policy
**ChaosCryptChat — threat model, guarantees and known limitations**
| | |
|---|---|
| **Version** | 3.0.0 |
| **Status** | Unaudited |
| **Licence** | MIT |
---
## 1. Scope
This document describes what ChaosCryptChat protects, what it does not, and
where its trust boundaries lie.
The application is an experiment in building complete encrypted messaging on
top of a non-standard cipher. It is intended for **learning, experimentation
and personal use**. It has not been audited, and it is not a substitute for an
audited secure messenger such as Signal or Matrix.
If your threat model includes a well-resourced adversary, or if
confidentiality carries regulatory or contractual weight, use an audited
messenger instead. That is not a disclaimer bolted on to be safe — it is the
correct engineering choice, and this document will not pretend otherwise.
The cipher itself is documented separately in the
[ChaosCrypt](https://git.dvscloud.net/dvs/ChaosCrypt) repository: key space,
resistance to differential, linear and algebraic cryptanalysis, and behaviour
under Shor's and Grover's algorithms. Everything established there applies to
this application. What follows concerns the *application* layer.
---
## 2. Threat model
### Trusted
- **Client machines.** Messages are encrypted and decrypted in client process
memory. A compromised client is a compromised conversation.
- **The channel used to share a group key.** The application cannot verify how
the key reached the other members.
### Untrusted
- **The network.** Transmission may be observed, altered or replayed.
- **The relay server.** Worst-case assumption: the operator is adversarial and
the machine is fully compromised.
### Partially trusted
- **The group host, in P2P mode.** The host runs both the server and the
client. If the host is compromised, that group is compromised.
- **Group members.** Any member holding the group key can read the group's
messages. Membership is a trust decision.
---
## 3. What is protected
### 3.1 Message confidentiality
Message contents are encrypted on the client with the group key. The relay
receives ciphertext and relays it onward without the ability to decrypt.
```
plaintext
│ encrypt with group key (ChaosCrypt)
▼
ciphertext ── HMAC ──► network ──► relay ──► network ──► members
│ verify HMAC
│ decrypt
▼
plaintext
```
The group key is generated on the client and stored locally. It is never
transmitted to the relay as part of normal operation.
**Consequence of relay compromise:** message contents remain confidential, but
the attacker learns group membership, message timing, message sizes, and who
communicates with whom. See §5.1.
### 3.2 Message integrity
Every message carries an HMAC computed over its contents. A message whose HMAC
does not verify is rejected rather than displayed. An attacker who can modify
traffic in transit cannot alter a message without detection, and cannot forge
a new one without the key.
### 3.3 Account credentials
Account passwords are never stored in plaintext. Each account has a random
salt, generated per account, and only the salted hash is persisted. This
means a stolen `users.db` does not directly yield passwords — though password
strength still determines how long an offline attack takes.
### 3.4 Member authentication
On joining a group, each member is issued a user key used to sign their
messages. Other members verify the signature, so one member cannot send
messages that appear to come from another within the same group.
### 3.5 Group key verification
Joining a group requires presenting a credential derived from the group key.
A party without the group key cannot join, so the group is closed to those who
do not already hold the secret.
---
## 4. Cryptographic building blocks
| Purpose | Mechanism |
|---|---|
| Message content | ChaosCrypt cipher with the group key |
| Per-message key | Message key derived from the group key and a per-message nonce |
| Integrity | HMAC-SHA256 over the ciphertext |
| Member signing | Per-user key issued on joining a group |
| Password storage | Salted hash, random per-account salt |
| Group key sharing | Out of band; optionally by QR code |
### 4.1 On the choice of cipher
ChaosCrypt is not a standardised construction. Its key space is very large and
it resists the classical cryptanalytic techniques that depend on algebraic or
number-theoretic structure — but it has not been reviewed by third parties, and
it has not accumulated the decades of scrutiny that AES or ChaCha20 have.
That is the honest trade-off. This application exists to explore the design,
not to claim parity with audited primitives.
### 4.2 Group key distribution
The security of a group depends entirely on the security of the channel used
to share its key. The application supports QR sharing for convenience, which
still requires that the code itself is shown over a trusted channel. If the
key is intercepted during sharing, the group should be considered compromised
and the key rotated.
---
## 5. Known limitations
### 5.1 Metadata is not protected
The relay necessarily observes:
- which accounts exist and when they authenticate;
- which groups exist and who belongs to them;
- when messages are sent, to which group, and their sizes;
- the network addresses involved.
None of this is hidden. Reliable metadata protection requires a design with
cover traffic, padding, and mixnet-style routing, none of which is present
here. If metadata is part of your threat model, this application does not
address it.
### 5.2 Local data is stored in plaintext
| Path | Contents |
|---|---|
| `data/users.db` | Accounts and salted password hashes |
| `data/chat_history.db` | Full message history |
| `data/session.dat` | Session token |
| `data/server_state.db` | Cached relay state and user keys |
| `server_data/server.db` | Server-side users, groups, membership |
| `~/Documents/ChaosChat/media/` | Received and sent media |
Message history and media are stored **without encryption**. Anyone with
access to the filesystem — including anyone who steals the machine or gains
access to a backup — can read them directly. Protect the machine, or keep
these directories on an encrypted volume.
Clearing the media cache from the application deletes the stored media
permanently; there is no undo.
### 5.3 P2P mode: the host is a participant
In end-to-end mode there is no separate server — the group host runs both.
This has two consequences:
1. The host can observe connection metadata for the whole group.
2. If the host's machine is compromised, that group's security is
compromised, because the host holds both the group key and the routing.
Use relay mode when you do not want one participant to hold that position.
### 5.4 Message withdrawal is best-effort
Recalling a message marks it as withdrawn locally and notifies the relay, which
broadcasts the withdrawal. Members who are offline when the withdrawal is
announced may still see the original message when they reconnect. A member who
has already saved the content keeps it.
Withdrawal is a convenience feature, not a confidentiality guarantee, and it
should never be relied on to retract sensitive data.
### 5.5 Third-party dependencies
Audio recording and playback, image handling and QR generation rely on
`pygame`, `sounddevice`, `pyaudio`, `Pillow` and `qrcode`. The security of
those libraries is outside this project's scope. They run in-process, so a
vulnerability in any of them affects the application.
The relay server, by contrast, uses only the Python standard library.
### 5.6 No forward secrecy
The design does not implement a ratchet. Compromise of a group key exposes
messages encrypted under that key, both past and future, until the key is
rotated. Rotating the group key after a suspected compromise limits the
exposure to messages sent under the new key.
### 5.7 No protection against a compromised endpoint
Nothing in this design helps if the client machine is compromised. Malware,
keyloggers, a hostile operating system, or physical access to an unlocked
session all defeat end-to-end encryption, as they do for every messaging
application.
### 5.8 Reachability
Direct peer connections require that peers can reach each other. Firewalls and
NAT frequently prevent this, which is the reason the relay exists. Relay mode
degrades the metadata situation (§5.1) because all traffic passes through one
point.
---
## 6. Operational guidance
**Do**
- Generate a strong, unique password for each account.
- Share group keys in person, or over a channel you already trust.
- Rotate the group key if you suspect it was exposed.
- Keep the local data directories on an encrypted volume.
- Use relay mode when you do not want a single participant to hold routing
visibility.
- Run the relay on a machine you control, and keep it patched.
**Do not**
- Send anything through a group whose key was shared over an untrusted
channel.
- Rely on message withdrawal to retract sensitive content.
- Assume message history is protected because messages were encrypted in
transit — locally, it is plaintext.
- Deploy this where an audit or a compliance certification is required.
- Treat metadata as private.
---
## 7. Reporting a vulnerability
If you believe you have found a security issue, please report it privately
before disclosing it publicly. Include:
- a description of the issue;
- steps to reproduce, ideally minimal;
- the version affected;
- any suggested remediation.
Reports are welcome. Note that this project is maintained on a best-effort
basis and carries no warranty or support commitment, as set out in the MIT
licence.
---
## 8. Summary
**Protected:** message contents from the relay and from network observers;
message integrity; account passwords at rest in the database; member identity
within a group.
**Not protected:** metadata; local history and media at rest; anything against
a compromised endpoint; past messages after a key compromise; retraction
guarantees.
**The honest position:** this is a working, thoughtfully constructed encrypted
messaging application built on an unaudited cipher. It demonstrates a complete
end-to-end design — client-side encryption, key-based membership, integrity
verification and a relay that cannot read anything. It is genuinely useful for
learning and for personal use. It is not a replacement for an audited
messenger, and it should not be treated as one.
---
## 9. Licence
MIT. Provided as-is, without warranty of any kind. See [LICENSE](LICENSE).
The authors accept no liability for any loss, disclosure or damage arising
from use of this software.
+4147
View File
File diff suppressed because it is too large Load Diff
+418
View File
@@ -0,0 +1,418 @@
# -*- coding: utf-8 -*-
"""
☁️ 混沌加密聊天 - 中央服务器 (解决 NAT / 公网穿透)
====================================================
- 服务器只负责: 用户认证 + 群成员管理 + 消息中继
- 所有消息内容由客户端加密, 服务器【不持有群密钥】
- 密钥只在客户端本地, 永不上传到服务器
- 部署: 放到有公网IP的机器, python server.py [端口]
"""
import os
import sys
import json
import time
import base64
import struct
import socket
import hashlib
import threading
import sqlite3
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 8666
DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'server_data', 'server.db')
MAX_FRAME = 256 * 1024 * 1024
# ==================== 帧协议 (与客户端一致) ====================
def send_msg(sock, obj):
payload = json.dumps(obj, ensure_ascii=False).encode('utf-8')
sock.sendall(struct.pack('>I', len(payload)) + payload)
def recv_exact(sock, n):
data = b''
while len(data) < n:
try:
chunk = sock.recv(n - len(data))
except socket.timeout:
continue
except Exception:
return None
if not chunk:
return None
data += chunk
return data
def recv_msg(sock):
header = recv_exact(sock, 4)
if header is None:
return None
length = struct.unpack('>I', header)[0]
if length <= 0 or length > MAX_FRAME:
return None
payload = recv_exact(sock, length)
if payload is None:
return None
try:
return json.loads(payload.decode('utf-8'))
except Exception:
return None
# ==================== 服务器数据库 ====================
class ServerDB:
def __init__(self, db_path=DB_PATH):
os.makedirs(os.path.dirname(db_path), exist_ok=True)
self.conn = sqlite3.connect(db_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self.lock = threading.Lock()
self._init()
def _init(self):
with self.lock:
cur = self.conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
salt TEXT NOT NULL,
pass_hash TEXT NOT NULL,
created_at REAL)''')
cur.execute('''CREATE TABLE IF NOT EXISTS groups(
id TEXT PRIMARY KEY,
owner TEXT NOT NULL,
name TEXT,
announcement TEXT,
created_at REAL)''')
cur.execute('''CREATE TABLE IF NOT EXISTS group_members(
group_id TEXT NOT NULL,
username TEXT NOT NULL,
joined_at REAL,
PRIMARY KEY(group_id, username))''')
self.conn.commit()
def register(self, username, password):
salt = os.urandom(16).hex()
ph = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'),
bytes.fromhex(salt), 120000).hex()
try:
with self.lock:
cur = self.conn.cursor()
cur.execute('INSERT INTO users(username, salt, pass_hash, created_at) VALUES(?,?,?,?)',
(username, salt, ph, time.time()))
self.conn.commit()
return True, 'ok'
except sqlite3.IntegrityError:
return False, '该用户名已被注册'
def login(self, username, password):
with self.lock:
cur = self.conn.cursor()
row = cur.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone()
if row is None:
return None, '用户不存在'
ph = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'),
bytes.fromhex(row['salt']), 120000).hex()
if ph != row['pass_hash']:
return None, '密码错误'
return row, 'ok'
def create_group(self, group_id, owner, name):
with self.lock:
cur = self.conn.cursor()
cur.execute('INSERT INTO groups(id, owner, name, created_at) VALUES(?,?,?,?)',
(group_id, owner, name, time.time()))
cur.execute('INSERT OR IGNORE INTO group_members(group_id, username, joined_at) VALUES(?,?,?)',
(group_id, owner, time.time()))
self.conn.commit()
def add_member(self, group_id, username):
with self.lock:
cur = self.conn.cursor()
row = cur.execute('SELECT 1 FROM groups WHERE id=?', (group_id,)).fetchone()
if row is None:
return False
cur.execute('INSERT OR IGNORE INTO group_members(group_id, username, joined_at) VALUES(?,?,?)',
(group_id, username, time.time()))
self.conn.commit()
return True
def remove_member(self, group_id, username):
with self.lock:
cur = self.conn.cursor()
cur.execute('DELETE FROM group_members WHERE group_id=? AND username=?',
(group_id, username))
self.conn.commit()
def get_group(self, group_id):
with self.lock:
cur = self.conn.cursor()
return cur.execute('SELECT id, name, announcement, owner FROM groups WHERE id=?',
(group_id,)).fetchone()
def list_groups(self, username):
with self.lock:
cur = self.conn.cursor()
rows = cur.execute('''SELECT g.id, g.name, g.owner, g.announcement FROM groups g
JOIN group_members m ON m.group_id = g.id
WHERE m.username=?''', (username,)).fetchall()
return [{'id': r['id'], 'name': r['name'], 'owner': r['owner'],
'announcement': r['announcement'] or ''} for r in rows]
def is_owner(self, group_id, username):
with self.lock:
cur = self.conn.cursor()
row = cur.execute('SELECT owner FROM groups WHERE id=?', (group_id,)).fetchone()
return bool(row and row['owner'] == username)
def set_group_name(self, group_id, name):
with self.lock:
cur = self.conn.cursor()
cur.execute('UPDATE groups SET name=? WHERE id=?', (name, group_id))
self.conn.commit()
def set_announcement(self, group_id, text):
with self.lock:
cur = self.conn.cursor()
cur.execute('UPDATE groups SET announcement=? WHERE id=?', (text, group_id))
self.conn.commit()
def members(self, group_id):
with self.lock:
cur = self.conn.cursor()
rows = cur.execute('SELECT username FROM group_members WHERE group_id=?',
(group_id,)).fetchall()
return [r['username'] for r in rows]
# ==================== 中央服务器 ====================
class CentralServer:
def __init__(self, host=SERVER_HOST, port=SERVER_PORT, db=None):
self.host = host
self.port = port
self.db = db or ServerDB()
self.sock = None
self.running = False
self.clients = {} # cid -> {socket, username, token, addr, lock}
self.next_id = 1
self.lock = threading.Lock()
def start(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.sock.listen(50)
self.running = True
print(f"☁️ 中央服务器启动: {self.host}:{self.port}")
print(f" 数据库: {DB_PATH}")
threading.Thread(target=self._accept_loop, daemon=True).start()
def stop(self):
self.running = False
if self.sock:
try:
self.sock.close()
except Exception:
pass
self.sock = None
with self.lock:
socks = [c['socket'] for c in self.clients.values()]
self.clients.clear()
for s in socks:
try:
s.close()
except Exception:
pass
def _accept_loop(self):
while self.running:
try:
client, addr = self.sock.accept()
with self.lock:
cid = self.next_id
self.next_id += 1
self.clients[cid] = {'socket': client, 'username': None,
'token': None, 'addr': addr,
'lock': threading.Lock()}
print(f" 📶 新连接: {addr[0]}:{addr[1]}")
threading.Thread(target=self._handler, args=(cid,), daemon=True).start()
except Exception:
break
def _send(self, cid, msg):
with self.lock:
c = self.clients.get(cid)
if c:
try:
with c['lock']:
send_msg(c['socket'], msg)
except Exception:
pass
def _handler(self, cid):
client = self.clients[cid]['socket']
# 第一步: 认证 (register 自动登录 或 login)
try:
msg = recv_msg(client)
if msg and msg.get('type') == 'register':
username = str(msg.get('username', ''))[:24]
password = str(msg.get('password', ''))
ok, err = self.db.register(username, password)
if not ok:
self._send(cid, {'type': 'error', 'msg': err})
self._remove(cid)
return
row, _ = self.db.login(username, password)
self._auth_ok(cid, row)
elif msg and msg.get('type') == 'login':
username = str(msg.get('username', ''))[:24]
password = str(msg.get('password', ''))
row, err = self.db.login(username, password)
if row is None:
self._send(cid, {'type': 'error', 'msg': err})
self._remove(cid)
return
self._auth_ok(cid, row)
else:
self._remove(cid)
return
except Exception:
self._remove(cid)
return
# 第二步: 业务消息循环
while self.running:
if cid not in self.clients:
break
try:
msg = recv_msg(client)
if msg is None:
break
self._handle(cid, msg)
except Exception:
break
self._remove(cid)
def _auth_ok(self, cid, row):
username = row['username']
token = os.urandom(16).hex()
with self.lock:
if cid in self.clients:
self.clients[cid]['username'] = username
self.clients[cid]['token'] = token
print(f" 👤 {username} 已登录")
self._send(cid, {'type': 'login_ok', 'token': token, 'username': username})
def _handle(self, cid, msg):
with self.lock:
if cid not in self.clients:
return
username = self.clients[cid]['username']
mtype = msg.get('type')
if mtype == 'create_group':
group_id = str(msg.get('group_id') or f"g{int(time.time()*1000)}-{os.urandom(3).hex()}")
name = str(msg.get('name', ''))[:40]
self.db.create_group(group_id, username, name or group_id)
print(f" 📡 {username} 创建群 [{name}] ({group_id})")
self._send(cid, {'type': 'group_created', 'group_id': group_id, 'name': name})
elif mtype == 'list_groups':
groups = self.db.list_groups(username)
self._send(cid, {'type': 'groups', 'groups': groups})
elif mtype == 'join_group':
group_id = str(msg.get('group_id', ''))
if self.db.add_member(group_id, username):
self._send(cid, {'type': 'join_ok', 'group_id': group_id})
# 推送当前群名/公告给新成员
ginfo = self.db.get_group(group_id)
self._send(cid, {'type': 'group_info', 'group_id': group_id,
'name': ginfo['name'] if ginfo else '',
'announcement': ginfo['announcement'] if ginfo else ''})
self._broadcast_group(group_id,
{'type': 'system', 'text': f"👋 {username} 加入了群",
'group_id': group_id}, exclude=cid)
else:
self._send(cid, {'type': 'error', 'msg': '群不存在'})
elif mtype == 'set_group_name':
group_id = str(msg.get('group_id', ''))
name = str(msg.get('name', ''))[:40]
if self.db.is_owner(group_id, username):
self.db.set_group_name(group_id, name)
self._broadcast_group(group_id, {'type': 'group_name', 'group_id': group_id,
'name': name}, exclude=None)
print(f" 🏷️ {username} 修改群名: {name}")
else:
self._send(cid, {'type': 'error', 'msg': '仅群主可修改群名'})
elif mtype == 'set_announcement':
group_id = str(msg.get('group_id', ''))
text = str(msg.get('text', ''))[:500]
if self.db.is_owner(group_id, username):
self.db.set_announcement(group_id, text)
self._broadcast_group(group_id, {'type': 'announcement', 'group_id': group_id,
'text': text}, exclude=None)
print(f" 📢 {username} 设置公告: {text[:30]}")
else:
self._send(cid, {'type': 'error', 'msg': '仅群主可设置公告'})
elif mtype == 'leave_group':
group_id = str(msg.get('group_id', ''))
self.db.remove_member(group_id, username)
self._send(cid, {'type': 'leave_ok', 'group_id': group_id})
self._broadcast_group(group_id,
{'type': 'system', 'text': f"👋 {username} 离开了群",
'group_id': group_id}, exclude=cid)
elif mtype == 'group_members':
group_id = str(msg.get('group_id', ''))
self._send(cid, {'type': 'members', 'group_id': group_id,
'members': self.db.members(group_id)})
elif mtype == 'group_message':
group_id = str(msg.get('group_id', ''))
payload = msg.get('payload')
# 转发给同群其他成员 (服务器不解析加密内容)
self._broadcast_group(group_id,
{'type': 'group_message', 'group_id': group_id,
'from': username, 'payload': payload}, exclude=cid)
def _broadcast_group(self, group_id, msg, exclude=None):
members = set(self.db.members(group_id))
with self.lock:
targets = [(cid2, c['socket'], c['lock']) for cid2, c in self.clients.items()
if c.get('username') in members and cid2 != exclude]
for cid2, sock, lk in targets:
try:
with lk:
send_msg(sock, msg)
except Exception:
pass
def _remove(self, cid):
with self.lock:
entry = self.clients.pop(cid, None)
if entry:
try:
entry['socket'].close()
except Exception:
pass
if entry['username']:
print(f" 🔌 {entry['username']} 断开")
if __name__ == '__main__':
port = int(sys.argv[1]) if len(sys.argv) > 1 else SERVER_PORT
srv = CentralServer(port=port)
srv.start()
print("按 Ctrl+C 停止服务器")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
srv.stop()
print("\n☁️ 服务器已停止")