1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to test latency of Mullvad WireGuard relays and generate a PAC file.
Uses raw sockets for cross-platform ICMP ping functionality.
"""
import argparse
import socket
import statistics
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from typing import List, TypedDict
import requests
from loguru import logger
class Relay(TypedDict):
hostname: str
location: str
socks5: str
class RelayResult(TypedDict):
relay: Relay
latency: float
def ping_host(hostname: str, ping_count: int, ping_timeout: int) -> float:
try:
try:
ip_address = socket.gethostbyname(hostname)
except socket.gaierror:
return float("inf")
rtts = []
for _ in range(ping_count):
try:
start = time.time()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(ping_timeout)
s.connect((ip_address, 1080))
s.close()
rtts.append((time.time() - start) * 1000)
except (socket.timeout, socket.error):
rtts.append(float("inf"))
valid_rtts = [rtt for rtt in rtts if rtt != float("inf")]
return statistics.mean(valid_rtts) if valid_rtts else float("inf")
except Exception as e:
logger.error(f"Error pinging {hostname}: {str(e)}")
return float("inf")
def get_relays(relays_url: str, location_prefixes: List[str]) -> List[Relay]:
try:
response = requests.get(relays_url, timeout=5).json()
relays = []
for relay in response["wireguard"]["relays"]:
if (
any(
relay["location"].startswith(prefix) for prefix in location_prefixes
)
and relay["active"] is True
):
host = "{}.relays.mullvad.net".format(
relay["hostname"].replace("wg-", "wg-socks5-")
)
relays.append(
{
"hostname": host,
"location": relay["location"],
"socks5": f"SOCKS5 {host}:1080",
}
)
return relays
except Exception as e:
logger.error(f"Failed to fetch relays: {str(e)}")
return []
def measure_latency(
relays: List[Relay], ping_count: int, ping_timeout: int
) -> List[RelayResult]:
results = []
with ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for relay in relays:
futures.append(
(
relay,
executor.submit(
ping_host, relay["hostname"], ping_count, ping_timeout
),
)
)
processed = 0
total = len(relays)
for relay, future in futures:
latency = future.result()
results.append({"relay": relay, "latency": latency})
processed += 1
if latency == float("inf"):
logger.warning(f"[{processed}/{total}] {relay['hostname']}: timed out")
else:
logger.info(
f"[{processed}/{total}] {relay['hostname']}: {latency:.2f} ms"
)
results.sort(key=lambda x: x["latency"])
return results
def generate_pac(ranked_relays: List[RelayResult]) -> str:
pac_content = """function FindProxyForURL(url, host) {
var proxies = [
"""
for result in ranked_relays:
pac_content += f' "{result["relay"]["socks5"]}",\n'
pac_content += """ ];
var i = Math.floor(Math.random() * proxies.length);
return proxies[i];
}"""
return pac_content
def main() -> int:
parser = argparse.ArgumentParser(
description="Mullvad WireGuard Relay Latency Tester and PAC Generator"
)
parser.add_argument(
"--relays-url",
default="https://api.mullvad.net/public/relays/wireguard/v2",
help="URL for Mullvad relays",
)
parser.add_argument(
"--pac-file", default="mullvad_proxy.pac", help="Output PAC file"
)
parser.add_argument(
"--ping-count", default=5, type=int, help="Number of connectivity checks"
)
parser.add_argument(
"--ping-timeout",
default=1,
type=int,
help="Timeout (seconds) for each connectivity check",
)
parser.add_argument(
"--max-latency",
default=None,
type=float,
help="Ignore relays with latency above this threshold (ms)",
)
parser.add_argument(
"--location-prefixes",
default=[""],
nargs="+",
help="Location prefixes to filter relays",
)
args = parser.parse_args()
logger.info(f"Using location prefixes: {args.location_prefixes}")
logger.info("Fetching relays...")
relays = get_relays(args.relays_url, args.location_prefixes)
if not relays:
logger.error("No relays found!")
return 1
logger.info("Measuring latency...")
ranked_relays = measure_latency(relays, args.ping_count, args.ping_timeout)
working_relays = [r for r in ranked_relays if r["latency"] != float("inf")]
if args.max_latency is not None:
working_relays = [r for r in working_relays if r["latency"] <= args.max_latency]
logger.info(
f"Found {len(working_relays)} working relays out of {len(relays)} total."
)
if not working_relays:
logger.error("No working relays found under the specified conditions!")
return 2
logger.info("Sorted relays by latency (lowest first):")
for i, result in enumerate(working_relays):
logger.info(
f"{i + 1}. {result['relay']['hostname']}: {result['latency']:.2f} ms"
)
logger.info("Generating PAC file content...")
pac_content = generate_pac(working_relays)
logger.info(f"Saving PAC file to {args.pac_file}")
try:
with open(args.pac_file, "w", encoding="utf-8") as f:
f.write(pac_content)
logger.success(f"PAC file saved with {len(working_relays)} working relays.")
except Exception as e:
logger.error(f"Failed to save PAC file: {str(e)}")
return 3
return 0
if __name__ == "__main__":
start_time = time.time()
exit_code = 0
try:
exit_code = main()
except Exception as e:
logger.error(f"Script failed: {str(e)}")
exit_code = 4
finally:
logger.info(f"Total execution time: {time.time() - start_time:.2f} seconds")
sys.exit(exit_code)
|