Files
waylume_server/lib/wireguard/peers.dart

197 lines
5.5 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:waylume_server/core/utils.dart';
import 'package:waylume_server/wireguard/utils.dart';
import 'package:waylume_server/wireguard/traffic_control.dart';
class WireGuardPeer {
final String privateKey;
final String publicKey;
final String ip;
WireGuardPeer({
required this.privateKey,
required this.publicKey,
required this.ip,
});
Map<String, dynamic> toJson() => {
'privateKey': privateKey,
'publicKey': publicKey,
'ip': ip,
};
factory WireGuardPeer.fromJson(Map<String, dynamic> json) => WireGuardPeer(
privateKey: json['privateKey'],
publicKey: json['publicKey'],
ip: json['ip'],
);
String generateClientConfig({
required String serverPublicKey,
required String serverEndpoint,
String dns = '1.1.1.1, 8.8.8.8', // Cloudflare and Google DNS
String allowedIPs = '0.0.0.0/0',
}) {
return '''
[Interface]
PrivateKey = $privateKey
Address = $ip/32
DNS = $dns
[Peer]
PublicKey = $serverPublicKey
Endpoint = $serverEndpoint
AllowedIPs = $allowedIPs
PersistentKeepalive = 25
''';
}
}
/// Creates a new WireGuard peer and returns the peer info
Future<WireGuardPeer> createPeer() async {
// Generate private key
final privateKeyResult = await Process.run('wg', ['genkey']);
final privateKey = privateKeyResult.stdout.toString().trim();
// Generate public key from private key
final pubProcess = await Process.start('wg', ['pubkey']);
pubProcess.stdin.writeln(privateKey);
await pubProcess.stdin.close();
final publicKey = await pubProcess.stdout.transform(utf8.decoder).join();
// Get next available IP
final ip = await _getNextIP();
// Add peer to WireGuard
await Process.run('wg', ['set', 'wg0', 'peer', publicKey.trim(), 'allowed-ips', '$ip/32']);
// Track peer creation time
await _trackPeerCreation(publicKey.trim());
return WireGuardPeer(
privateKey: privateKey,
publicKey: publicKey.trim(),
ip: ip,
);
}
Future<bool> deletePeer(String publicKey) async {
// Remove peer from WireGuard
final result = await Process.run('wg', ['set', 'wg0', 'peer', publicKey, 'remove']);
if (result.exitCode != 0) {
print('Error removing peer: ${result.stderr}');
return false;
}
// Clean up peer creation tracking
await _cleanupPeerCreation(publicKey);
return true;
}
Future<void> setSpeedLimit(String publicKey, int speedKbps) async {
print('Setting speed limit for peer $publicKey to ${speedKbps}kbps');
final peerIP = await _getPeerIP(publicKey);
print('Found peer IP: $peerIP for publicKey: $publicKey');
if (peerIP == null) throw Exception('Peer not found');
await TrafficControlService.setSpeedLimit(peerIP, speedKbps);
}
Future<void> setDataCap(String publicKey, int dataCapMB) async {
final peerIP = await _getPeerIP(publicKey);
if (peerIP == null) throw Exception('Peer not found');
await TrafficControlService.setDataCap(peerIP, dataCapMB);
}
Future<String?> _getPeerIP(String publicKey) async {
final result = await Process.run('wg', ['show', 'wg0', 'allowed-ips']);
if (result.exitCode != 0) return null;
final lines = result.stdout.toString().split('\n');
for (final line in lines) {
if (line.contains(publicKey)) {
final match = RegExp(r'(\d+\.\d+\.\d+\.\d+)').firstMatch(line);
return match?.group(1);
}
}
return null;
}
Future<String> _getNextIP() async {
final result = await Process.run('wg', ['show', 'wg0', 'allowed-ips']);
final usedIPs = RegExp(r'10\.(\d+)\.(\d+)\.(\d+)')
.allMatches(result.stdout.toString())
.map((m) => '${m.group(1)}.${m.group(2)}.${m.group(3)}')
.toSet();
// Start from 10.0.0.2 (skip .1 for server)
for (int a = 0; a <= 255; a++) {
for (int b = 0; b <= 255; b++) {
for (int c = (a == 0 && b == 0 ? 2 : 1); c <= 254; c++) {
final ip = '10.$a.$b.$c';
if (!usedIPs.contains('$a.$b.$c')) return ip;
}
}
}
throw Exception('No available IPs');
}
/// Tracks when a peer was created
Future<void> _trackPeerCreation(String publicKey) async {
try {
final file = File('/tmp/peer_creation_times.json');
Map<String, dynamic> creationTimes = {};
if (await file.exists()) {
final content = await file.readAsString();
creationTimes = jsonDecode(content);
}
creationTimes[publicKey] = DateTime.now().millisecondsSinceEpoch;
await file.writeAsString(jsonEncode(creationTimes));
} catch (e) {
print('Error tracking peer creation: $e');
}
}
/// Gets the creation time for a peer
Future<DateTime?> getPeerCreationTime(String publicKey) async {
try {
final file = File('/tmp/peer_creation_times.json');
if (!await file.exists()) return null;
final content = await file.readAsString();
final creationTimes = jsonDecode(content) as Map<String, dynamic>;
final timestamp = creationTimes[publicKey];
if (timestamp == null) return null;
return DateTime.fromMillisecondsSinceEpoch(timestamp);
} catch (e) {
print('Error getting peer creation time: $e');
return null;
}
}
/// Cleans up peer creation tracking when peer is deleted
Future<void> _cleanupPeerCreation(String publicKey) async {
try {
final file = File('/tmp/peer_creation_times.json');
if (!await file.exists()) return;
final content = await file.readAsString();
final creationTimes = jsonDecode(content) as Map<String, dynamic>;
creationTimes.remove(publicKey);
await file.writeAsString(jsonEncode(creationTimes));
} catch (e) {
print('Error cleaning up peer creation tracking: $e');
}
}