SettingsViewController.swift 46.5 KB
Newer Older
Davide De Rosa's avatar
Davide De Rosa committed
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
//
//  SettingsViewController.swift
//  PIA VPN
//
//  Created by Davide De Rosa on 12/8/17.
//  Copyright © 2017 London Trust Media. All rights reserved.
//

import UIKit
import PIALibrary
import PIATunnel
import SafariServices
import SwiftyBeaver

private let log = SwiftyBeaver.self

private extension String {
    var vpnTypeDescription: String {
        guard (self != PIATunnelProfile.vpnType) else {
            return "OpenVPN"
        }
        return self
    }
}

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
enum Setting: Int {
    case vpnProtocolSelection
    
    case vpnSocket
    
    case vpnPort
    
    case vpnDns
    
    case encryptionCipher
    
    case encryptionDigest
    
    case encryptionHandshake
    
    case automaticReconnection
Jose Blaya's avatar
Jose Blaya committed
42

Jose Blaya's avatar
wip    
Jose Blaya committed
43
    case trustedNetworks
44

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    case contentBlockerState
    
    case contentBlockerRefreshRules
    
    case mace
    
    case darkTheme
    
    case sendDebugLog
    
    case resetSettings
    
    // development
    
    //        case truncateDebugLog
    //
    //        case recalculatePingTimes
    //
    //        case invokeMACERequest
    
65
66
67
68
69
70
    case publicUsername
    
    case username
    
    case password
    
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    case resolveGoogleAdsDomain
}

protocol SettingsViewControllerDelegate: class {
    
    /**
     Called to update the setting sent as parameter.
     
     - Parameter setting: The setting to update.
     - Parameter value: Optional value to update the setting
     */
    func updateSetting(_ setting: Setting, withValue value: Any?)
}


Davide De Rosa's avatar
Davide De Rosa committed
86
class SettingsViewController: AutolayoutViewController {
87
88
89

    fileprivate static let DNS: String = "DNS"

90
91
    fileprivate static let AUTOMATIC_SOCKET = "automatic"

92
    fileprivate static let AUTOMATIC_PORT: UInt16 = 0
93

Davide De Rosa's avatar
Davide De Rosa committed
94
95
96
97
98
99
    private enum Section: Int {
        case connection

        case encryption

        case applicationSettings
Jose Blaya's avatar
Jose Blaya committed
100
        
Jose Blaya's avatar
Jose Blaya committed
101
102
        case autoConnectSettings

Davide De Rosa's avatar
Davide De Rosa committed
103
104
105
106
107
108
109
110
111
112
113
114
115
        case contentBlocker

        case applicationInformation
        
        case reset

        case development
    }

    private static let allSections: [Section] = [
        .connection,
        .encryption,
        .applicationSettings,
Jose Blaya's avatar
Jose Blaya committed
116
        .autoConnectSettings,
Davide De Rosa's avatar
Davide De Rosa committed
117
        .applicationInformation,
Davide De Rosa's avatar
Davide De Rosa committed
118
119
        .reset,
        .contentBlocker
Davide De Rosa's avatar
Davide De Rosa committed
120
121
122
123
124
125
126
127
    ]

    private var visibleSections: [Section] = []

    private var rowsBySection: [Section: [Setting]] = [
        .connection: [
            .vpnProtocolSelection,
            .vpnSocket,
128
129
            .vpnPort,
            .vpnDns
Davide De Rosa's avatar
Davide De Rosa committed
130
131
132
133
134
135
136
        ],
        .encryption: [
            .encryptionCipher,
            .encryptionDigest,
            .encryptionHandshake
        ],
        .applicationSettings: [], // dynamic
Jose Blaya's avatar
Jose Blaya committed
137
        .autoConnectSettings: [
138
            .trustedNetworks
Jose Blaya's avatar
Jose Blaya committed
139
        ],
Davide De Rosa's avatar
Davide De Rosa committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        .contentBlocker: [
            .contentBlockerState,
            .contentBlockerRefreshRules
        ],
        .applicationInformation: [
            .sendDebugLog
        ],
        .reset: [
            .resetSettings
        ],
        .development: [
//            .truncateDebugLog,
//            .recalculatePingTimes,
//            .invokeMACERequest,
154
//            .mace,
155
156
157
            .publicUsername,
            .username,
            .password,
Davide De Rosa's avatar
Davide De Rosa committed
158
159
160
161
162
163
164
165
166
167
            .resolveGoogleAdsDomain
        ]
    ]
    
    private struct Cells {
        static let setting = "SettingCell"
    }
    
    @IBOutlet private weak var tableView: UITableView!

168
169
    private lazy var switchAutoJoinWiFi = UISwitch()

Davide De Rosa's avatar
Davide De Rosa committed
170
    private lazy var switchPersistent = UISwitch()
171

Davide De Rosa's avatar
Davide De Rosa committed
172
173
174
175
176
    private lazy var switchMACE = UISwitch()
    
    private lazy var switchContentBlocker = FakeSwitch()
    
    private lazy var switchDarkMode = UISwitch()
Jose Blaya's avatar
Jose Blaya committed
177

Davide De Rosa's avatar
Davide De Rosa committed
178
179
180
181
182
183
184
185
186
187
    private lazy var imvSelectedOption = UIImageView(image: Asset.accessorySelected.image)

    private var isContentBlockerEnabled = false

//    private lazy var buttonConfirm = UIBarButtonItem(
//        barButtonSystemItem: .save,
//        target: self,
//        action: #selector(confirmChangesImmediately(_:))
//    )
    
188
189
    private var pendingPreferences: Client.Preferences.Editable!
    
190
191
    private var pendingOpenVPNSocketType: PIATunnelProvider.SocketType?
    
192
    private var pendingOpenVPNConfiguration: PIATunnelProvider.ConfigurationBuilder!
Davide De Rosa's avatar
Davide De Rosa committed
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214

    private var pendingVPNAction: VPNAction?
//    private var pendingVPNAction: VPNAction? {
//        didSet {
//            if let _ = pendingVPNAction {
//                buttonConfirm.isEnabled = true
//            } else {
//                buttonConfirm.isEnabled = false
//            }
//        }
//    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        title = L10n.Menu.Item.settings
//        buttonConfirm.isEnabled = false
//        navigationItem.rightBarButtonItem = buttonConfirm
215
216
        
        pendingPreferences = Client.preferences.editable()
217
218
219
220
221

        // XXX: fall back to default configuration (don't rely on client library)
        guard let currentOpenVPNConfiguration = pendingPreferences.vpnCustomConfiguration(for: PIATunnelProfile.vpnType) as? PIATunnelProvider.Configuration ??
            Client.preferences.defaults.vpnCustomConfiguration(for: PIATunnelProfile.vpnType) as? PIATunnelProvider.Configuration else {

222
223
            fatalError("No default VPN custom configuration provided for PIA protocol")
        }
224
        pendingOpenVPNSocketType = AppPreferences.shared.piaSocketType
225
        pendingOpenVPNConfiguration = currentOpenVPNConfiguration.builder()
226
227
        
        validateDNSList()
Davide De Rosa's avatar
Davide De Rosa committed
228
229
230
231
232
233
234

        if #available(iOS 11, *) {
            tableView.sectionFooterHeight = UITableViewAutomaticDimension
            tableView.estimatedSectionFooterHeight = 1.0
        }
        switchPersistent.addTarget(self, action: #selector(togglePersistentConnection(_:)), for: .valueChanged)
        switchMACE.addTarget(self, action: #selector(toggleMACE(_:)), for: .valueChanged)
Davide De Rosa's avatar
Davide De Rosa committed
235
//        switchContentBlocker.isGrayed = true
Davide De Rosa's avatar
Davide De Rosa committed
236
237
238
239
240
241
242
243
244
        switchContentBlocker.addTarget(self, action: #selector(showContentBlockerTutorial), for: .touchUpInside)
        switchDarkMode.addTarget(self, action: #selector(toggleDarkMode(_:)), for: .valueChanged)
        redisplaySettings()

        NotificationCenter.default.addObserver(self, selector: #selector(refreshContentBlockerState), name: .UIApplicationDidBecomeActive, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
245
        refreshContentBlockerState()
Davide De Rosa's avatar
Davide De Rosa committed
246
247
248
249
250
251
252
253
254
255
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        
        if #available(iOS 11, *) {
            tableView.reloadData()
        }
    }
    
256
257
258
259
260
261
262
263
264
265
266
267
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let customDNSSettingsVC = segue.destination as? CustomDNSSettingsViewController {
            customDNSSettingsVC.delegate = self
            let ips = DNSList.shared.valueForKey(DNSList.CUSTOM_DNS_KEY)
            if ips.count > 0 {
                customDNSSettingsVC.primaryDNSValue = ips.first
                if ips.count > 1 {
                    customDNSSettingsVC.secondaryDNSValue = ips.last
                }
            }
        }
    }
Davide De Rosa's avatar
Davide De Rosa committed
268
    
269
270
271
272
273
    // MARK: Actions
    @objc private func edit(_ sender: Any?) {
        self.perform(segue: StoryboardSegue.Main.customDNSSegueIdentifier)
    }

Davide De Rosa's avatar
Davide De Rosa committed
274
275
276
277
278
279
280
281
282
283
284
    @objc private func togglePersistentConnection(_ sender: UISwitch) {
        pendingPreferences.isPersistentConnection = sender.isOn
        redisplaySettings()
        reportUpdatedPreferences()
    }
    
    @objc private func toggleMACE(_ sender: UISwitch) {
        pendingPreferences.mace = sender.isOn
        redisplaySettings()
        reportUpdatedPreferences()
    }
Jose Blaya's avatar
Jose Blaya committed
285
    
Davide De Rosa's avatar
Davide De Rosa committed
286
287
    // XXX: no need to bufferize app preferences
    @objc private func toggleDarkMode(_ sender: UISwitch) {
288
        AppPreferences.shared.transitionTheme(to: sender.isOn ? .dark : .light)
Davide De Rosa's avatar
Davide De Rosa committed
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
    }
    
    @objc private func showContentBlockerTutorial() {
        perform(segue: StoryboardSegue.Main.contentBlockerSegueIdentifier)
    }

    @objc private func refreshContentBlockerState(withHUD: Bool = false) {
        if #available(iOS 10, *) {
            var hud: HUD?
            if withHUD {
                hud = HUD()
            }
            SFContentBlockerManager.getStateOfContentBlocker(withIdentifier: AppConstants.Extensions.adBlockerBundleIdentifier) { (state, error) in
                DispatchQueue.main.async {
                    hud?.hide()
                    
                    self.isContentBlockerEnabled = state?.isEnabled ?? false
                    self.redisplaySettings()
                }
            }
        }
    }
    
    private func refreshContentBlockerRules() {
        let hud = HUD()
        SFContentBlockerManager.reloadContentBlocker(withIdentifier: AppConstants.Extensions.adBlockerBundleIdentifier) { (error) in
            if let error = error {
                log.error("Could not reload Safari Content Blocker: \(error)")
            }
            DispatchQueue.main.async {
                hud.hide()
            }
        }
    }
    
    private func submitTunnelLog() {
        let hud = HUD()
        
        Client.providers.vpnProvider.submitLog { (log, error) in
            hud.hide()
            
            let title: String
            let message: String
        
            defer {
                let alert = Macros.alert(title, message)
                alert.addCancelAction(L10n.Global.ok)
                self.present(alert, animated: true, completion: nil)
                
//                UIActivityViewController *vc = [[UIActivityViewController alloc] initWithActivityItems:@[log] applicationActivities:nil];
//                [self presentViewController:vc animated:YES completion:NULL];
            }
            
            guard let log = log else {
                title = L10n.Settings.ApplicationInformation.Debug.Failure.title
                message = L10n.Settings.ApplicationInformation.Debug.Failure.message
                return
            }
            guard !log.isEmpty else {
                title = L10n.Settings.ApplicationInformation.Debug.Empty.title
                message = L10n.Settings.ApplicationInformation.Debug.Empty.message
                return
            }

            title = L10n.Settings.ApplicationInformation.Debug.Success.title
            message = L10n.Settings.ApplicationInformation.Debug.Success.message(log.identifier)
        }
    }
    
    private func resetToDefaultSettings() {
        let alert = Macros.alert(
            L10n.Settings.Reset.Defaults.Confirm.title,
            L10n.Settings.Reset.Defaults.Confirm.message
        )
        alert.addDestructiveAction(L10n.Settings.Reset.Defaults.Confirm.button) {
            self.doReset()
        }
        alert.addCancelAction(L10n.Global.cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    private func doReset() {

        // only don't reset selected server
        let savedServer = pendingPreferences.preferredServer
        pendingPreferences.reset()
        pendingPreferences.preferredServer = savedServer
376
377
378
        guard let currentOpenVPNConfiguration = pendingPreferences.vpnCustomConfiguration(for: PIATunnelProfile.vpnType) as? PIATunnelProvider.Configuration else {
            fatalError("No default VPN custom configuration provided for PIA protocol")
        }
379
        AppPreferences.shared.reset()
380
        DNSList.shared.resetPlist()
381
        pendingOpenVPNSocketType = AppPreferences.shared.piaSocketType
382
        pendingOpenVPNConfiguration = currentOpenVPNConfiguration.builder()
Davide De Rosa's avatar
Davide De Rosa committed
383
384
385
386
387
388
389
390
391
392
393
394

        redisplaySettings()
        reportUpdatedPreferences()
    }
    
//    @IBAction private func confirmChangesImmediately(_ sender: Any?) {
//        confirmChanges(retainingConnection: false) {
//            self.buttonConfirm.isEnabled = false
//        }
//    }
    
    func commitChanges(_ completionHandler: @escaping () -> Void) {
395
        if !Flags.shared.enablesMACESetting && !visibleSections.contains(.development) {
Davide De Rosa's avatar
Davide De Rosa committed
396
397
398
399
            pendingPreferences.mace = false
        }
        
        guard let action = pendingVPNAction else {
400
            commitPreferences()
Davide De Rosa's avatar
Davide De Rosa committed
401
402
403
404
405
406
407
408
409
410
            completionHandler()
            return
        }
        
        let isDisconnected = (Client.providers.vpnProvider.vpnStatus == .disconnected)
        let completionHandlerAfterVPNAction: (Bool) -> Void = { (shouldReconnect) in
            let hud = HUD()
            action.execute { (error) in
                self.pendingVPNAction = nil
                
411
412
                Client.providers.vpnProvider.updatePreferences(nil)
                
Davide De Rosa's avatar
Davide De Rosa committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
                if shouldReconnect && !isDisconnected {
                    Client.providers.vpnProvider.reconnect(after: nil) { (error) in
                        completionHandler()
                        hud.hide()
                    }
                } else {
                    completionHandler()
                    hud.hide()
                }
            }
        }

        // disconnected, commit and execute
        guard !isDisconnected else {
427
            commitPreferences()
Davide De Rosa's avatar
Davide De Rosa committed
428
429
430
431
432
433
434
435
436
437
438
439
440
            completionHandlerAfterVPNAction(false)
            return
        }

        // must reconnect
        guard action.canRetainConnection else {
            let alert = Macros.alert(
                title,
                L10n.Settings.Commit.Messages.mustDisconnect
            )

            // reconnect -> reconnect VPN and close
            alert.addDefaultAction(L10n.Settings.Commit.Buttons.reconnect) {
441
                self.commitPreferences()
Davide De Rosa's avatar
Davide De Rosa committed
442
443
444
445
446
447
448
449
450
451
452
453
454
                completionHandlerAfterVPNAction(true)
            }

            // cancel -> revert changes and close
            alert.addAction(UIAlertAction(title: L10n.Global.cancel, style: .cancel) { (action) in
                completionHandler()
            })
            present(alert, animated: true, completion: nil)
            return
        }

        // should reconnect
        guard !pendingPreferences.suggestsVPNReconnection() else {
455
456
            commitPreferences()

Davide De Rosa's avatar
Davide De Rosa committed
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
            let alert = Macros.alert(
                title,
                L10n.Settings.Commit.Messages.shouldReconnect
            )

            // reconnect -> reconnect VPN and close
            alert.addDefaultAction(L10n.Settings.Commit.Buttons.reconnect) {
                completionHandlerAfterVPNAction(true)
            }

            // later -> close
            alert.addAction(UIAlertAction(title: L10n.Settings.Commit.Buttons.later, style: .cancel) { (action) in
                completionHandler()
            })
            present(alert, animated: true, completion: nil)
            return
        }
        
        // action doesn't affect VPN connection, commit and execute
476
        commitPreferences()
Davide De Rosa's avatar
Davide De Rosa committed
477
478
479
        completionHandlerAfterVPNAction(false)
    }
    
480
481
    private func commitPreferences() {
        AppPreferences.shared.piaSocketType = pendingOpenVPNSocketType
Jose Blaya's avatar
Jose Blaya committed
482
483
484
485
        //Update with values from Trusted Network Settings
        pendingPreferences.trustedNetworks = Client.preferences.trustedNetworks
        pendingPreferences.availableNetworks = Client.preferences.availableNetworks
        pendingPreferences.shouldConnectForAllNetworks = Client.preferences.shouldConnectForAllNetworks
486
        pendingPreferences.useWiFiProtection = Client.preferences.useWiFiProtection
487
        pendingPreferences.trustCellularData = Client.preferences.trustCellularData
488
489
490
        pendingPreferences.commit()
    }
    
Davide De Rosa's avatar
Davide De Rosa committed
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
    // MARK: Unwind segues
    
    @IBAction private func unwoundContentBlockerViewController(_ segue: UIStoryboardSegue) {
    }

    // MARK: Development
    
//    private func truncateDebugLog() {
//        connectionBusiness.truncateTunnelSnapshot()
//    }
    
//    private func recalculatePingTimes() {
//        PingerDaemon.shared.pingAllRegions()
//    }
    
//    private func invokeMACERequest() {
//        PIAEphemeralClient.shared()!.enableMACE(nil)
//    }
    
    private func resolveGoogleAdsDomain() {
        let resolver = DNSResolver(hostname: "google-analytics.com")
        resolver.resolve { (entries, error) in
            let addresses: [String]
            if let entries = entries, !entries.isEmpty {
                addresses = entries
            } else {
                addresses = ["Can't resolve"]
            }
            
            let alert = Macros.alert(nil, addresses.joined(separator: ","))
521
            alert.addCancelAction(L10n.Global.close)
Davide De Rosa's avatar
Davide De Rosa committed
522
523
524
525
526
527
528
529
530
531
532
533
            self.present(alert, animated: true, completion: nil)
        }
    }
    
    // MARK: Helpers
    
    @objc private func redisplaySettings() {
        var sections = SettingsViewController.allSections
        if !Flags.shared.enablesProtocolSelection {
            sections.remove(at: sections.index(of: .connection)!)
            sections.remove(at: sections.index(of: .encryption)!)
        } else {
Jose Blaya's avatar
Jose Blaya committed
534
535
            if (pendingPreferences.vpnType == IPSecProfile.vpnType ||
                pendingPreferences.vpnType == IKEv2Profile.vpnType) {
Davide De Rosa's avatar
Davide De Rosa committed
536
537
538
                sections.remove(at: sections.index(of: .encryption)!)
            }
        }
539
        if Flags.shared.enablesMACESetting {
Davide De Rosa's avatar
Davide De Rosa committed
540
            rowsBySection[.applicationSettings] = [
541
                .darkTheme,
542
                .automaticReconnection,
Davide De Rosa's avatar
Davide De Rosa committed
543
544
545
546
                .mace
            ]
        } else {
            rowsBySection[.applicationSettings] = [
547
                .darkTheme,
548
                .automaticReconnection,
Davide De Rosa's avatar
Davide De Rosa committed
549
550
            ]
        }
551
552
553
        if !Flags.shared.enablesContentBlockerSetting {
            sections.remove(at: sections.index(of: .contentBlocker)!)
        }
Davide De Rosa's avatar
Davide De Rosa committed
554
555
556
557
558
559
560
561
562
563
564
565
        if (pendingPreferences.vpnType != PIATunnelProfile.vpnType) {
            sections.remove(at: sections.index(of: .applicationInformation)!)
        }
        if !Flags.shared.enablesResetSettings {
            sections.remove(at: sections.index(of: .reset)!)
        }
        if Flags.shared.enablesDevelopmentSettings {
            sections.append(.development)
        }
        visibleSections = sections
        
        if (pendingPreferences.vpnType == PIATunnelProfile.vpnType) {
566
567
568
569
570
571
            
            let dnsSettingsEnabled = Flags.shared.enablesDNSSettings
            
            rowsBySection[.connection] = dnsSettingsEnabled ?
                [.vpnProtocolSelection, .vpnSocket, .vpnPort, .vpnDns] :
                [.vpnProtocolSelection, .vpnSocket, .vpnPort]
Davide De Rosa's avatar
Davide De Rosa committed
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
        } else {
            rowsBySection[.connection] = [
                .vpnProtocolSelection
            ]
        }
        
        tableView.reloadData()
    }
    
    private func reportUpdatedPreferences() {
        pendingVPNAction = pendingPreferences.requiredVPNAction()
    }
    
    // MARK: ModalController
    
    override func dismissModal() {
        commitChanges {
            super.dismissModal()
        }
    }
    
    // MARK: Restylable
    
    override func viewShouldRestyle() {
        super.viewShouldRestyle()
    
        // XXX: for some reason, UITableView is not affected by appearance updates
        if let viewContainer = viewContainer {
            Theme.current.applyLightBackground(viewContainer)
        }
        Theme.current.applyLightBackground(tableView)
        Theme.current.applyDividerToSeparator(tableView)
        tableView.reloadData()
    }
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
    
    ///Check if the current value of the DNS is valid. If not, reset to default PIA server
    private func validateDNSList() {
        
        if Flags.shared.enablesDNSSettings {
            var isValid = false
            for dns in DNSList.shared.dnsList {
                for (_, value) in dns {
                    if pendingOpenVPNConfiguration.dnsServers == value {
                        isValid = true
                        break
                    }
                }
            }
            
            if !isValid {
                pendingOpenVPNConfiguration.dnsServers = []
            }
        }
        
    }
Davide De Rosa's avatar
Davide De Rosa committed
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
}

extension SettingsViewController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return visibleSections.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch visibleSections[section] {
        case .connection:
            return L10n.Settings.Connection.title
            
        case .encryption:
            return L10n.Settings.Encryption.title
            
        case .applicationSettings:
            return L10n.Settings.ApplicationSettings.title
Jose Blaya's avatar
Jose Blaya committed
644
           
645
        case .autoConnectSettings:
Jose Blaya's avatar
Jose Blaya committed
646
647
            return nil

Davide De Rosa's avatar
Davide De Rosa committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        case .contentBlocker:
            return L10n.Settings.ContentBlocker.title

        case .applicationInformation:
            return L10n.Settings.ApplicationInformation.title

        case .reset:
            return L10n.Settings.Reset.title

        case .development:
            return "DEVELOPMENT"
        }
    }

    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        switch visibleSections[section] {
        case .applicationSettings:
665
            var footer: [String] = [
666
                L10n.Settings.ApplicationSettings.KillSwitch.footer
667
            ]
668
            if Flags.shared.enablesMACESetting {
Davide De Rosa's avatar
Davide De Rosa committed
669
670
671
                footer.append(L10n.Settings.ApplicationSettings.Mace.footer)
            }
            return footer.joined(separator: "\n\n")
Jose Blaya's avatar
Jose Blaya committed
672

Jose Blaya's avatar
Jose Blaya committed
673
674
675
        case .autoConnectSettings:
            return L10n.Settings.Hotspothelper.description
            
Davide De Rosa's avatar
Davide De Rosa committed
676
677
678
        case .reset:
            return L10n.Settings.Reset.footer
            
Davide De Rosa's avatar
Davide De Rosa committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        case .contentBlocker:
            return L10n.Settings.ContentBlocker.footer

        default:
            break
        }
        
        return nil
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rowsBySection[visibleSections[section]]!.count
    }
    
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
    func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
        let section = visibleSections[indexPath.section]
        guard let setting = rowsBySection[section]?[indexPath.row] else {
            fatalError("Data source is incorrect")
        }
        switch setting {
        case .username, .publicUsername, .password:
            return true
        default:
            return false
        }
    }

    func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
        return action == #selector(copy(_:))
    }

    func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
        if action == #selector(copy(_:)) {
            let cell = tableView.cellForRow(at: indexPath)
            let pasteboard = UIPasteboard.general
            pasteboard.string = cell?.detailTextLabel?.text
        }
    }
    
Davide De Rosa's avatar
Davide De Rosa committed
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Cells.setting, for: indexPath)
        cell.accessoryType = .disclosureIndicator
        cell.accessoryView = nil
        cell.selectionStyle = .default

        let section = visibleSections[indexPath.section]
        guard let setting = rowsBySection[section]?[indexPath.row] else {
            fatalError("Data source is incorrect")
        }
        
        switch setting {
        case .vpnProtocolSelection:
            cell.textLabel?.text = L10n.Settings.Connection.VpnProtocol.title
            cell.detailTextLabel?.text = pendingPreferences.vpnType.vpnTypeDescription
            if !Flags.shared.enablesProtocolSelection {
                cell.accessoryType = .none
                cell.selectionStyle = .none
            }

        case .vpnSocket:
739
            cell.textLabel?.text = L10n.Settings.Connection.SocketProtocol.title
740
            cell.detailTextLabel?.text = pendingOpenVPNSocketType?.description ?? L10n.Global.automatic
Davide De Rosa's avatar
Davide De Rosa committed
741
742
            
        case .vpnPort:
743
            cell.textLabel?.text = L10n.Settings.Connection.RemotePort.title
744
745
746
747
            guard pendingOpenVPNSocketType != nil else {
                cell.detailTextLabel?.text = L10n.Global.automatic
                break
            }
748
            cell.detailTextLabel?.text = pendingOpenVPNConfiguration.currentPort?.description ?? L10n.Global.automatic
Davide De Rosa's avatar
Davide De Rosa committed
749

750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
        case .vpnDns:
            cell.textLabel?.text = SettingsViewController.DNS
            
            let dnsValue = pendingOpenVPNConfiguration.dnsServers
            for dns in DNSList.shared.dnsList {
                for (key, value) in dns {
                    if dnsValue == value {
                        cell.detailTextLabel?.text = DNSList.shared.descriptionForKey(key)
                        break
                    }
                }
            }
            
            if !Flags.shared.enablesDNSSettings {
                cell.accessoryType = .none
                cell.selectionStyle = .none
            }

Davide De Rosa's avatar
Davide De Rosa committed
768
769
        case .encryptionCipher:
            cell.textLabel?.text = L10n.Settings.Encryption.Cipher.title
770
            cell.detailTextLabel?.text = pendingOpenVPNConfiguration.cipher.description
Davide De Rosa's avatar
Davide De Rosa committed
771
772
773
774
775
776
777
            if !Flags.shared.enablesEncryptionSettings {
                cell.accessoryType = .none
                cell.selectionStyle = .none
            }
            
        case .encryptionDigest:
            cell.textLabel?.text = L10n.Settings.Encryption.Digest.title
778
779
780
781
            guard !pendingOpenVPNConfiguration.isEncryptionGCM() else {
                cell.detailTextLabel?.text = "GCM"
                break
            }
782
            cell.detailTextLabel?.text = pendingOpenVPNConfiguration.digest.description
Davide De Rosa's avatar
Davide De Rosa committed
783
784
785
786
787
788
789
            if !Flags.shared.enablesEncryptionSettings {
                cell.accessoryType = .none
                cell.selectionStyle = .none
            }

        case .encryptionHandshake:
            cell.textLabel?.text = L10n.Settings.Encryption.Handshake.title
790
            cell.detailTextLabel?.text = pendingOpenVPNConfiguration.handshake.description
Davide De Rosa's avatar
Davide De Rosa committed
791
792
793
794
795
796
            if !Flags.shared.enablesEncryptionSettings {
                cell.accessoryType = .none
                cell.selectionStyle = .none
            }

        case .automaticReconnection:
797
            cell.textLabel?.text = L10n.Settings.ApplicationSettings.KillSwitch.title
Davide De Rosa's avatar
Davide De Rosa committed
798
799
800
801
            cell.detailTextLabel?.text = nil
            cell.accessoryView = switchPersistent
            cell.selectionStyle = .none
            switchPersistent.isOn = pendingPreferences.isPersistentConnection
802

Davide De Rosa's avatar
Davide De Rosa committed
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
        case .mace:
            cell.textLabel?.text = L10n.Settings.ApplicationSettings.Mace.title
            cell.detailTextLabel?.text = nil
            cell.accessoryView = switchMACE
            cell.selectionStyle = .none
            switchMACE.isOn = pendingPreferences.mace
            
        case .contentBlockerState:
            cell.textLabel?.text = L10n.Settings.ContentBlocker.State.title
            cell.detailTextLabel?.text = nil
            if #available(iOS 10, *) {
                cell.accessoryView = switchContentBlocker
                cell.selectionStyle = .none
                switchContentBlocker.isOn = isContentBlockerEnabled
            }
            
        case .contentBlockerRefreshRules:
            cell.textLabel?.text = L10n.Settings.ContentBlocker.Refresh.title
            cell.detailTextLabel?.text = nil
            
        case .darkTheme:
            cell.textLabel?.text = L10n.Settings.ApplicationSettings.DarkTheme.title
            cell.detailTextLabel?.text = nil
            cell.accessoryView = switchDarkMode
            cell.selectionStyle = .none
            switchDarkMode.isOn = (AppPreferences.shared.currentThemeCode == .dark)

        case .sendDebugLog:
            cell.textLabel?.text = L10n.Settings.ApplicationInformation.Debug.title
            cell.detailTextLabel?.text = nil
            
        case .resetSettings:
            cell.textLabel?.text = L10n.Settings.Reset.Defaults.title
            cell.detailTextLabel?.text = nil

//        case .truncateDebugLog:
//            cell.textLabel?.text = "Truncate debug log (disconnect first)"
//            cell.detailTextLabel?.text = nil
//
//        case .recalculatePingTimes:
//            cell.textLabel?.text = "Recalculate ping times (disconnect first)"
//            cell.detailTextLabel?.text = nil
//
//        case .invokeMACERequest:
//            cell.textLabel?.text = "Invoke MACE request"
//            cell.detailTextLabel?.text = nil

        case .resolveGoogleAdsDomain:
            cell.textLabel?.text = "Resolve google-analytics.com"
            cell.detailTextLabel?.text = nil
Jose Blaya's avatar
wip    
Jose Blaya committed
853
            
854
855
856
        case .publicUsername:
            cell.textLabel?.text = "Public username"
            cell.detailTextLabel?.text = Client.providers.accountProvider.publicUsername ?? ""
857
            cell.accessoryType = .none
858
859
860
        case .username:
            cell.textLabel?.text = "Username"
            cell.detailTextLabel?.text = Client.providers.accountProvider.currentUser?.credentials.username ?? ""
861
            cell.accessoryType = .none
862
863
864
        case .password:
            cell.textLabel?.text = "Password"
            cell.detailTextLabel?.text = Client.providers.accountProvider.currentUser?.credentials.password ?? ""
865
            cell.accessoryType = .none
Jose Blaya's avatar
wip    
Jose Blaya committed
866
        case .trustedNetworks:
867
            cell.textLabel?.text = L10n.Settings.Hotspothelper.title
Davide De Rosa's avatar
Davide De Rosa committed
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
        }

        Theme.current.applySolidLightBackground(cell)
        Theme.current.applyDetailTableCell(cell)

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let section = visibleSections[indexPath.section]
        guard let setting = rowsBySection[section]?[indexPath.row] else {
            fatalError("Data source is incorrect")
        }

        var controller: OptionsViewController?
        
        switch setting {
        case .vpnProtocolSelection:
            let options: [String] = [
Davide De Rosa's avatar
Davide De Rosa committed
887
                PIATunnelProfile.vpnType,
888
889
                IPSecProfile.vpnType,
                IKEv2Profile.vpnType,
Davide De Rosa's avatar
Davide De Rosa committed
890
891
892
893
894
            ]
            controller = OptionsViewController()
            controller?.options = options
            controller?.selectedOption = pendingPreferences.vpnType
            
895
        case .vpnSocket:
896
897
898
899
900
901
            let options: [PIATunnelProvider.SocketType] = [
                .udp,
                .tcp
            ]
            controller = OptionsViewController()
            controller?.options = options.map { $0.rawValue }
902
903
            controller?.options.insert(SettingsViewController.AUTOMATIC_SOCKET, at: 0)
            controller?.selectedOption = pendingOpenVPNSocketType?.rawValue ?? SettingsViewController.AUTOMATIC_SOCKET
904

Davide De Rosa's avatar
Davide De Rosa committed
905
        case .vpnPort:
906
907
908
            guard let socketType = pendingOpenVPNSocketType else {
                break
            }
909
            let availablePorts = Client.providers.serverProvider.currentServersConfiguration.vpnPorts
910
            var options = (socketType == .udp) ? availablePorts.udp : availablePorts.tcp
911
912
913
914
            options.insert(SettingsViewController.AUTOMATIC_PORT, at: 0)
            controller = OptionsViewController()
            controller?.options = options
            controller?.selectedOption = pendingOpenVPNConfiguration.currentPort ?? SettingsViewController.AUTOMATIC_PORT
Davide De Rosa's avatar
Davide De Rosa committed
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
        case .vpnDns:
            guard Flags.shared.enablesDNSSettings else {
                break
            }
            
            controller = OptionsViewController()
            if let dnsList = DNSList.shared.dnsList {
                controller?.options = dnsList.compactMap {
                    if let first = $0.first {
                        return first.key
                    }
                    return nil
                }
            }
            
            if let options = controller?.options,
                !options.contains(DNSList.CUSTOM_DNS_KEY) {
                controller?.options.append(DNSList.CUSTOM_DNS_KEY)
            } else {
                for dns in DNSList.shared.dnsList {
                    for (key, value) in dns {
                        if key == DNSList.CUSTOM_DNS_KEY {
                            if !value.isEmpty {
                                controller?.navigationItem.rightBarButtonItem = UIBarButtonItem(
                                    title: L10n.Global.edit,
                                    style: .plain,
                                    target: self,
                                    action: #selector(edit(_:))
                                )
                            }
                        }
                    }
                }
            }
            
            controller?.selectedOption = pendingOpenVPNConfiguration.dnsServers
            
Davide De Rosa's avatar
Davide De Rosa committed
953
954
955
956
957
        case .encryptionCipher:
            guard Flags.shared.enablesEncryptionSettings else {
                break
            }
            let options: [PIATunnelProvider.Cipher] = [
958
959
                .aes128gcm,
                .aes256gcm,
Davide De Rosa's avatar
Davide De Rosa committed
960
961
962
963
964
                .aes128cbc,
                .aes256cbc
            ]
            controller = OptionsViewController()
            controller?.options = options.map { $0.rawValue }
965
            controller?.selectedOption = pendingOpenVPNConfiguration.cipher.rawValue
Davide De Rosa's avatar
Davide De Rosa committed
966
967
968
969
970

        case .encryptionDigest:
            guard Flags.shared.enablesEncryptionSettings else {
                break
            }
971
972
973
            guard !pendingOpenVPNConfiguration.isEncryptionGCM() else {
                break
            }
Davide De Rosa's avatar
Davide De Rosa committed
974
975
976
977
978
979
            let options: [PIATunnelProvider.Digest] = [
                .sha1,
                .sha256
            ]
            controller = OptionsViewController()
            controller?.options = options.map { $0.rawValue }
980
            controller?.selectedOption = pendingOpenVPNConfiguration.digest.rawValue
Davide De Rosa's avatar
Davide De Rosa committed
981
982
983
984
985
986
987
988
989
990

        case .encryptionHandshake:
            guard Flags.shared.enablesEncryptionSettings else {
                break
            }
            let options: [PIATunnelProvider.Handshake] = [
                .rsa2048,
                .rsa3072,
                .rsa4096,
                .ecc256r1,
991
                .ecc256k1,
Davide De Rosa's avatar
Davide De Rosa committed
992
993
994
995
                .ecc521r1
            ]
            controller = OptionsViewController()
            controller?.options = options.map { $0.rawValue }
996
            controller?.selectedOption = pendingOpenVPNConfiguration.handshake.rawValue
Davide De Rosa's avatar
Davide De Rosa committed
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
            
        case .contentBlockerState:
            if #available(iOS 10, *) {
                
            } else {
                showContentBlockerTutorial()
            }
            
        case .contentBlockerRefreshRules:
            refreshContentBlockerRules()

        case .sendDebugLog:
            submitTunnelLog()
            
        case .resetSettings:
            resetToDefaultSettings()

//        case .truncateDebugLog:
//            truncateDebugLog()
//
//        case .recalculatePingTimes:
//            recalculatePingTimes()
//
//        case .invokeMACERequest:
//            invokeMACERequest()

        case .resolveGoogleAdsDomain:
            resolveGoogleAdsDomain()

Jose Blaya's avatar
wip    
Jose Blaya committed
1026
1027
1028
        case .trustedNetworks:
            self.perform(segue: StoryboardSegue.Main.trustedNetworksSegueIdentifier)

Davide De Rosa's avatar
Davide De Rosa committed
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
        default:
            break
        }

        if let controller = controller {
            guard let cell = tableView.cellForRow(at: indexPath) else {
                fatalError("Cell not found at \(indexPath)")
            }

            controller.title = cell.textLabel?.text
            controller.tag = setting.rawValue
            controller.delegate = self

            parent?.navigationItem.setEmptyBackButton()
            navigationController?.pushViewController(controller, animated: true)
        }

        tableView.deselectRow(at: indexPath, animated: true)
    }

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        Theme.current.applyTableSectionHeader(view)
    }

    func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        Theme.current.applyTableSectionFooter(view)
    }
}

extension SettingsViewController: OptionsViewControllerDelegate {
    func backgroundColorForOptionsController(_ controller: OptionsViewController) -> UIColor {
        return Theme.current.palette.lightBackground
    }
    
    func tableStyleForOptionsController(_ controller: OptionsViewController) -> UITableViewStyle {
        return .grouped
    }
    
    func optionsController(_ controller: OptionsViewController, didLoad tableView: UITableView) {
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.cellLayoutMarginsFollowReadableWidth = false
    }

    func optionsController(_ controller: OptionsViewController, tableView: UITableView, reusableCellAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    }
    
    func optionsController(_ controller: OptionsViewController, renderOption option: AnyHashable, in cell: UITableViewCell, at row: Int, isSelected: Bool) {
        guard let setting = Setting(rawValue: controller.tag) else {
            fatalError("Unhandled setting \(controller.tag)")
        }

        switch setting {
        case .vpnProtocolSelection:
1083
1084
            let vpnType = option as? String
            cell.textLabel?.text = vpnType?.vpnTypeDescription
Davide De Rosa's avatar
Davide De Rosa committed
1085
            
1086
        case .vpnSocket:
1087
            let rawSocketType = option as? String
1088
1089
1090
1091
1092
            if rawSocketType != SettingsViewController.AUTOMATIC_SOCKET {
                cell.textLabel?.text = rawSocketType?.description
            } else {
                cell.textLabel?.text = L10n.Global.automatic
            }
1093
            
Davide De Rosa's avatar
Davide De Rosa committed
1094
        case .vpnPort:
1095
            if let port = option as? UInt16, (port != SettingsViewController.AUTOMATIC_PORT) {
Davide De Rosa's avatar
Davide De Rosa committed
1096
1097
1098
1099
                cell.textLabel?.text = (option as? UInt16)?.description
            } else {
                cell.textLabel?.text = L10n.Global.automatic
            }
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
            
        case .vpnDns:
            if let option = option as? String {
                cell.textLabel?.text = DNSList.shared.descriptionForKey(option)
                if option == DNSList.CUSTOM_DNS_KEY {
                    var isFound = false
                    for dns in DNSList.shared.dnsList {
                        for (key, value) in dns {
                            if key == option {
                                isFound = true
                                if value.isEmpty {
                                    cell.accessoryType = .disclosureIndicator
                                }
                            }
                        }
                    }
                    if !isFound { //first time
                        cell.accessoryType = .disclosureIndicator
                    }
                }
            }
Davide De Rosa's avatar
Davide De Rosa committed
1121
        case .encryptionCipher:
1122
1123
            let rawCipher = option as! String
            cell.textLabel?.text = PIATunnelProvider.Cipher(rawValue: rawCipher)?.description
Davide De Rosa's avatar
Davide De Rosa committed
1124
1125

        case .encryptionDigest:
1126
1127
            let rawDigest = option as! String
            cell.textLabel?.text = PIATunnelProvider.Digest(rawValue: rawDigest)?.description
Davide De Rosa's avatar
Davide De Rosa committed
1128
1129

        case .encryptionHandshake:
1130
1131
            let rawHandshake = option as! String
            cell.textLabel?.text = PIATunnelProvider.Handshake(rawValue: rawHandshake)?.description
Davide De Rosa's avatar
Davide De Rosa committed
1132
1133
1134
1135
1136
1137
1138

        default:
            break
        }
        
        cell.accessoryView = (isSelected ? imvSelectedOption : nil)

1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
        if setting == .vpnDns,
            let option = option as? String {
            let dnsJoinedValue = pendingOpenVPNConfiguration.dnsServers.joined()
            for dns in DNSList.shared.dnsList {
                for (key, value) in dns {
                    if key == option,
                        dnsJoinedValue == value.joined() {
                        cell.accessoryView = imvSelectedOption
                    }
                }
            }
        }
        
Davide De Rosa's avatar
Davide De Rosa committed
1152
1153
1154
1155
1156
1157
1158
1159
1160
        Theme.current.applySolidLightBackground(cell)
        Theme.current.applyDetailTableCell(cell)
    }

    func optionsController(_ controller: OptionsViewController, didSelectOption option: AnyHashable, at row: Int) {
        guard let setting = Setting(rawValue: controller.tag) else {
            fatalError("Unhandled setting \(controller.tag)")
        }

1161
1162
        let serversCfg = Client.providers.serverProvider.currentServersConfiguration

Davide De Rosa's avatar
Davide De Rosa committed
1163
1164
        switch setting {
        case .vpnProtocolSelection:
1165
1166
            let vpnType = option as! String
            pendingPreferences.vpnType = vpnType
Davide De Rosa's avatar
Davide De Rosa committed
1167
            
1168
        case .vpnSocket:
1169
            let rawSocketType = option as! String
1170
            let optSocketType = PIATunnelProvider.SocketType(rawValue: rawSocketType)
1171
1172
1173

            let currentProtocols = pendingOpenVPNConfiguration.endpointProtocols
            var newProtocols: [PIATunnelProvider.EndpointProtocol] = []
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183

            if let socketType = optSocketType {
                let ports = (socketType == .udp) ? serversCfg.vpnPorts.udp : serversCfg.vpnPorts.tcp
                if currentProtocols.count == 1, let currentPort = pendingOpenVPNConfiguration?.currentPort, ports.contains(currentPort) {
                    newProtocols.append(PIATunnelProvider.EndpointProtocol(socketType, currentPort, .pia))
                } else {
                    for port in ports {
                        newProtocols.append(PIATunnelProvider.EndpointProtocol(socketType, port, .pia))
                    }
                }
1184
            } else {
1185
1186
1187
1188
1189
1190
1191
//                for port in serversCfg.vpnPorts.udp {
//                    newProtocols.append(PIATunnelProvider.EndpointProtocol(.udp, port, .pia))
//                }
//                for port in serversCfg.vpnPorts.tcp {
//                    newProtocols.append(PIATunnelProvider.EndpointProtocol(.tcp, port, .pia))
//                }
                newProtocols = AppConfiguration.VPN.piaAutomaticProtocols
1192
            }
1193
            pendingOpenVPNSocketType = optSocketType
1194
            pendingOpenVPNConfiguration.endpointProtocols = newProtocols
1195

Davide De Rosa's avatar
Davide De Rosa committed
1196
        case .vpnPort:
1197
1198
1199
1200
            let port = option as! UInt16

            var newProtocols: [PIATunnelProvider.EndpointProtocol] = []
            if (port != SettingsViewController.AUTOMATIC_PORT) {
1201
1202
1203
1204
                guard let socketType = pendingOpenVPNSocketType else {
                    fatalError("Port cannot be set manually when socket type is automatic")
                }
                newProtocols.append(PIATunnelProvider.EndpointProtocol(socketType, port, .pia))
1205
            } else {
1206
1207
1208
1209
                if (pendingOpenVPNSocketType == nil) {
                    newProtocols = AppConfiguration.VPN.piaAutomaticProtocols
                }
                else if (pendingOpenVPNSocketType == .udp) {
1210
1211
1212
1213
                    for port in serversCfg.vpnPorts.udp {
                        newProtocols.append(PIATunnelProvider.EndpointProtocol(.udp, port, .pia))
                    }
                }
1214
                else if (pendingOpenVPNSocketType == .tcp) {
1215
1216
1217
                    for port in serversCfg.vpnPorts.tcp {
                        newProtocols.append(PIATunnelProvider.EndpointProtocol(.tcp, port, .pia))
                    }
1218
1219
1220
                }
            }
            pendingOpenVPNConfiguration.endpointProtocols = newProtocols
Davide De Rosa's avatar
Davide De Rosa committed
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
        case .vpnDns:
            if let option = option as? String {
                var isFound = false
                
                for dns in DNSList.shared.dnsList {
                    for (key, value) in dns {
                        if key == option {
                            isFound = true
                            pendingOpenVPNConfiguration.dnsServers = value
                            break
                        }
                    }
                }
                
                if !isFound && option == DNSList.CUSTOM_DNS_KEY {
                    let alertController = Macros.alert(L10n.Settings.Dns.Custom.dns,
                                                       L10n.Settings.Dns.Alert.Create.message)
                    let saveAction = UIAlertAction(title: L10n.Global.ok, style: UIAlertActionStyle.default, handler: { alert -> Void in
                        self.perform(segue: StoryboardSegue.Main.customDNSSegueIdentifier)
                    })
                    let cancelAction = UIAlertAction(title: L10n.Global.cancel, style: UIAlertActionStyle.default,
                                                     handler: nil)
                    
                    alertController.addAction(saveAction)
                    alertController.addAction(cancelAction)
                    
                    self.present(alertController,
                                 animated: true,
                                 completion: nil)
                }
                
            }
Davide De Rosa's avatar
Davide De Rosa committed
1254
        case .encryptionCipher:
1255
            let rawCipher = option as! String
1256
            pendingOpenVPNConfiguration.cipher = PIATunnelProvider.Cipher(rawValue: rawCipher)!
Davide De Rosa's avatar
Davide De Rosa committed
1257
1258

        case .encryptionDigest:
1259
            let rawDigest = option as! String
1260
            pendingOpenVPNConfiguration.digest = PIATunnelProvider.Digest(rawValue: rawDigest)!
Davide De Rosa's avatar
Davide De Rosa committed
1261
1262

        case .encryptionHandshake:
1263
            let rawHandshake = option as! String
1264
            pendingOpenVPNConfiguration.handshake = PIATunnelProvider.Handshake(rawValue: rawHandshake)!
Davide De Rosa's avatar
Davide De Rosa committed
1265
1266
1267
1268
1269

        default:
            break
        }
        
1270
1271
1272
1273
1274
1275
        savePreferences()
        navigationController?.popViewController(animated: true)

    }
    
    private func savePreferences() {
1276
        log.debug("OpenVPN endpoints: \(pendingOpenVPNConfiguration.endpointProtocols)")
1277
        pendingPreferences.setVPNCustomConfiguration(pendingOpenVPNConfiguration.build(), for: pendingPreferences.vpnType)
1278
        
Davide De Rosa's avatar
Davide De Rosa committed
1279
1280
1281
1282
        redisplaySettings()
        reportUpdatedPreferences()
    }
}
1283
1284

private extension PIATunnelProvider.ConfigurationBuilder {
1285
1286
1287
1288
1289
1290
1291
//    var currentSocketType: PIATunnelProvider.SocketType {
//        guard let currentType = endpointProtocols.first?.socketType else {
//            fatalError("Zero current protocols")
//        }
//        return currentType
//    }

1292
1293
1294
1295
1296
1297
1298
1299
1300
    var currentPort: UInt16? {
        guard endpointProtocols.count == 1 else {
            return nil
        }
        guard let port = endpointProtocols.first?.port else {
            fatalError("Zero current protocols")
        }
        return port
    }
1301
1302
1303
1304

    func isEncryptionGCM() -> Bool {
        return (cipher == .aes128gcm) || (cipher == .aes256gcm)
    }
1305
}
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323

extension SettingsViewController: SettingsViewControllerDelegate {
    
    func updateSetting(_ setting: Setting, withValue value: Any?) {
        switch setting {
        case .vpnDns:
            if let settingValue = value as? String {
                pendingOpenVPNConfiguration.dnsServers = DNSList.shared.valueForKey(settingValue)
            }
        default:
            break
        }
        
        savePreferences()

    }
    
}