subconverter 0.2.34

A more powerful utility to convert between proxy subscription format
Documentation
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use crate::models::{Proxy, SS_DEFAULT_GROUP};
use crate::utils::url::url_decode;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use serde_json::Value;

/// Parse a Shadowsocks link into a Proxy object
/// Based on the C++ implementation in explodeSS function
pub fn explode_ss(ss: &str, node: &mut Proxy) -> bool {
    // Check if the link starts with ss://
    if !ss.starts_with("ss://") {
        return false;
    }

    // Extract the content part after ss://
    let mut ss_content = ss[5..].to_string();
    // Replace "/?" with "?" like in C++ replaceAllDistinct
    ss_content = ss_content.replace("/?", "?");

    // Extract fragment (remark) if present
    let mut ps = String::new();
    if let Some(hash_pos) = ss_content.find('#') {
        ps = url_decode(&ss_content[hash_pos + 1..]);
        ss_content = ss_content[..hash_pos].to_string();
    }

    // Extract plugin and other query parameters
    let mut plugin = String::new();
    let mut plugin_opts = String::new();
    let mut group = SS_DEFAULT_GROUP.to_string();

    if let Some(query_pos) = ss_content.find('?') {
        let addition = ss_content[query_pos + 1..].to_string();
        ss_content = ss_content[..query_pos].to_string();

        // Parse query parameters
        for (key, value) in url::form_urlencoded::parse(addition.as_bytes()) {
            if key == "plugin" {
                let plugins = url_decode(&value);
                if let Some(semicolon_pos) = plugins.find(';') {
                    plugin = plugins[..semicolon_pos].to_string();
                    plugin_opts = plugins[semicolon_pos + 1..].to_string();
                } else {
                    plugin = plugins;
                }
            } else if key == "group" {
                if !value.is_empty() {
                    group = crate::utils::base64::url_safe_base64_decode(&value);
                }
            }
        }
    }

    // Parse the main part of the URL
    let method;
    let password;
    let server;
    let port;

    if ss_content.contains('@') {
        // SIP002 format (method:password@server:port)
        let parts: Vec<&str> = ss_content.split('@').collect();
        if parts.len() < 2 {
            return false;
        }

        let secret = parts[0];
        let server_port = parts[1];

        // Parse server and port
        let server_port_parts: Vec<&str> = server_port.split(':').collect();
        if server_port_parts.len() < 2 {
            return false;
        }
        server = server_port_parts[0].to_string();
        port = match server_port_parts[1].parse::<u16>() {
            Ok(p) => p,
            Err(_) => return false,
        };

        // Decode the secret part
        let decoded_secret = crate::utils::base64::url_safe_base64_decode(secret);
        let method_pass: Vec<&str> = decoded_secret.split(':').collect();
        if method_pass.len() < 2 {
            return false;
        }
        method = method_pass[0].to_string();
        password = method_pass[1..].join(":"); // In case password contains colons
    } else {
        // Legacy format
        let decoded = crate::utils::base64::url_safe_base64_decode(&ss_content);
        if decoded.is_empty() {
            return false;
        }

        // Parse method:password@server:port
        let parts: Vec<&str> = decoded.split('@').collect();
        if parts.len() < 2 {
            return false;
        }

        let method_pass = parts[0];
        let server_port = parts[1];

        // Parse method and password
        let method_pass_parts: Vec<&str> = method_pass.split(':').collect();
        if method_pass_parts.len() < 2 {
            return false;
        }
        method = method_pass_parts[0].to_string();
        password = method_pass_parts[1..].join(":"); // In case password contains colons

        // Parse server and port
        let server_port_parts: Vec<&str> = server_port.split(':').collect();
        if server_port_parts.len() < 2 {
            return false;
        }
        server = server_port_parts[0].to_string();
        port = match server_port_parts[1].parse::<u16>() {
            Ok(p) => p,
            Err(_) => return false,
        };
    }

    // Skip if port is 0
    if port == 0 {
        return false;
    }

    // Use server:port as remark if none provided
    if ps.is_empty() {
        ps = format!("{} ({})", server, port);
    }

    // Create the proxy
    *node = Proxy::ss_construct(
        &group,
        &ps,
        &server,
        port,
        &password,
        &method,
        &plugin,
        &plugin_opts,
        None,
        None,
        None,
        None,
        "",
    );

    true
}

/// Parse a SSD (Shadowsocks subscription) link into a vector of Proxy objects
pub fn explode_ssd(link: &str, nodes: &mut Vec<Proxy>) -> bool {
    // Check if the link starts with ssd://
    if !link.starts_with("ssd://") {
        return false;
    }

    // Extract the base64 part
    let encoded = &link[6..];

    // Decode base64
    let decoded = match STANDARD.decode(encoded) {
        Ok(bytes) => match String::from_utf8(bytes) {
            Ok(s) => s,
            Err(_) => return false,
        },
        Err(_) => return false,
    };

    // Parse as JSON
    let json: Value = match serde_json::from_str(&decoded) {
        Ok(json) => json,
        Err(_) => return false,
    };

    // Extract common fields
    let airport = json["airport"].as_str().unwrap_or("");
    let port = json["port"].as_u64().unwrap_or(0) as u16;
    let encryption = json["encryption"].as_str().unwrap_or("");
    let password = json["password"].as_str().unwrap_or("");

    // Extract servers
    if !json["servers"].is_array() {
        return false;
    }

    let servers = json["servers"].as_array().unwrap();

    for server in servers {
        let server_host = server["server"].as_str().unwrap_or("");
        let server_port = server["port"].as_u64().unwrap_or(port as u64) as u16;
        let server_encryption = server["encryption"].as_str().unwrap_or(encryption);
        let server_password = server["password"].as_str().unwrap_or(password);
        let server_remark = server["remarks"].as_str().unwrap_or("");
        let server_plugin = server["plugin"].as_str().unwrap_or("");
        let server_plugin_opts = server["plugin_options"].as_str().unwrap_or("");

        // Create formatted remark
        let formatted_remark = format!("{} - {}", airport, server_remark);

        // Create the proxy object
        let node = Proxy::ss_construct(
            SS_DEFAULT_GROUP,
            &formatted_remark,
            server_host,
            server_port,
            server_password,
            server_encryption,
            server_plugin,
            server_plugin_opts,
            None,
            None,
            None,
            None,
            "",
        );

        nodes.push(node);
    }

    !nodes.is_empty()
}

/// Parse Android Shadowsocks configuration into a vector of Proxy objects
pub fn explode_ss_android(content: &str, nodes: &mut Vec<Proxy>) -> bool {
    // Try to parse as JSON
    let json: Value = match serde_json::from_str(content) {
        Ok(json) => json,
        Err(_) => {
            println!(
                "Error parsing Android Shadowsocks configuration: {}",
                content
            );
            return false;
        }
    };

    // Check if it contains profiles
    if !json["configs"].is_array() && !json["proxies"].is_array() {
        return false;
    }

    // Determine which field to use
    let configs = if json["configs"].is_array() {
        json["configs"].as_array().unwrap()
    } else {
        json["proxies"].as_array().unwrap()
    };

    let mut index = nodes.len();

    for config in configs {
        // Extract fields
        let server = config["server"].as_str().unwrap_or("");
        if server.is_empty() {
            continue;
        }

        let port_num = config["server_port"].as_u64().unwrap_or(0) as u16;
        if port_num == 0 {
            continue;
        }

        let method = config["method"].as_str().unwrap_or("");
        let password = config["password"].as_str().unwrap_or("");

        // Get remark, try both "remarks" and "name" fields
        let remark = if config["remarks"].is_string() {
            config["remarks"].as_str().unwrap_or("").to_string()
        } else if config["name"].is_string() {
            config["name"].as_str().unwrap_or("").to_string()
        } else {
            format!("{} ({})", server, port_num)
        };

        // Get plugin and plugin_opts
        let plugin = config["plugin"].as_str().unwrap_or("");
        let plugin_opts = config["plugin_opts"].as_str().unwrap_or("");

        // Create the proxy object
        let mut node = Proxy::ss_construct(
            SS_DEFAULT_GROUP,
            &remark,
            server,
            port_num,
            password,
            method,
            plugin,
            plugin_opts,
            None,
            None,
            None,
            None,
            "",
        );

        node.id = index as u32;
        nodes.push(node);
        index += 1;
    }

    !nodes.is_empty()
}

/// Parse a Shadowsocks configuration file into a vector of Proxy objects
pub fn explode_ss_conf(content: &str, nodes: &mut Vec<Proxy>) -> bool {
    // Try to parse as JSON
    let json: Value = match serde_json::from_str(content) {
        Ok(json) => json,
        Err(_) => return false,
    };

    // Check for different configuration formats
    if json["configs"].is_array() || json["proxies"].is_array() {
        return explode_ss_android(content, nodes);
    }

    // Check for single server configuration
    if json["server"].is_string() && json["server_port"].is_u64() {
        let index = nodes.len();

        // Extract fields
        let server = json["server"].as_str().unwrap_or("");
        let port_num = json["server_port"].as_u64().unwrap_or(0) as u16;
        if server.is_empty() || port_num == 0 {
            return false;
        }

        let method = json["method"].as_str().unwrap_or("");
        let password = json["password"].as_str().unwrap_or("");

        // Get remark
        let remark = if json["remarks"].is_string() {
            json["remarks"].as_str().unwrap_or("")
        } else {
            &format!("{} ({})", server, port_num)
        };

        // Get plugin and plugin_opts
        let plugin = json["plugin"].as_str().unwrap_or("");
        let plugin_opts = json["plugin_opts"].as_str().unwrap_or("");

        // Create the proxy object
        let mut node = Proxy::ss_construct(
            SS_DEFAULT_GROUP,
            remark,
            server,
            port_num,
            password,
            method,
            plugin,
            plugin_opts,
            None,
            None,
            None,
            None,
            "",
        );

        node.id = index as u32;
        nodes.push(node);

        return true;
    }

    // Check for server list configuration
    if json["servers"].is_array() {
        let servers = json["servers"].as_array().unwrap();
        let mut index = nodes.len();

        for server_json in servers {
            // Extract fields
            let server = server_json["server"].as_str().unwrap_or("");
            let port_num = server_json["server_port"].as_u64().unwrap_or(0) as u16;
            if server.is_empty() || port_num == 0 {
                continue;
            }

            let method = server_json["method"].as_str().unwrap_or("");
            let password = server_json["password"].as_str().unwrap_or("");

            // Get remark
            let remark = if server_json["remarks"].is_string() {
                server_json["remarks"].as_str().unwrap_or("")
            } else {
                &format!("{} ({})", server, port_num)
            };

            // Get plugin and plugin_opts
            let plugin = server_json["plugin"].as_str().unwrap_or("");
            let plugin_opts = server_json["plugin_opts"].as_str().unwrap_or("");

            // Create the proxy object
            let mut node = Proxy::ss_construct(
                SS_DEFAULT_GROUP,
                remark,
                server,
                port_num,
                password,
                method,
                plugin,
                plugin_opts,
                None,
                None,
                None,
                None,
                "",
            );

            node.id = index as u32;
            nodes.push(node);
            index += 1;
        }

        return !nodes.is_empty();
    }

    false
}