-
Notifications
You must be signed in to change notification settings - Fork 13
/
client.swift
76 lines (61 loc) · 2.51 KB
/
client.swift
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
//
// client.swift
// swifttls
//
// Created by Nico Schmidt on 05.04.18.
// Copyright © 2018 Nico Schmidt. All rights reserved.
//
import Foundation
import SwiftTLS
func connectTo(host : String, port : UInt16 = 443, supportedVersions: [TLSProtocolVersion] = [.v1_3, .v1_2], cipherSuite : CipherSuite? = nil) async throws
{
var configuration: TLSConfiguration
if let cipherSuite = cipherSuite {
configuration = TLSConfiguration(supportedVersions: cipherSuite.descriptor!.supportedProtocolVersions)
configuration.cipherSuites = [cipherSuite]
}
else {
configuration = TLSConfiguration(supportedVersions: supportedVersions)
}
configuration.earlyData = .supported(maximumEarlyDataSize: 4096)
// Connect twice to test session resumption
var context: TLSClientContext? = nil
var connectionNumber = 0
try await BigInt.withContext { _ in
var client: TLSClient
for _ in 0..<2 {
do {
print("Connecting to \(host):\(port)")
client = TLSClient(configuration: configuration, context: context)
connectionNumber += 1
try await Log.withConnectionNumber(connectionNumber) {
let requestData = [UInt8]("GET / HTTP/1.1\r\nHost: \(host)\r\nUser-Agent: SwiftTLS\r\nConnection: Close\r\n\r\n".utf8)
try await client.connect(hostname: host, port: port, withEarlyData: Data(requestData))
let earlyDataState = client.earlyDataState
print("Early data: \(earlyDataState)")
if context == nil {
context = client.context as? TLSClientContext
}
print("Connection established using cipher suite \(client.cipherSuite!)")
if earlyDataState != .accepted {
try await client.write(requestData)
}
while true {
let data = try await client.read(count: 4096)
if data.count == 0 {
break
}
_ = data.withUnsafeBytes { buffer in
write(1, buffer.baseAddress, buffer.count)
}
break
}
}
}
catch (let error) {
await client.close()
print("Error: \(error)")
}
}
}
}