Add SwiftLint (#318)

This commit is contained in:
Davide De Rosa 2023-04-20 21:52:45 +02:00 committed by GitHub
parent c62fc4adaa
commit 0c77062add
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
96 changed files with 1292 additions and 1266 deletions

View File

@ -27,7 +27,7 @@ import Foundation
import TunnelKitOpenVPNAppExtension
class PacketTunnelProvider: OpenVPNTunnelProvider {
override func startTunnel(options: [String : NSObject]? = nil) async throws {
override func startTunnel(options: [String: NSObject]? = nil) async throws {
dataCountInterval = 3
try await super.startTunnel(options: options)
}

View File

@ -34,7 +34,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let logDestination = ConsoleDestination()
logDestination.minLevel = .debug

View File

@ -31,8 +31,6 @@ private let log = SwiftyBeaver.self
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let logDestination = ConsoleDestination()
logDestination.minLevel = .debug
@ -46,6 +44,4 @@ class AppDelegate: NSObject, NSApplicationDelegate {
// Insert code here to tear down your application
}
}

View File

@ -175,4 +175,3 @@ class OpenVPNViewController: NSViewController {
// print("\(username) -> \(fetchedPassword)")
// }
}

View File

@ -41,7 +41,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
@ -69,6 +68,4 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}

View File

@ -48,6 +48,4 @@ class ViewController: UIViewController {
// Dispose of any resources that can be recreated.
}
}

View File

@ -418,6 +418,7 @@
0E05416725A232FD00EFC5FF /* Resources */,
0E0541AD25A2343500EFC5FF /* Embed App Extensions */,
0E05438525A240E400EFC5FF /* Embed Frameworks */,
0EB5A56B29F1C9C8005313B3 /* SwiftLint */,
);
buildRules = (
);
@ -463,6 +464,7 @@
0E05422A25A236EB00EFC5FF /* Resources */,
0E05428425A239C600EFC5FF /* Embed App Extensions */,
0E05438825A240E900EFC5FF /* Embed Frameworks */,
0EB5A56A29F1C8FC005313B3 /* SwiftLint */,
);
buildRules = (
);
@ -700,6 +702,45 @@
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
0EB5A56A29F1C8FC005313B3 /* SwiftLint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = SwiftLint;
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "PATH=\"/opt/homebrew/bin:${PATH}\"\nif which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
};
0EB5A56B29F1C9C8005313B3 /* SwiftLint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = SwiftLint;
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "PATH=\"/opt/homebrew/bin:${PATH}\"\nif which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
0E05416525A232FD00EFC5FF /* Sources */ = {
isa = PBXSourcesBuildPhase;

View File

@ -188,6 +188,6 @@ let package = Package(
dependencies: [
"TunnelKitCore",
"TunnelKitLZO"
]),
])
]
)

View File

@ -107,8 +107,8 @@ public class NETCPSocket: NSObject, GenericSocket {
// MARK: Connection KVO (any queue)
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard (context == &NETCPSocket.linkContext) else {
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard context == &NETCPSocket.linkContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
@ -120,7 +120,7 @@ public class NETCPSocket: NSObject, GenericSocket {
}
}
private func observeValueInTunnelQueue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
private func observeValueInTunnelQueue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
// if let keyPath = keyPath {
// log.debug("KVO change reported (\(anyPointer(object)).\(keyPath))")
// }

View File

@ -64,7 +64,7 @@ public class NETunnelInterface: TunnelInterface {
private func loopReadPackets(_ queue: DispatchQueue, _ handler: @escaping ([Data]?, Error?) -> Void) {
// WARNING: runs in NEPacketTunnelFlow queue
impl?.readPackets { [weak self] (packets, protocols) in
impl?.readPackets { [weak self] (packets, _) in
queue.sync {
self?.loopReadPackets(queue, handler)
handler(packets, nil)

View File

@ -107,8 +107,8 @@ public class NEUDPSocket: NSObject, GenericSocket {
// MARK: Connection KVO (any queue)
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard (context == &NEUDPSocket.linkContext) else {
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard context == &NEUDPSocket.linkContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
@ -120,7 +120,7 @@ public class NEUDPSocket: NSObject, GenericSocket {
}
}
private func observeValueInTunnelQueue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
private func observeValueInTunnelQueue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
// if let keyPath = keyPath {
// log.debug("KVO change reported (\(anyPointer(object)).\(keyPath))")
// }

View File

@ -61,9 +61,9 @@ public func Z(_ data: Data) -> ZeroingData {
return ZeroingData(data: data)
}
//public func Z(_ data: Data, _ offset: Int, _ count: Int) -> ZeroingData {
// public func Z(_ data: Data, _ offset: Int, _ count: Int) -> ZeroingData {
// return ZeroingData(data: data, offset: offset, count: count)
//}
// }
public func Z(_ string: String, nullTerminated: Bool) -> ZeroingData {
return ZeroingData(string: string, nullTerminated: nullTerminated)

View File

@ -94,8 +94,7 @@ class ConnectionStrategy {
from provider: NEProvider,
timeout: Int,
queue: DispatchQueue,
completionHandler: @escaping (Result<GenericSocket, OpenVPNProviderError>) -> Void)
{
completionHandler: @escaping (Result<GenericSocket, OpenVPNProviderError>) -> Void) {
guard let remote = currentRemote else {
completionHandler(.failure(.exhaustedEndpoints))
return

View File

@ -140,7 +140,7 @@ open class OpenVPNTunnelProvider: NEPacketTunnelProvider {
}
}
open override func startTunnel(options: [String : NSObject]? = nil, completionHandler: @escaping (Error?) -> Void) {
open override func startTunnel(options: [String: NSObject]? = nil, completionHandler: @escaping (Error?) -> Void) {
// required configuration
do {

View File

@ -66,10 +66,10 @@ extension OpenVPN {
public var shouldDebug = false
/// Debug log path.
public var debugLogPath: String? = nil
public var debugLogPath: String?
/// Optional debug log format (SwiftyBeaver format).
public var debugLogFormat: String? = nil
public var debugLogFormat: String?
/// Mask private data in debug log (default is `true`).
public var masksPrivateData = true

View File

@ -183,7 +183,7 @@ extension OpenVPN {
let prefixLength = ProtocolMacros.tlsPrefix.count
// TLS prefix + random (x2) + opts length [+ opts]
guard (controlBuffer.count >= prefixLength + 2 * CoreConfiguration.OpenVPN.randomLength + 2) else {
guard controlBuffer.count >= prefixLength + 2 * CoreConfiguration.OpenVPN.randomLength + 2 else {
return false
}

View File

@ -155,7 +155,7 @@ extension OpenVPN {
// packet count
let packetCount = currentPacketId.outbound - oldIdOut
if (packetCount > 1) {
if packetCount > 1 {
log.debug("Control: Enqueued \(packetCount) packets [\(oldIdOut)-\(currentPacketId.outbound - 1)]")
} else {
log.debug("Control: Enqueued 1 packet [\(oldIdOut)]")
@ -167,7 +167,7 @@ extension OpenVPN {
for packet in queue.outbound {
if let sentDate = packet.sentDate {
let timeAgo = -sentDate.timeIntervalSinceNow
guard (timeAgo >= CoreConfiguration.OpenVPN.retransmissionLimit) else {
guard timeAgo >= CoreConfiguration.OpenVPN.retransmissionLimit else {
log.debug("Control: Skip writing packet with packetId \(packet.packetId) (sent on \(sentDate), \(timeAgo) seconds ago)")
continue
}

View File

@ -79,7 +79,7 @@ extension CoreConfiguration {
"IV_UI_VER=\(uiVersion)",
"IV_PROTO=2",
"IV_NCP=2",
"IV_LZO_STUB=1",
"IV_LZO_STUB=1"
]
if LZOFactory.isSupported() {
info.append("IV_LZO=1")

View File

@ -88,7 +88,7 @@ extension OpenVPN {
let out = Z()
let buffer = Z(count: EncryptionBridge.maxHmacLength)
var chain = try EncryptionBridge.hmac(buffer, digestName, secret, seed)
while (out.count < size) {
while out.count < size {
out.append(try EncryptionBridge.hmac(buffer, digestName, secret, chain.appending(seed)))
chain = try EncryptionBridge.hmac(buffer, digestName, secret, chain)
}

View File

@ -228,7 +228,7 @@ public class OpenVPNSession: Session {
// MARK: Session
public func setLink(_ link: LinkInterface) {
guard (self.link == nil) else {
guard self.link == nil else {
log.warning("Link interface already set!")
return
}
@ -269,7 +269,7 @@ public class OpenVPNSession: Session {
}
public func setTunnel(tunnel: TunnelInterface) {
guard (self.tunnel == nil) else {
guard self.tunnel == nil else {
log.warning("Tunnel interface already set!")
return
}
@ -445,7 +445,7 @@ public class OpenVPNSession: Session {
// log.verbose("Parsed packet with code \(code)")
var offset = 1
if (code == .dataV2) {
if code == .dataV2 {
guard packet.count >= offset + PacketPeerIdLength else {
log.warning("Dropped malformed packet (missing peerId)")
continue
@ -719,12 +719,12 @@ public class OpenVPNSession: Session {
guard let renegotiatesAfter = configuration.renegotiatesAfter, renegotiatesAfter > 0 else {
return
}
guard (negotiationKeyIdx == currentKeyIdx) else {
guard negotiationKeyIdx == currentKeyIdx else {
return
}
let elapsed = -negotiationKey.startTime.timeIntervalSinceNow
if (elapsed > renegotiatesAfter) {
if elapsed > renegotiatesAfter {
log.debug("Renegotiating after \(elapsed.asTimeString)")
softReset(isServerInitiated: false)
}
@ -811,7 +811,7 @@ public class OpenVPNSession: Session {
enqueueControlPackets(code: .controlV1, key: negotiationKey.id, payload: cipherTextOut)
}
// exchange TLS ciphertext
else if ((packet.code == .controlV1) && (negotiationKey.state == .tls)) {
else if (packet.code == .controlV1) && (negotiationKey.state == .tls) {
guard let remoteSessionId = controlChannel.remoteSessionId else {
log.error("No remote sessionId found in packet (control packets before server HARD_RESET)")
deferStop(.shutdown, OpenVPNError.missingSessionId)
@ -873,7 +873,7 @@ public class OpenVPNSession: Session {
auth.appendControlData(data)
if (negotiationKey.controlState == .preAuth) {
if negotiationKey.controlState == .preAuth {
do {
guard try auth.parseAuthReply() else {
return
@ -1003,7 +1003,7 @@ public class OpenVPNSession: Session {
// Ruby: clean_keys
private func cleanKeys() {
while (oldKeys.count > 1) {
while oldKeys.count > 1 {
let key = oldKeys.removeFirst()
keys.removeValue(forKey: key.id)
}
@ -1259,7 +1259,7 @@ public class OpenVPNSession: Session {
completion()
return
}
link.writePackets(packets) { [weak self] (error) in
link.writePackets(packets) { [weak self] (_) in
self?.queue.sync {
completion()
}

View File

@ -65,7 +65,7 @@ extension OpenVPN {
ConfigurationParser.Regex.authToken.replaceMatches(
in: stripped,
options: [],
range: NSMakeRange(0, stripped.length),
range: NSRange(location: 0, length: stripped.length),
withTemplate: "auth-token"
)
return stripped as String

View File

@ -51,9 +51,9 @@ extension WireGuard {
public var shouldDebug = false
public var debugLogPath: String? = nil
public var debugLogPath: String?
public var debugLogFormat: String? = nil
public var debugLogFormat: String?
public init(_ title: String, appGroup: String, configuration: WireGuard.Configuration) {
self.title = title
@ -95,7 +95,6 @@ extension WireGuard.ProviderConfiguration {
return defaults?.wireGuardLastError
}
public var urlForDebugLog: URL? {
return defaults?.wireGuardURLForDebugLog(appGroup: appGroup)
}

View File

@ -44,11 +44,9 @@ extension UnicodeScalar {
let value = self.value
if 48 <= value && value <= 57 {
return UInt8(value - 48)
}
else if 65 <= value && value <= 70 {
} else if 65 <= value && value <= 70 {
return UInt8(value - 55)
}
else if 97 <= value && value <= 102 {
} else if 97 <= value && value <= 102 {
return UInt8(value - 87)
}
fatalError("\(self) not a legal hex nibble")
@ -58,7 +56,7 @@ extension UnicodeScalar {
extension Data {
public init(hex: String) {
let scalars = hex.unicodeScalars
var bytes = Array<UInt8>(repeating: 0, count: (scalars.count + 1) >> 1)
var bytes = [UInt8](repeating: 0, count: (scalars.count + 1) >> 1)
for (index, scalar) in scalars.enumerated() {
var nibble = scalar.hexNibble
if index & 1 == 0 {
@ -115,7 +113,7 @@ extension Data {
public func nullTerminatedString(from: Int) -> String? {
var nullOffset: Int?
for i in from..<count {
if (self[i] == 0) {
if self[i] == 0 {
nullOffset = i
break
}

View File

@ -32,7 +32,7 @@ extension NSRegularExpression {
public func groups(in string: String) -> [String] {
var results: [String] = []
enumerateMatches(in: string, options: [], range: NSMakeRange(0, string.count)) { result, flags, stop in
enumerateMatches(in: string, options: [], range: NSRange(location: 0, length: string.count)) { result, _, _ in
guard let result = result else {
return
}
@ -48,7 +48,7 @@ extension NSRegularExpression {
extension NSRegularExpression {
public func enumerateSpacedComponents(in string: String, using block: ([String]) -> Void) {
enumerateMatches(in: string, options: [], range: NSMakeRange(0, string.count)) { result, flags, stop in
enumerateMatches(in: string, options: [], range: NSRange(location: 0, length: string.count)) { result, _, _ in
guard let range = result?.range else {
return
}

View File

@ -55,7 +55,7 @@ class RawPerformanceTests: XCTestCase {
measure {
for _ in 0..<1000000 {
let _ = data.UInt16Value(from: 3)
_ = data.UInt16Value(from: 3)
}
}
}
@ -88,7 +88,7 @@ class RawPerformanceTests: XCTestCase {
measure {
for _ in 0..<1000000 {
let _ = data.UInt32Value(from: 1)
_ = data.UInt32Value(from: 1)
}
}
}
@ -106,7 +106,7 @@ class RawPerformanceTests: XCTestCase {
func testRandomUInt32FromPointers() {
measure {
for _ in 0..<10000 {
let _ = try! SecureRandom.uint32()
_ = try! SecureRandom.uint32()
}
}
}
@ -127,7 +127,7 @@ class RawPerformanceTests: XCTestCase {
measure {
for data in suite {
// let _ = UInt32(bigEndian: data.subdata(in: 0..<4).withUnsafeBytes { $0.pointee })
let _ = data.networkUInt32Value(from: 0)
_ = data.networkUInt32Value(from: 0)
}
}
}
@ -137,7 +137,7 @@ class RawPerformanceTests: XCTestCase {
let suite = TestUtils.generateDataSuite(1000, 100000)
measure {
for data in suite {
let _ = data.subdata(in: 5..<data.count)
_ = data.subdata(in: 5..<data.count)
}
}
}

View File

@ -40,7 +40,7 @@ class CompressionTests: XCTestCase {
}
func testSymmetric() {
XCTAssertTrue(LZOFactory.isSupported());
XCTAssertTrue(LZOFactory.isSupported())
let lzo = LZOFactory.create()
let src = Data([UInt8](repeating: 6, count: 100))
guard let dst = try? lzo.compressedData(with: src) else {

View File

@ -110,7 +110,7 @@ class ConfigurationParserTests: XCTestCase {
let file = try OpenVPN.ConfigurationParser.parsed(fromURL: url(withName: "pia-hungary"))
XCTAssertEqual(file.configuration.remotes, [
.init("hungary.privateinternetaccess.com", .init(.udp, 1198)),
.init("hungary.privateinternetaccess.com", .init(.tcp, 502)),
.init("hungary.privateinternetaccess.com", .init(.tcp, 502))
])
XCTAssertEqual(file.configuration.cipher, .aes128cbc)
XCTAssertEqual(file.configuration.digest, .sha1)
@ -130,7 +130,7 @@ class ConfigurationParserTests: XCTestCase {
func testXOR() throws {
let cfg = try OpenVPN.ConfigurationParser.parsed(fromLines: ["scramble xormask F"])
XCTAssertNil(cfg.warning)
XCTAssertEqual(cfg.configuration.xorMethod, OpenVPN.XORMethod.xormask(mask: Data(repeating: Character("F").asciiValue!, count:1)))
XCTAssertEqual(cfg.configuration.xorMethod, OpenVPN.XORMethod.xormask(mask: Data(repeating: Character("F").asciiValue!, count: 1)))
let cfg2 = try OpenVPN.ConfigurationParser.parsed(fromLines: ["scramble reverse"])
XCTAssertNil(cfg.warning)
@ -142,7 +142,7 @@ class ConfigurationParserTests: XCTestCase {
let cfg4 = try OpenVPN.ConfigurationParser.parsed(fromLines: ["scramble obfuscate FFFF"])
XCTAssertNil(cfg.warning)
XCTAssertEqual(cfg4.configuration.xorMethod, OpenVPN.XORMethod.obfuscate(mask: Data(repeating: Character("F").asciiValue!, count:4)))
XCTAssertEqual(cfg4.configuration.xorMethod, OpenVPN.XORMethod.obfuscate(mask: Data(repeating: Character("F").asciiValue!, count: 4)))
}
private func privateTestEncryptedCertificateKey(pkcs: String) throws {

View File

@ -72,7 +72,7 @@ class EncryptionPerformanceTests: XCTestCase {
let suite = TestUtils.generateDataSuite(1000, 100000)
measure {
for data in suite {
let _ = try! self.cbcEncrypter.encryptData(data, flags: nil)
_ = try! self.cbcEncrypter.encryptData(data, flags: nil)
}
}
}
@ -86,7 +86,7 @@ class EncryptionPerformanceTests: XCTestCase {
}
measure {
for data in suite {
let _ = try! self.gcmEncrypter.encryptData(data, flags: &flags)
_ = try! self.gcmEncrypter.encryptData(data, flags: &flags)
}
}
}

View File

@ -167,11 +167,11 @@ class LinkTests: XCTestCase {
print("id = \(id)")
for p in q {
print("test(\(p))")
if (p < id) {
if p < id {
q.removeFirst()
continue
}
if (p != id) {
if p != id {
return
}

View File

@ -41,7 +41,7 @@ import CTunnelKitOpenVPNProtocol
public class TestUtils {
public static func uniqArray(_ v: [Int]) -> [Int] {
return v.reduce([]){ $0.contains($1) ? $0 : $0 + [$1] }
return v.reduce([]) { $0.contains($1) ? $0 : $0 + [$1] }
}
public static func generateDataSuite(_ size: Int, _ count: Int) -> [Data] {