summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadREST/Transport/Socks5/Socks5DataStreamHandler.swift
blob: 7eedcbcdc9e0b2a9e2aebe65e5afdedb324fe10d (plain)
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
//
//  Socks5DataStreamHandler.swift
//  MullvadTransport
//
//  Created by pronebird on 20/10/2023.
//

import Foundation
import Network

/// The object handling bidirectional streaming of data between local and remote connection.
struct Socks5DataStreamHandler: Sendable {
    /// How many bytes the handler can receive at one time, when streaming data between local and remote connection.
    static let maxBytesToRead = Int(UInt16.max)

    /// Local TCP connection.
    let localConnection: NWConnection

    /// Remote TCP connection to the socks proxy.
    let remoteConnection: NWConnection

    /// Error handler.
    let errorHandler: @Sendable (Error) -> Void

    /// Start streaming data between local and remote connection.
    func start() {
        streamOutboundTraffic()
        streamInboundTraffic()
    }

    /// Pass outbound traffic from local to remote connection.
    private func streamOutboundTraffic() {
        localConnection.receive(
            minimumIncompleteLength: 1,
            maximumLength: Self.maxBytesToRead
        ) { [self] content, _, isComplete, error in
            if let error {
                errorHandler(Socks5Error.localConnectionFailure(error))
                return
            }

            remoteConnection.send(
                content: content,
                isComplete: isComplete,
                completion: .contentProcessed { [self] error in
                    if let error {
                        errorHandler(Socks5Error.remoteConnectionFailure(error))
                    } else if !isComplete {
                        streamOutboundTraffic()
                    }
                }
            )
        }
    }

    /// Pass inbound traffic from remote to local connection.
    private func streamInboundTraffic() {
        remoteConnection.receive(
            minimumIncompleteLength: 1,
            maximumLength: Self.maxBytesToRead
        ) { [self] content, _, isComplete, error in
            if let error {
                errorHandler(Socks5Error.remoteConnectionFailure(error))
                return
            }

            localConnection.send(
                content: content,
                isComplete: isComplete,
                completion: .contentProcessed { [self] error in
                    if let error {
                        errorHandler(Socks5Error.localConnectionFailure(error))
                    } else if !isComplete {
                        streamInboundTraffic()
                    }
                }
            )
        }
    }
}