shoes 0.3.1

A multi-protocol proxy server.
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
//! VISION stream implementation
//!
//! VisionStream wraps an IO stream and TLS session, allowing it to:
//! - Use TLS with VISION padding to hide protocol fingerprints
//! - Detect TLS-in-TLS scenarios by analyzing traffic patterns
//! - Switch to direct I/O mode, bypassing TLS for zero-copy performance

use bytes::{Buf, BytesMut};

use crate::crypto::CryptoConnection;
use futures::ready;
use std::io::{self, BufRead, Write};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

use crate::async_stream::AsyncStream;
use crate::crypto::feed_crypto_connection;
use crate::sync_adapter::{SyncReadAdapter, SyncWriteAdapter};
use crate::util::allocate_vec;

use super::tls_deframer::TlsDeframer;
use super::tls_fuzzy_deframer::{DeframeResult, FuzzyTlsDeframer};
use super::vision_filter::VisionFilter;
use super::vision_unpad::{UnpadCommand, UnpadResult, VisionUnpadder};

// TODO: consider combining with UnpadCommand
const COMMAND_CONTINUE: u8 = 0x00;
const COMMAND_END: u8 = 0x01;
const COMMAND_DIRECT: u8 = 0x02;

#[inline]
fn feed_and_process_crypto_connection(
    session: &mut CryptoConnection,
    data: &[u8],
) -> std::io::Result<usize> {
    feed_crypto_connection(session, data)?;
    Ok(session
        .process_new_packets()
        .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?
        .plaintext_bytes_to_read())
}

/// Current operating mode of the VISION stream
#[derive(Debug, PartialEq)]
enum VisionMode {
    /// Using TLS with VISION padding/unpadding
    PaddingTls,
    /// Regular TLS (padding ended, but still using TLS encryption)
    Tls,
    /// Direct I/O, TLS bypassed completely
    Direct,
}

impl std::fmt::Display for VisionMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VisionMode::PaddingTls => write!(f, "PaddingTls"),
            VisionMode::Tls => write!(f, "Tls"),
            VisionMode::Direct => write!(f, "Direct"),
        }
    }
}

pub struct VisionStream<IO> {
    /// The underlying transport stream (e.g., TcpStream)
    tcp: IO,

    /// rustls session for TLS encryption and decryption
    /// Used in PaddingTls and Tls mode
    session: CryptoConnection,

    /// Current READ operating mode (independent from write mode)
    read_mode: VisionMode,

    /// Current WRITE operating mode (independent from read mode)
    write_mode: VisionMode,

    /// Outer TLS deframer for read path
    /// Deframes TCP stream into complete TLS records before feeding to rustls
    /// Used in PaddingTls mode
    outer_read_deframer: Option<TlsDeframer>,

    /// Unpadding state machine for read path
    read_unpadder: VisionUnpadder,

    /// Inner TLS deframer for filtering read packets
    /// Used in PaddingTls mode
    inner_read_deframer: FuzzyTlsDeframer,

    /// Inner TLS deframer for filtering write packets
    /// Used in PaddingTls mode
    inner_write_deframer: FuzzyTlsDeframer,

    /// Whether this is the first write (includes UUID in padding)
    /// Used in PaddingTls mode
    write_first_packet: bool,

    /// User UUID for padding validation
    /// Used in PaddingTls mode
    user_uuid: [u8; 16],

    /// TLS pattern filter for inner TLS
    /// Used in PaddingTls mode
    filter: VisionFilter,

    /// Buffer for leftover data when switching modes or when output buffer is too small
    /// Used in PaddingTls mode
    pending_read: BytesMut,

    /// Whether we need to read VLESS response header (client-side only)
    /// Similar to shadowsocks's `is_initial_read` pattern
    /// Used in PaddingTls mode
    vless_response_pending: bool,

    /// Partial VLESS response data accumulated across multiple TLS records
    /// Used to handle cases where the response header is split across TLS records
    /// Used in PaddingTls mode
    partial_vless_response: BytesMut,

    /// Whether we need to send VLESS response header (server-side only)
    /// The response will be prepended to the first write as per the protocol
    /// Used in PaddingTls mode
    vless_response_to_send: bool,

    /// Flag indicating we should switch to direct mode on the NEXT write call
    /// Used in PaddingTls mode
    pending_direct_mode_switch: bool,

    /// Flag indicating we should switch to Tls mode on the NEXT write call
    /// Used in PaddingTls mode
    pending_tls_mode_switch: bool,

    /// Reusable buffer for TLS read operations (TCP → read_tls → decrypt)
    /// Used in PaddingTls mode
    tls_read_buffer: Vec<u8>,

    /// Buffer for plaintext data waiting to be written to the TLS session buffer
    /// When the rustls Writer buffer fills (write length 0), we store the remainder here
    /// Used in PaddingTls mode - drained immediately before switching modes
    pending_plain_writes: BytesMut,

    /// Caches whether we've hit EOF when reading
    /// Used in PaddingTls and Tls mode
    is_read_eof: bool,
}

impl<IO> VisionStream<IO>
where
    IO: AsyncRead + AsyncWrite + Unpin,
{
    /// Create a new VisionStream for server-side (inbound) connections with VLESS response writing
    pub fn new_server(
        tcp: IO,
        session: CryptoConnection,
        user_uuid: [u8; 16],
        initial_read_data: &[u8],
    ) -> std::io::Result<Self> {
        if !session.is_server() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "VisionStream::new_server requires a server-side connection",
            ));
        }

        let mut stream = Self::new_common(
            tcp, session, user_uuid, false, // vless_response_pending
            true,  // vless_response_to_send
        );

        // feed in the initial read data that came from reading the VLESS request
        stream.feed_initial_read_data(initial_read_data)?;
        // read all the remaining plaintext data from the session since we start directly
        // with TCP reads in poll_read_padding_tls
        stream.feed_initial_session_data()?;

        Ok(stream)
    }

    /// Create a new VisionStream for client-side connections with VLESS response handling
    pub fn new_client(tcp: IO, session: CryptoConnection, user_uuid: [u8; 16]) -> Self {
        if !session.is_client() {
            panic!("VisionStream::new_client requires a client-side connection");
        }

        Self::new_common(
            tcp, session, user_uuid, true,  // vless_response_pending
            false, // vless_response_to_send
        )
    }

    fn new_common(
        tcp: IO,
        session: CryptoConnection,
        user_uuid: [u8; 16],
        vless_response_pending: bool,
        vless_response_to_send: bool,
    ) -> Self {
        Self {
            tcp,
            session,
            // this should be somewhat smaller than TLS_MAX_RECORD_SIZE when used with session.read_tls,
            // else we will hit "message buffer full" (see other comment) - because if we set it at
            // TLS_MAX_RECORD_SIZE, and a small record is read first, there can be a large partial record
            // left in the buffer and then prevoius_record_size + TLS_MAX_RECORD_SIZE > TLS_MAX_RECORD_SIZE
            // will trigger the error.
            tls_read_buffer: allocate_vec(8192),
            read_mode: VisionMode::PaddingTls,
            write_mode: VisionMode::PaddingTls,
            outer_read_deframer: Some(TlsDeframer::new()),
            inner_read_deframer: FuzzyTlsDeframer::new(),
            inner_write_deframer: FuzzyTlsDeframer::new(),
            read_unpadder: VisionUnpadder::new(user_uuid),
            write_first_packet: true,
            user_uuid,
            filter: VisionFilter::new(),
            pending_read: BytesMut::new(),
            vless_response_pending,
            partial_vless_response: BytesMut::new(),
            vless_response_to_send,
            pending_direct_mode_switch: false,
            pending_tls_mode_switch: false,
            pending_plain_writes: BytesMut::new(),
            is_read_eof: false,
        }
    }

    /// Feed TLS plaintext buffered before the Vision handoff. An earlier chunk may
    /// already have ended padding, so subsequent chunks must follow the new mode.
    fn feed_initial_read_data(&mut self, data: &[u8]) -> std::io::Result<()> {
        if data.is_empty() {
            return Ok(());
        }

        log::debug!(
            "VISION: Feeding {} initial decrypted bytes in {} mode",
            data.len(),
            self.read_mode
        );

        match self.read_mode {
            VisionMode::PaddingTls => self.handle_padded_bytes(data)?,
            VisionMode::Tls | VisionMode::Direct => self.pending_read.extend_from_slice(data),
        }

        Ok(())
    }

    // Read all the available plaintext data from the session.
    // This should only be necessary for server streams since a read occurred in order to read the
    // VLESS request before the session is passed to VisionStream.
    fn feed_initial_session_data(&mut self) -> std::io::Result<()> {
        let plaintext_len = self
            .session
            .process_new_packets()
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?
            .plaintext_bytes_to_read();
        let mut decrypted = Vec::with_capacity(plaintext_len);

        let mut reader = self.session.reader();
        let mut i = 0;
        while i < plaintext_len {
            match reader.fill_buf() {
                Ok(buf) => {
                    let len = buf.len();
                    if len == 0 {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "TLS session filled buffer with zero bytes",
                        ));
                    }
                    decrypted.extend_from_slice(buf);
                    reader.consume(len);
                    log::debug!("VISION: Filled more unparsed data of length {}", len);
                    i += len;
                }
                Err(e) => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("failed to read TLS session: {e}"),
                    ));
                }
            }
        }

        self.feed_initial_read_data(&decrypted)
    }

    fn switch_read_to_direct_mode(&mut self) -> io::Result<()> {
        if self.read_mode != VisionMode::PaddingTls {
            return Err(std::io::Error::other(format!(
                "switch_read_to_direct_mode called from mode {}",
                self.read_mode
            )));
        }

        log::debug!(
            "VISION READ: Switching to direct copy mode (asymmetric - write side may still use padding)"
        );

        // Set read mode to Direct FIRST to avoid inconsistent state
        self.read_mode = VisionMode::Direct;

        log::debug!("VISION READ: Switched to direct mode");

        self.post_padding_cleanup();

        Ok(())
    }

    fn switch_read_to_tls_mode(&mut self) -> io::Result<()> {
        if self.read_mode != VisionMode::PaddingTls {
            return Err(std::io::Error::other(format!(
                "switch_read_to_tls_mode called from mode {}",
                self.read_mode
            )));
        }

        log::debug!("VISION READ: Switching to Tls mode (no XTLS support)");

        // Set read mode to Tls
        self.read_mode = VisionMode::Tls;

        self.post_padding_cleanup();

        Ok(())
    }

    /// Switch WRITE side from TLS mode to direct I/O mode
    /// This doesn't need to preserve any data, just updates the mode
    fn switch_write_to_direct_mode(&mut self) -> io::Result<()> {
        if self.write_mode != VisionMode::PaddingTls {
            return Err(std::io::Error::other(format!(
                "switch_write_to_direct_mode called from mode {}",
                self.write_mode
            )));
        }

        log::debug!(
            "VISION WRITE: Switching to direct copy mode (asymmetric - read side may still use padding)"
        );

        // Set write mode to Direct
        self.write_mode = VisionMode::Direct;

        self.post_padding_cleanup();

        Ok(())
    }

    /// Switch WRITE side from PaddingTls to Tls mode
    /// This happens when XTLS is not supported or TLS 1.2 is detected
    fn switch_write_to_tls_mode(&mut self) -> io::Result<()> {
        if self.write_mode != VisionMode::PaddingTls {
            return Err(std::io::Error::other(format!(
                "switch_write_to_tls_mode called from mode {}",
                self.write_mode
            )));
        }

        log::debug!("VISION WRITE: Switching to Tls mode (no XTLS support)");

        // Set write mode to Tls
        self.write_mode = VisionMode::Tls;

        self.post_padding_cleanup();

        Ok(())
    }

    fn post_padding_cleanup(&mut self) {
        if self.read_mode == VisionMode::PaddingTls || self.write_mode == VisionMode::PaddingTls {
            return;
        }

        log::debug!("VISION: Cleaning up after read and write padding mode switch");

        // TODO: consider using an Option for all PaddingTls fields instead
        self.inner_read_deframer.deallocate();
        self.inner_write_deframer.deallocate();
        self.tls_read_buffer = Vec::new();
        self.pending_plain_writes = BytesMut::new();
    }

    /// Drain pending plaintext writes to TLS session buffer.
    ///
    /// Returns the number of bytes successfully written to the session.
    /// - If returned > 0: progress was made, wants_write() should be true
    /// - If returned == 0 and pending_plain_writes not empty: no progress (buffer full)
    /// - If returned == 0 and pending_plain_writes empty: nothing to do
    fn drain_pending_plain_writes(&mut self) -> io::Result<usize> {
        if self.pending_plain_writes.is_empty() {
            return Ok(0);
        }

        let initial_len = self.pending_plain_writes.len();

        // Try to write pending plaintext to TLS session
        while !self.pending_plain_writes.is_empty() {
            match self.session.writer().write(&self.pending_plain_writes) {
                Ok(0) => {
                    // Session buffer full
                    break;
                }
                Ok(n) => {
                    self.pending_plain_writes.advance(n);
                }
                Err(e) => return Err(e),
            }
        }

        let written = initial_len - self.pending_plain_writes.len();
        if written > 0 {
            log::debug!(
                "VISION WRITE: Drained {} plaintext bytes to session ({} remaining)",
                written,
                self.pending_plain_writes.len()
            );
        }
        Ok(written)
    }

    /// Drain all pending writes in PaddingTls mode: plain → TLS → TCP
    ///
    /// This drains the write pipeline in priority order:
    /// 1. TLS session → TCP socket (highest priority, creates space in session)
    /// 2. Plain buffer → TLS session (writes to session)
    ///
    /// Returns Poll::Ready(Ok(())) when all buffers are fully drained
    /// Returns Poll::Pending if TCP blocks (backpressure - nothing else can make progress)
    fn drain_all_writes_padding(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        loop {
            // Drain TLS session to TCP if there's data to send
            if self.session.wants_write() {
                match self.write_tls_direct(cx) {
                    Poll::Ready(Ok(0)) => return Poll::Ready(Err(io::ErrorKind::WriteZero.into())),
                    Poll::Ready(Ok(_)) => {
                        // Wrote some data, freed up space in session buffer. Loop to continue.
                        continue;
                    }
                    Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                    Poll::Pending => {
                        // TCP blocked - waker is registered, return Pending
                        return Poll::Pending;
                    }
                }
            }

            // Drain plaintext buffer to TLS session
            if !self.pending_plain_writes.is_empty() {
                let written = self.drain_pending_plain_writes()?;
                if written > 0 {
                    // Made progress - session now has data, wants_write() should be true
                    continue;
                } else {
                    // No progress: session buffer was already full but wants_write() was false.
                    // This shouldn't happen - if buffer is full, there should be data to send.
                    log::error!(
                        "DRAIN: stuck - couldn't write to session but wants_write=false, pending={}",
                        self.pending_plain_writes.len()
                    );
                    return Poll::Ready(Err(io::Error::other(
                        "drain stuck: session buffer full but wants_write is false",
                    )));
                }
            }

            // Both empty - done
            return Poll::Ready(Ok(()));
        }
    }

    /// Drain all pending writes in Tls mode
    ///
    /// This is simpler than PaddingTls mode because `pending_plain_writes` is no longer used.
    ///
    /// Returns Poll::Ready(Ok(())) when fully drained
    /// Returns Poll::Pending if TCP blocks
    fn drain_all_writes_tls(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        // Drain TLS session output directly to TCP
        while self.session.wants_write() {
            if ready!(self.write_tls_direct(cx))? == 0 {
                return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
            }
        }

        Poll::Ready(Ok(()))
    }

    /// Write data to TLS session, handling buffer full by saving to pending buffer
    /// Used in PaddingTls mode
    fn write_to_session(&mut self, data: &[u8]) -> io::Result<()> {
        if !self.pending_plain_writes.is_empty() {
            // If there's already pending data, just append to it
            // (don't try to write, as that would require cx for polling)
            self.pending_plain_writes.extend_from_slice(data);
            return Ok(());
        }

        let mut written = 0;
        while written < data.len() {
            let n = self.session.writer().write(&data[written..])?;
            if n == 0 {
                // Session buffer full, save remainder
                log::debug!(
                    "VISION WRITE: Session buffer full, saving {} bytes to pending",
                    data.len() - written
                );
                self.pending_plain_writes
                    .extend_from_slice(&data[written..]);
                return Ok(());
            }
            written += n;
        }

        Ok(())
    }

    /// Write TLS session output directly to TCP stream
    /// Returns the number of bytes written from TLS session to TCP
    fn write_tls_direct(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
        let mut writer = SyncWriteAdapter {
            io: &mut self.tcp,
            cx,
        };

        // Write TLS output DIRECTLY to TCP (zero intermediate copies)
        match self.session.write_tls(&mut writer) {
            Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Poll::Pending,
            result => Poll::Ready(result),
        }
    }

    /// Write data in Tls mode
    fn poll_write_tls(&mut self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
        let mut pos = 0;

        while pos < buf.len() {
            let mut would_block = false;

            // Write plaintext to TLS session
            match self.session.writer().write(&buf[pos..]) {
                Ok(n) => pos += n,
                Err(e) => return Poll::Ready(Err(e)),
            };

            // Drain TLS output to TCP stream
            while self.session.wants_write() {
                match self.write_tls_direct(cx) {
                    Poll::Ready(Ok(0)) | Poll::Pending => {
                        would_block = true;
                        break;
                    }
                    Poll::Ready(Ok(_)) => (),
                    Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
                }
            }

            return match (pos, would_block) {
                (0, true) => Poll::Pending,
                (n, true) => Poll::Ready(Ok(n)), // Partial write
                (_, false) => continue,          // Keep writing
            };
        }

        Poll::Ready(Ok(pos))
    }

    /// Read the VLESS response header from the TLS session
    ///
    /// The VLESS response consists of:
    /// - 1 byte: version (must be 0)
    /// - 1 byte: addon length
    /// - N bytes: addon data (if addon_length > 0)
    ///
    /// This is called lazily on the first read when vless_response_pending is true.
    /// Uses packetization to feed TLS records one at a time to avoid bad MAC errors.
    ///
    /// Returns any unused data that came after the response
    fn poll_read_vless_response(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<BytesMut>> {
        log::debug!(
            "VLESS: poll_read_vless_response called, partial_vless_response has {} bytes",
            self.partial_vless_response.len()
        );

        loop {
            // Always read from TCP to feed the deframer
            let mut read_buf = ReadBuf::new(&mut self.tls_read_buffer);
            match ready!(Pin::new(&mut self.tcp).poll_read(cx, &mut read_buf)) {
                Ok(()) => {}
                Err(e) => return Poll::Ready(Err(e)),
            };

            let tcp_bytes = read_buf.filled();

            if tcp_bytes.is_empty() {
                return Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "Connection closed while reading VLESS response",
                )));
            }

            log::debug!(
                "VLESS: Read {} bytes from TCP for response header",
                tcp_bytes.len()
            );

            // Feed to outer read deframer
            self.outer_read_deframer
                .as_mut()
                .expect("outer_read_deframer must exist in PaddingTls mode")
                .feed(tcp_bytes);

            // We have to handle all packets and drain the outer_read_deframer because
            // poll_read_padded_tls() will always read from the TCP and assume there's outstanding
            // data.
            // We don't have to worry about consuming some data post-Direct command because the TLS
            // flow is one-directional atm and it's not possible to complete a handshake.
            // If the peer sends a Direct command without handshake completing, this will error out
            // when we feed the TLS record to the session.
            let tls_records = self
                .outer_read_deframer
                .as_mut()
                .expect("outer_read_deframer must exist in PaddingTls mode")
                .next_records()?;

            for tls_record in tls_records.into_iter() {
                // Feed single TLS record to session
                let plaintext_len =
                    feed_and_process_crypto_connection(&mut self.session, tls_record.as_ref())?;

                // Access the decrypted buffer and accumulate into partial_vless_response
                let mut reader = self.session.reader();

                let mut i = 0;
                while i < plaintext_len {
                    let decrypted_buf = match reader.fill_buf() {
                        Ok(buf) => buf,
                        Err(e) => return Poll::Ready(Err(e)),
                    };

                    if decrypted_buf.is_empty() {
                        return Poll::Ready(Err(io::Error::other(
                            "no plaintext data when some is available",
                        )));
                    }

                    // Accumulate decrypted data into partial buffer
                    self.partial_vless_response.extend_from_slice(decrypted_buf);

                    let consumed_len = decrypted_buf.len();
                    reader.consume(consumed_len);
                    i += consumed_len;
                }
            }

            log::debug!(
                "VLESS: Accumulated vless response with {} bytes",
                self.partial_vless_response.len()
            );

            // Try to parse the VLESS response from accumulated data
            if self.partial_vless_response.len() < 2 {
                // Need at least 2 bytes for header, try to read from the TCP stream again
                continue;
            }

            // Read the 2-byte header
            let version = self.partial_vless_response[0];
            let addon_length = self.partial_vless_response[1];

            // Validate version
            if version != 0 {
                return Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Invalid VLESS response version: {}", version),
                )));
            }

            // Check if we have enough data for the full response
            let total_response_len = 2 + addon_length as usize;
            if self.partial_vless_response.len() < total_response_len {
                // Need more data - read more TCP
                continue;
            }

            // We have the complete VLESS response! Consume it from the buffer
            self.partial_vless_response.advance(total_response_len);

            log::debug!(
                "VLESS: Successfully parsed {} byte response header (version={}, addon_length={}), {} bytes remaining in buffer",
                total_response_len,
                version,
                addon_length,
                self.partial_vless_response.len()
            );

            // If there's any remaining data in partial buffer, it belongs to the actual payload
            let remaining_data = std::mem::take(&mut self.partial_vless_response);
            return Poll::Ready(Ok(remaining_data));
        }
    }

    fn poll_read_padding_tls(
        &mut self,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        if self.is_read_eof {
            return Poll::Ready(Ok(()));
        }

        loop {
            // Read from TCP to feed the deframer.
            // At this point, there is no data ready in neither the session or the outer read
            // deframer.
            let mut read_buf = ReadBuf::new(&mut self.tls_read_buffer);
            match ready!(Pin::new(&mut self.tcp).poll_read(cx, &mut read_buf)) {
                Ok(()) => {}
                Err(e) => return Poll::Ready(Err(e)),
            };

            let tcp_bytes = read_buf.filled();

            if tcp_bytes.is_empty() {
                log::debug!("VISION READ: TCP connection EOF in PaddingTls mode");
                self.is_read_eof = true;
                return Poll::Ready(Ok(()));
            }

            log::debug!("VISION READ: Read {} bytes from TCP", tcp_bytes.len());

            // Feed to outer TLS deframer
            self.outer_read_deframer
                .as_mut()
                .expect("outer_read_deframer must exist in PaddingTls mode")
                .feed(tcp_bytes);

            // Process TLS records one at a time
            loop {
                let tls_record = match self
                    .outer_read_deframer
                    .as_mut()
                    .expect("outer_read_deframer must exist in PaddingTls mode")
                    .next_record()?
                {
                    Some(record) => record,
                    None => {
                        log::debug!(
                            "VISION READ: No more complete TLS records in deframer, need more TCP data"
                        );
                        break; // Need more TCP data
                    }
                };

                log::debug!(
                    "VISION READ: Processing {} byte TLS record",
                    tls_record.len()
                );

                // Feed single TLS record to session
                let plaintext_len =
                    feed_and_process_crypto_connection(&mut self.session, tls_record.as_ref())?;

                if plaintext_len == 0 {
                    continue; // Process next TLS record
                }

                let mut reader = self.session.reader();

                let mut decrypted = Vec::with_capacity(plaintext_len);
                let mut i = 0;
                while i < plaintext_len {
                    let decrypted_part = match reader.fill_buf() {
                        Ok(buf) => buf,
                        Err(e) => {
                            // TODO: better error eg expected available plaintext but got error
                            return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, e)));
                        }
                    };

                    let part_len = decrypted_part.len();
                    decrypted.extend_from_slice(decrypted_part);
                    reader.consume(part_len);
                    i += part_len;
                }

                log::debug!("VISION READ: Got {} decrypted bytes", decrypted.len());
                self.handle_padded_bytes(&decrypted)?;

                // If the mode changed, the outer read deframer has been consumed and
                // we should return any pending read data and use the new mode's read function
                match self.read_mode {
                    VisionMode::PaddingTls => {
                        // Need more TCP data, loop back to read
                    }
                    VisionMode::Tls => {
                        if !self.pending_read.is_empty() {
                            let len = buf.remaining().min(self.pending_read.len());
                            buf.put_slice(&self.pending_read[..len]);
                            self.pending_read.advance(len);
                            return Poll::Ready(Ok(()));
                        }
                        return self.poll_read_tls(cx, buf);
                    }
                    VisionMode::Direct => {
                        if !self.pending_read.is_empty() {
                            let len = buf.remaining().min(self.pending_read.len());
                            buf.put_slice(&self.pending_read[..len]);
                            self.pending_read.advance(len);
                            return Poll::Ready(Ok(()));
                        }
                        return Pin::new(&mut self.tcp).poll_read(cx, buf);
                    }
                }
            }

            // Finished iterating through all TLS records, return data if we have any, else loop
            // back to read more TCP data
            if !self.pending_read.is_empty() {
                let len = buf.remaining().min(self.pending_read.len());
                buf.put_slice(&self.pending_read[..len]);
                self.pending_read.advance(len);
                return Poll::Ready(Ok(()));
            }
        }
    }

    fn handle_padded_bytes(&mut self, decrypted: &[u8]) -> std::io::Result<()> {
        // Feed newly decrypted bytes to the unpadder.
        // All data should be consumed from the rustls session, as any actual content
        // will eventually be returned by the unpadder.
        // The unpadder maintains internal state for partial parsing
        let UnpadResult {
            content: mut unpadded,
            command: maybe_command,
        } = self.read_unpadder.unpad(decrypted)?;

        log::debug!("VISION READ: Unpadded to {} bytes", unpadded.len());

        if !unpadded.is_empty() && self.filter.is_filtering() {
            // Feed to deframer
            self.inner_read_deframer.feed(&unpadded);

            // Process all complete TLS packets
            loop {
                match self.inner_read_deframer.next_record() {
                    Ok(DeframeResult::TlsRecord(record)) => {
                        self.filter.filter_record(&record);
                        if !self.filter.is_filtering() {
                            break;
                        }
                    }
                    Ok(DeframeResult::UnknownPrefix(prefix)) => {
                        // Skip unknown prefix bytes (e.g., VLESS headers from proxy chain)
                        if prefix.is_empty() {
                            return Err(io::Error::other("FuzzyTlsDeframer returned empty prefix"));
                        }
                        if prefix.len() > 512 {
                            log::warn!(
                                "VISION READ: Unusually large prefix discarded: {} bytes",
                                prefix.len()
                            );
                        }
                        log::debug!("VISION READ: Skipped {} byte prefix", prefix.len());

                        // Decrement once for this chunk
                        self.filter.decrement_filter_count();

                        // Continue processing
                    }
                    Ok(DeframeResult::NeedData) => break, // Need more data
                    Err(e) => {
                        // Invalid TLS packet - stop filtering
                        // This only occurs if we've already seen valid TLS records, and
                        // then encountered invalid ones.
                        log::error!(
                            "VISION READ: Read invalid TLS data after valid records - stopping filtering: {}",
                            e
                        );
                        self.filter
                            .stop_filtering("read invalid TLS data".to_string());
                        break;
                    }
                }
            }
        }

        match maybe_command {
            Some(UnpadCommand::Direct) => {
                log::debug!(
                    "VISION READ: Received DIRECT command with {} bytes",
                    unpadded.len()
                );

                // The unpadded data already contains:
                // 1. The Direct command content
                // 2. Any remaining bytes after the padding (already appended by unpadder)

                // Extract remaining data from outer read deframer (raw TCP data in Direct mode)
                let remaining = self
                    .outer_read_deframer
                    .take()
                    .expect("outer_read_deframer must exist")
                    .into_remaining_data();

                if !remaining.is_empty() {
                    log::debug!(
                        "VISION READ: Extracted {} bytes from deframer as raw data",
                        remaining.len()
                    );
                    unpadded.extend_from_slice(&remaining);
                }

                self.pending_read.extend_from_slice(&unpadded);

                self.switch_read_to_direct_mode()?;
            }
            Some(UnpadCommand::End) => {
                log::debug!("VISION READ: Received END command, switching to Tls mode");

                // The `unpadded` data is already decrypted, store it in pending_read to be
                // returned
                if !unpadded.is_empty() {
                    log::debug!(
                        "VISION READ: Storing {} decrypted bytes in pending_read (End command - already decrypted)",
                        unpadded.len()
                    );
                    self.pending_read.extend_from_slice(&unpadded);
                }

                // Process the remaining data from the outer read deframer.
                // Previously we called into_remaining_data and fed it all at once to
                // feed_and_process_crypto_connection, but if there was too much outstanding
                // data, we hit "message buffer full" at
                // https://github.com/rustls/rustls/blob/58fbe9e7ad91951a7df148c2854f57db728a717c/rustls/src/msgs/deframer/buffers.rs#L235

                let mut outer_read_deframer = self
                    .outer_read_deframer
                    .take()
                    .expect("outer_read_deframer must exist");

                while let Some(record) = outer_read_deframer.next_record()? {
                    // Feed the encrypted TLS records to the session
                    let plaintext_len =
                        feed_and_process_crypto_connection(&mut self.session, &record)?;

                    if plaintext_len > 0 {
                        // Extract the decrypted data
                        let mut reader = self.session.reader();

                        // Read all available decrypted data, possibly in multiple chunks
                        let mut total_read = 0;
                        while total_read < plaintext_len {
                            let chunk = match reader.fill_buf() {
                                Ok(buf) => buf,
                                Err(e) => {
                                    return Err(io::Error::new(io::ErrorKind::InvalidData, e));
                                }
                            };

                            let chunk_len = chunk.len();
                            self.pending_read.extend_from_slice(chunk);
                            reader.consume(chunk_len);
                            total_read += chunk_len;
                        }

                        log::debug!(
                            "VISION READ: Decrypted {} bytes from deframer remaining data (End command)",
                            total_read
                        );
                    }
                }

                let remaining = outer_read_deframer.into_remaining_data();

                // The `remaining` data from the deframer is ENCRYPTED TLS record bytes
                // We need to feed it to the TLS session for decryption
                if !remaining.is_empty() {
                    // This should only be a partial TLS record so there should be no new plaintext
                    // to read
                    let plaintext_len =
                        feed_and_process_crypto_connection(&mut self.session, &remaining)?;
                    assert!(plaintext_len == 0);
                }

                // Switch to Tls mode - End command means: stop padding, continue normal relay through outer TLS
                self.switch_read_to_tls_mode()?;
            }
            Some(UnpadCommand::Continue) => {
                self.pending_read.extend_from_slice(&unpadded);
            }
            None => {
                self.pending_read.extend_from_slice(&unpadded);
            }
        }
        Ok(())
    }

    fn poll_read_tls(
        &mut self,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        // Check if rustls buffer has decrypted data available first
        {
            let mut reader = self.session.reader();
            match reader.fill_buf() {
                Ok(available) if !available.is_empty() => {
                    // Copy directly from rustls buffer to user buffer (single copy)
                    let len = buf.remaining().min(available.len());
                    buf.put_slice(&available[..len]);
                    reader.consume(len);
                    // If we didn't consume all data, it stays in rustls buffer for next read
                    return Poll::Ready(Ok(()));
                }
                Ok(_) => {
                    // Empty buffer, fall through to slow path
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // No data available, fall through to slow path
                }
                Err(e) => return Poll::Ready(Err(e)),
            }
        }

        if self.is_read_eof {
            return Poll::Ready(Ok(()));
        }

        // No data in rustls buffer, need to read from TCP
        // To prevent "message buffer full", we use a SyncReadAdapter to allow
        // rustls to decide how much to read from TCP, versus reading to a buffer
        // and then feeding like in PaddingTls mode.
        //
        // In read_tls, rustls will internally:
        // 1. Check if it has buffer space via prepare_read()
        // 2. Read only up to 4KB at a time
        // 3. Prevent "message buffer full" by reading less
        let mut reader = SyncReadAdapter {
            io: &mut self.tcp,
            cx,
        };

        loop {
            match self.session.read_tls(&mut reader) {
                Ok(n) => {
                    if n == 0 {
                        log::debug!("VISION READ: TCP connection EOF in Tls mode");
                        self.is_read_eof = true;
                        return Poll::Ready(Ok(()));
                    }

                    log::debug!("VISION READ: Read {} bytes from TCP via rustls", n);

                    // Process the encrypted data
                    let plaintext_len = self
                        .session
                        .process_new_packets()
                        .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?
                        .plaintext_bytes_to_read();

                    if plaintext_len == 0 {
                        // No plaintext yet, need more TCP data
                        continue;
                    }

                    // Extract plaintext from rustls and return it
                    let mut reader = self.session.reader();
                    match reader.fill_buf() {
                        Ok(available) => {
                            // TODO: this should probably be a debug_assert!
                            if available.is_empty() {
                                return Poll::Ready(Err(io::Error::new(
                                    io::ErrorKind::UnexpectedEof,
                                    "Read zero bytes when plaintext is available",
                                )));
                            }
                            let len = buf.remaining().min(available.len());
                            buf.put_slice(&available[..len]);
                            reader.consume(len);
                            return Poll::Ready(Ok(()));
                        }
                        Err(e) => {
                            return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, e)));
                        }
                    }
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                    return Poll::Pending;
                }
                Err(e) => {
                    return Poll::Ready(Err(e));
                }
            }
        }
    }

    fn poll_write_padding_tls(
        &mut self,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        if self.vless_response_to_send {
            log::debug!("VISION WRITE: Sending VLESS response to TLS session");

            // VLESS response header: [version=0, addon_length=0]
            const VLESS_RESPONSE: [u8; 2] = [0, 0];

            // Write VLESS response to TLS session (will be encrypted)
            self.write_to_session(&VLESS_RESPONSE)?;

            // Clear flag so we don't send it again
            self.vless_response_to_send = false;
        }

        // Drain all pending writes - this must be done before mode switch
        // as the session could contain the DIRECT/END packet that triggered the mode switch flag,
        // and because we no longer use `pending_plain_writes` afterwards.
        if !self.pending_plain_writes.is_empty() || self.session.wants_write() {
            ready!(self.drain_all_writes_padding(cx))?;
        }

        if self.pending_direct_mode_switch {
            log::debug!("VISION WRITE: Switching to direct mode (flag set by previous write)");
            self.pending_direct_mode_switch = false;
            self.switch_write_to_direct_mode()?;
            return Pin::new(&mut self.tcp).poll_write(cx, buf);
        }

        if self.pending_tls_mode_switch {
            log::debug!("VISION WRITE: Switching to Tls mode (flag set by previous write)");
            self.pending_tls_mode_switch = false;
            self.switch_write_to_tls_mode()?;
            return self.poll_write_tls(cx, buf);
        }

        // Feed write buffer to inner deframer and check for ApplicationData
        let existing_inner_len = self.inner_write_deframer.pending_bytes();
        self.inner_write_deframer.feed(buf);

        // Process all complete TLS records in the buffer
        let mut processed_len = 0;
        loop {
            match self.inner_write_deframer.next_record() {
                Ok(DeframeResult::TlsRecord(record)) => {
                    processed_len += record.len();

                    // Feed to filter for TLS pattern detection
                    self.filter.filter_record(&record);

                    // Check if this packet is ApplicationData to switch to Direct mode
                    let is_app_data = self.filter.is_tls() && record.len() >= 3
                        && record[0] == 0x17  // ApplicationData
                        && record[1] == 0x03;

                    // Check if filtering ended and we are not TLS 1.2 or above
                    let non_tls_filtering_ended = !is_app_data
                        && !self.filter.is_filtering()
                        && !self.filter.is_tls12_or_above();

                    if is_app_data || non_tls_filtering_ended {
                        if is_app_data {
                            log::debug!(
                                "VISION WRITE: Detected ApplicationData in {} byte packet",
                                record.len()
                            );
                        } else {
                            log::debug!("VISION WRITE: Filtering ended, not TLS 1.2 or above");
                        }

                        // DIRECT or END command
                        // Toggle mode switch flag, if `non_tls_filtering_ended`, it never supports XTLS
                        let command = if self.filter.supports_xtls() {
                            self.pending_direct_mode_switch = true;
                            COMMAND_DIRECT
                        } else {
                            self.pending_tls_mode_switch = true;
                            COMMAND_END
                        };

                        let final_padded_packet = if self.write_first_packet {
                            self.write_first_packet = false;
                            super::vision_pad::pad_with_uuid_and_command(
                                &record,
                                &self.user_uuid,
                                command,
                                true, // is_tls
                            )
                        } else {
                            super::vision_pad::pad_with_command(
                                &record, command, true, // is_tls
                            )
                        };

                        self.write_to_session(&final_padded_packet)?;

                        // this must be true because else we would have a successful next_record call on previous iteration
                        assert!(processed_len > existing_inner_len);

                        // Drain and handle result
                        match self.drain_all_writes_padding(cx) {
                            Poll::Ready(Ok(())) => {
                                // Fully drained, continue
                            }
                            Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                            Poll::Pending => {
                                // Still draining
                            }
                        }

                        // Clear deframer since caller will re-feed remaining data
                        self.inner_write_deframer.clear();

                        // tell caller to resend the next packets after the mode switch
                        return Poll::Ready(Ok(processed_len - existing_inner_len));
                    }

                    // if we got here, it's:
                    // - a non-TLS packet of data and we're still filtering
                    // - a TLS record that is not app data, and we have not yet seen app data, even
                    //   though we might be done filtering
                    // .. so we need to continue padding
                    // ref: https://github.com/XTLS/Xray-core/blob/9f5dcb15910aadc7ef450514747576827a389853/proxy/proxy.go#L371

                    let padded_packet = if self.write_first_packet {
                        self.write_first_packet = false;
                        super::vision_pad::pad_with_uuid_and_command(
                            &record,
                            &self.user_uuid,
                            COMMAND_CONTINUE,
                            self.filter.is_tls(),
                        )
                    } else {
                        super::vision_pad::pad_with_command(
                            &record,
                            COMMAND_CONTINUE,
                            self.filter.is_tls(),
                        )
                    };

                    self.write_to_session(&padded_packet)?;
                    match self.drain_all_writes_padding(cx) {
                        Poll::Pending => {
                            let unprocessed_buf_len =
                                buf.len() - (processed_len - existing_inner_len);
                            // sanity check
                            assert!(
                                self.inner_write_deframer.pending_bytes() == unprocessed_buf_len
                            );
                            // clear since the user will re-feed
                            self.inner_write_deframer.clear();
                            return Poll::Ready(Ok(processed_len - existing_inner_len));
                        }
                        Poll::Ready(Ok(())) => {
                            // continue since it drained
                        }
                        Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                    }
                }
                Ok(DeframeResult::NeedData) => {
                    // TODO: There's a theoretical edge case where non-TLS data ends with bytes
                    // that look like a valid TLS record prefix (e.g., [0x16, 0x03, 0x03]).
                    // The deframer would hold onto these bytes waiting for more data to
                    // complete the "TLS record", but since it's not actually TLS, no more
                    // data will come. This would cause a hang.
                    //
                    // This is extremely unlikely in practice, so we choose not to handle this edge
                    // case to keep the code simple.
                    break;
                }
                Ok(DeframeResult::UnknownPrefix(prefix)) => {
                    // TODO: check lengths and see if we need to split into multiple packets, see
                    // https://github.com/XTLS/Xray-core/blob/9f5dcb15910aadc7ef450514747576827a389853/proxy/proxy.go#L390

                    processed_len += prefix.len();

                    self.filter.decrement_filter_count();

                    if self.filter.is_filtering() {
                        // We don't assume the deframer won't return any more packets,
                        // so we continue here, and stop if we're no longer filtering.
                        let padded_packet = if self.write_first_packet {
                            self.write_first_packet = false;
                            super::vision_pad::pad_with_uuid_and_command(
                                &prefix,
                                &self.user_uuid,
                                COMMAND_CONTINUE,
                                self.filter.is_tls(),
                            )
                        } else {
                            super::vision_pad::pad_with_command(
                                &prefix,
                                COMMAND_CONTINUE,
                                self.filter.is_tls(),
                            )
                        };

                        self.write_to_session(&padded_packet)?;
                        match self.drain_all_writes_padding(cx) {
                            Poll::Pending => {}
                            Poll::Ready(Ok(())) => {}
                            Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                        }

                        // Continue processing
                    } else {
                        // Sending end command to switch to TLS, there are no more padded packets.
                        self.pending_tls_mode_switch = true;

                        let padded_packet = if self.write_first_packet {
                            self.write_first_packet = false;
                            super::vision_pad::pad_with_uuid_and_command(
                                &prefix,
                                &self.user_uuid,
                                COMMAND_END,
                                self.filter.is_tls(),
                            )
                        } else {
                            super::vision_pad::pad_with_command(
                                &prefix,
                                COMMAND_END,
                                self.filter.is_tls(),
                            )
                        };

                        // Clear deframe, not really necessary since deallocate will occur and this
                        // will never be used again.
                        self.inner_write_deframer.clear();

                        self.write_to_session(&padded_packet)?;
                        // Drain and handle result
                        match self.drain_all_writes_padding(cx) {
                            Poll::Ready(Ok(())) => {
                                // Fully drained
                            }
                            Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                            Poll::Pending => {
                                // Still draining
                            }
                        }

                        // tell caller to resend the next packets after the mode switch
                        return Poll::Ready(Ok(processed_len - existing_inner_len));
                    }
                }
                Err(e) => {
                    // Deframing failed, this error means we've already seen a valid TLS record on
                    // the write side and then invalid TLS data is encountered.
                    // Switch immediately to TLS mode and send the invalid data as a single packet.
                    // TODO: check lengths and see if we need to split into multiple packets, see
                    // https://github.com/XTLS/Xray-core/blob/9f5dcb15910aadc7ef450514747576827a389853/proxy/proxy.go#L390
                    //
                    log::error!(
                        "VISION WRITE: Deframing failed, invalid data after valid records - stopping filtering: {}",
                        e
                    );

                    self.pending_tls_mode_switch = true;

                    self.filter
                        .stop_filtering("write invalid TLS data".to_string());

                    let remaining_data = self.inner_write_deframer.remaining_data();

                    let padded_packet = if self.write_first_packet {
                        self.write_first_packet = false;
                        super::vision_pad::pad_with_uuid_and_command(
                            remaining_data,
                            &self.user_uuid,
                            COMMAND_END,
                            self.filter.is_tls(),
                        )
                    } else {
                        super::vision_pad::pad_with_command(
                            remaining_data,
                            COMMAND_END,
                            self.filter.is_tls(),
                        )
                    };

                    self.write_to_session(&padded_packet)?;

                    match self.drain_all_writes_padding(cx) {
                        Poll::Pending => {}
                        Poll::Ready(Ok(())) => {}
                        Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                    }

                    self.inner_write_deframer.clear();

                    return Poll::Ready(Ok(buf.len()));
                }
            }
        }

        // we processed all records if we got here
        Poll::Ready(Ok(buf.len()))
    }
}

// AsyncRead implementation
impl<IO> AsyncRead for VisionStream<IO>
where
    IO: AsyncRead + AsyncWrite + Unpin,
{
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let this = self.get_mut();

        // If we have leftover buffered data, return it first
        if !this.pending_read.is_empty() {
            let len = buf.remaining().min(this.pending_read.len());
            buf.put_slice(&this.pending_read[..len]);
            this.pending_read.advance(len);
            return Poll::Ready(Ok(()));
        }

        match this.read_mode {
            VisionMode::PaddingTls => {
                if this.vless_response_pending {
                    let decrypted_data = ready!(this.poll_read_vless_response(cx))?;
                    this.vless_response_pending = false;
                    if !decrypted_data.is_empty() {
                        this.handle_padded_bytes(&decrypted_data)?;
                        if !this.pending_read.is_empty() {
                            let len = buf.remaining().min(this.pending_read.len());
                            buf.put_slice(&this.pending_read[..len]);
                            this.pending_read.advance(len);
                            return Poll::Ready(Ok(()));
                        }
                        match this.read_mode {
                            VisionMode::PaddingTls => {
                                // Fall-through
                            }
                            VisionMode::Tls => {
                                return this.poll_read_tls(cx, buf);
                            }
                            VisionMode::Direct => {
                                return Pin::new(&mut this.tcp).poll_read(cx, buf);
                            }
                        }
                    }
                }
                this.poll_read_padding_tls(cx, buf)
            }
            VisionMode::Tls => this.poll_read_tls(cx, buf),
            VisionMode::Direct => Pin::new(&mut this.tcp).poll_read(cx, buf),
        }
    }
}

// AsyncWrite implementation
impl<IO> AsyncWrite for VisionStream<IO>
where
    IO: AsyncRead + AsyncWrite + Unpin,
{
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();

        match this.write_mode {
            VisionMode::PaddingTls => this.poll_write_padding_tls(cx, buf),
            VisionMode::Tls => this.poll_write_tls(cx, buf),
            VisionMode::Direct => Pin::new(&mut this.tcp).poll_write(cx, buf),
        }
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = self.get_mut();

        match this.write_mode {
            VisionMode::PaddingTls => {
                ready!(this.drain_all_writes_padding(cx))?;
                Pin::new(&mut this.tcp).poll_flush(cx)
            }
            VisionMode::Tls => {
                ready!(this.drain_all_writes_tls(cx))?;
                Pin::new(&mut this.tcp).poll_flush(cx)
            }
            VisionMode::Direct => Pin::new(&mut this.tcp).poll_flush(cx),
        }
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().tcp).poll_shutdown(cx)
    }
}

// Implement AsyncPing trait
impl<IO> crate::async_stream::AsyncPing for VisionStream<IO>
where
    IO: AsyncStream,
{
    fn supports_ping(&self) -> bool {
        self.tcp.supports_ping()
    }

    fn poll_write_ping(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<bool>> {
        Pin::new(&mut self.get_mut().tcp).poll_write_ping(cx)
    }
}

impl<IO> AsyncStream for VisionStream<IO> where IO: AsyncStream {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::address::{Address, NetLocation};
    use crate::reality::{RealityServerConfig, RealityServerConnection};
    use futures::task::noop_waker_ref;

    fn completed_reality_connection() -> CryptoConnection {
        let config = RealityServerConfig {
            private_key: [0; 32],
            short_ids: vec![[0; 8]],
            dest: NetLocation::new(Address::UNSPECIFIED, 443),
            max_time_diff: None,
            min_client_version: None,
            max_client_version: None,
            cipher_suites: Vec::new(),
        };
        CryptoConnection::new_reality_server(
            RealityServerConnection::new(config)
                .unwrap()
                .complete_for_test()
                .unwrap(),
        )
    }

    fn assert_initial_mode_transition(command: UnpadCommand, session_plaintext: &[u8]) {
        let uuid = [7; 16];
        let mut initial = uuid.to_vec();
        initial.extend_from_slice(&[command as u8, 0, 3, 0, 2]);
        initial.extend_from_slice(b"one\0\0-two");

        let mut session = completed_reality_connection();
        if !session_plaintext.is_empty() {
            let mut peer = completed_reality_connection();
            peer.writer().write_all(session_plaintext).unwrap();
            let mut ciphertext = Vec::new();
            peer.write_tls(&mut ciphertext).unwrap();
            feed_and_process_crypto_connection(&mut session, &ciphertext).unwrap();
        }

        let (io, _peer) = tokio::io::duplex(64);
        let mut stream = VisionStream::new_server(io, session, uuid, &initial).unwrap();
        let expected_mode = match command {
            UnpadCommand::End => VisionMode::Tls,
            UnpadCommand::Direct => VisionMode::Direct,
            UnpadCommand::Continue => panic!("expected a final padding command"),
        };
        assert_eq!(stream.read_mode, expected_mode);

        let mut expected = b"one-two".to_vec();
        expected.extend_from_slice(session_plaintext);
        let mut received = Vec::new();
        let mut cx = Context::from_waker(noop_waker_ref());
        while received.len() < expected.len() {
            let mut bytes = [0; 3];
            let mut buf = ReadBuf::new(&mut bytes);
            assert!(matches!(
                Pin::new(&mut stream).poll_read(&mut cx, &mut buf),
                Poll::Ready(Ok(()))
            ));
            assert!(!buf.filled().is_empty());
            received.extend_from_slice(buf.filled());
        }
        assert_eq!(received, expected);
        assert!(stream.pending_read.is_empty());
    }

    #[test]
    fn initial_end_preserves_session_plaintext() {
        assert_initial_mode_transition(UnpadCommand::End, b"-three");
    }

    #[test]
    fn initial_end_accepts_empty_session() {
        assert_initial_mode_transition(UnpadCommand::End, b"");
    }

    #[test]
    fn initial_direct_preserves_session_plaintext() {
        assert_initial_mode_transition(UnpadCommand::Direct, b"-three");
    }

    #[test]
    fn initial_direct_accepts_empty_session() {
        assert_initial_mode_transition(UnpadCommand::Direct, b"");
    }
}