-
-
Notifications
You must be signed in to change notification settings - Fork 245
/
SPConnectionController.m
3727 lines (2993 loc) · 136 KB
/
SPConnectionController.m
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
//
// SPConnectionController.m
// sequel-pro
//
// Created by Stuart Connolly (stuconnolly.com) on November 15, 2010.
// Copyright (c) 2010 Stuart Connolly. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// More info at <https://github.com/sequelpro/sequelpro>
#import "SPConnectionController.h"
#import "SPDatabaseDocument.h"
#import "SPAppController.h"
#import "SPPreferenceController.h"
#import "ImageAndTextCell.h"
#import "RegexKitLite.h"
#import "SPKeychain.h"
#import "SPSSHTunnel.h"
#import "SPTableTextFieldCell.h"
#import "SPFavoritesController.h"
#import "SPFavoriteNode.h"
#import "SPGeneralPreferencePane.h"
#import "SPTreeNode.h"
#import "SPFavoritesExporter.h"
#import "SPFavoritesImporter.h"
#import "SPThreadAdditions.h"
#import "SPFavoriteColorSupport.h"
#import "SPNamedNode.h"
#import "SPWindowController.h"
#import "SPFavoritesOutlineView.h"
#import "SPCategoryAdditions.h"
#import "SPFavoriteTextFieldCell.h"
#import "SPGroupNode.h"
#import "SPSplitView.h"
#import "SPColorSelectorView.h"
#import "SPFunctions.h"
#import "SPBundleHTMLOutputController.h"
#import "SPBundleManager.h"
@import Firebase;
#import <SPMySQL/SPMySQL.h>
#import "sequel-ace-Swift.h"
// Constants
static NSString *SPRemoveNode = @"RemoveNode";
static NSString *SPExportFavoritesFilename = @"SequelProFavorites.plist";
static NSString *SPLocalhostAddress = @"127.0.0.1";
static NSString *SPDatabaseImage = @"database-small";
static NSString *SPQuickConnectImage = @"quick-connect-icon.pdf";
static NSString *SPQuickConnectImageWhite = @"quick-connect-icon-white.pdf";
static NSString *SPConnectionViewNibName = @"ConnectionView";
const static NSInteger SPUseServerTimeZoneTag = -1;
const static NSInteger SPUseSystemTimeZoneTag = -2;
@interface SPConnectionController ()
// Privately redeclare as read/write to get the synthesized setter
@property (readwrite, assign) BOOL isEditingConnection;
@property (readwrite, assign) BOOL allowSplitViewResizing;
@property (readwrite, assign) BOOL errorShowing;
- (void)_saveCurrentDetailsCreatingNewFavorite:(BOOL)createNewFavorite validateDetails:(BOOL)validateDetails;
- (void)_sortFavorites;
- (void)_sortTreeNode:(SPTreeNode *)node usingKey:(NSString *)key;
- (void)_favoriteTypeDidChange;
- (void)_reloadFavoritesViewData;
- (void)_updateFavoriteFirstResponder;
- (void)_restoreConnectionInterface;
- (void)_selectNode:(SPTreeNode *)node;
- (void)_scrollToSelectedNode;
- (void)_removeNode:(SPTreeNode *)node;
- (void)_removeAllPasswordsForNode:(SPTreeNode *)node;
- (void)_refreshBookmarks;
- (NSNumber *)_createNewFavoriteID;
- (SPTreeNode *)_favoriteNodeForFavoriteID:(NSInteger)favoriteID;
- (NSString *)_stripInvalidCharactersFromString:(NSString *)subject;
- (NSString *)_generateNameForConnection;
- (void)_startEditingConnection;
- (void)_documentWillClose:(NSNotification *)notification;
static NSComparisonResult _compareFavoritesUsingKey(id favorite1, id favorite2, void *key);
#pragma mark - SPConnectionControllerDelegate
- (void)_stopEditingConnection;
#pragma mark - SPConnectionHandlerPrivateAPI
- (void)_showConnectionTestResult:(NSString *)resultString;
#pragma mark - SPConnectionControllerDelegate_Private_API
- (void)_setNodeIsExpanded:(BOOL)expanded fromNotification:(NSNotification *)notification;
#pragma mark - SPConnectionControllerInitializer_Private_API
- (void)_restoreOutlineViewStateNode:(SPTreeNode *)node;
- (void)_processFavoritesDataChange:(NSNotification *)aNotification;
- (void)scrollViewFrameChanged:(NSNotification *)aNotification;
@end
@implementation SPConnectionController
@synthesize delegate;
@synthesize type;
@synthesize name;
@synthesize host;
@synthesize user;
@synthesize password;
@synthesize database;
@synthesize socket;
@synthesize port;
@synthesize colorIndex;
@synthesize timeZoneMode;
@synthesize timeZoneIdentifier;
@synthesize allowDataLocalInfile;
@synthesize enableClearTextPlugin;
@synthesize useSSL;
@synthesize sslKeyFileLocationEnabled;
@synthesize sslKeyFileLocation;
@synthesize sslCertificateFileLocationEnabled;
@synthesize sslCertificateFileLocation;
@synthesize sslCACertFileLocationEnabled;
@synthesize sslCACertFileLocation;
@synthesize sshHost;
@synthesize sshUser;
@synthesize sshPassword;
@synthesize sshKeyLocationEnabled;
@synthesize sshKeyLocation;
@synthesize sshPort;
@synthesize useCompression;
@synthesize bookmarks;
@synthesize allowSplitViewResizing;
@synthesize connectionKeychainID = connectionKeychainID;
@synthesize connectionKeychainItemName;
@synthesize connectionKeychainItemAccount;
@synthesize connectionSSHKeychainItemName;
@synthesize connectionSSHKeychainItemAccount;
@synthesize socketHelpWindowUUID;
@synthesize isConnecting;
@synthesize isEditingConnection;
@synthesize errorShowing;
+ (void)initialize {
}
- (NSString *)keychainPassword
{
NSString *kcItemName = [self connectionKeychainItemName];
// If no keychain item is available, return an empty password
if (!kcItemName) return nil;
// Otherwise, pull the password from the keychain using the details from this connection
NSString *kcPassword = [keychain getPasswordForName:kcItemName account:[self connectionKeychainItemAccount]];
return kcPassword;
}
- (NSString *)keychainPasswordForSSH
{
if (![self connectionKeychainItemName]) return nil;
// Otherwise, pull the password from the keychain using the details from this connection
NSString *kcSSHPassword = [keychain getPasswordForName:connectionSSHKeychainItemName account:connectionSSHKeychainItemAccount];
return kcSSHPassword;
}
#pragma mark -
#pragma mark Connection processes
-(BOOL)connected{
SPReachability *reachability = [SPReachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}
/**
* Starts the connection process; invoked when user hits the connect button
* or double-clicks on a favourite.
* Error-checks fields as required, and triggers connection of MySQL or any
* connection proxies in use.
*/
- (IBAction)initiateConnection:(id)sender
{
// If this action was triggered via a double-click on the favorites outline view,
// ensure that one of the connections was double-clicked, not the area above or below
if (sender == favoritesOutlineView && [favoritesOutlineView clickedRow] <= 0) return;
// If triggered via the "Test Connection" button, set the state - otherwise clear it
isTestingConnection = (sender == testConnectButton);
NSFileManager *fileManager = [NSFileManager defaultManager];
// Ensure that host is not empty if this is a TCP/IP or SSH connection
if (([self type] == SPTCPIPConnection || [self type] == SPSSHTunnelConnection) && ![[self host] length]) {
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"Insufficient connection details", @"insufficient details message") message:NSLocalizedString(@"Insufficient details provided to establish a connection. Please enter at least the hostname.", @"insufficient details informative message") callback:nil];
return;
}
// If SSH is enabled, ensure that the SSH host is not nil
if ([self type] == SPSSHTunnelConnection && ![[self sshHost] length]) {
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"Insufficient connection details", @"insufficient details message") message:NSLocalizedString(@"Insufficient details provided to establish a connection. Please enter the hostname for the SSH Tunnel, or disable the SSH Tunnel.", @"insufficient SSH tunnel details informative message") callback:nil];
return;
}
// If an SSH key has been provided, verify it exists
if ([self type] == SPSSHTunnelConnection && sshKeyLocationEnabled && sshKeyLocation) {
if (![fileManager fileExistsAtPath:[sshKeyLocation stringByExpandingTildeInPath]]) {
[self setSshKeyLocationEnabled:NSOffState];
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"SSH Key not found", @"SSH key check error") message:NSLocalizedString(@"A SSH key location was specified, but no file was found in the specified location. Please re-select the key and try again.", @"SSH key not found message") callback:nil];
return;
}
}
// If SSL keys have been supplied, verify they exist
if (([self type] == SPTCPIPConnection || [self type] == SPSocketConnection) && [self useSSL]) {
if (sslKeyFileLocationEnabled && sslKeyFileLocation &&
![fileManager fileExistsAtPath:[sslKeyFileLocation stringByExpandingTildeInPath]])
{
[self setSslKeyFileLocationEnabled:NSOffState];
[self setSslKeyFileLocation:nil];
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"SSL Key File not found", @"SSL key file check error") message:NSLocalizedString(@"A SSL key file location was specified, but no file was found in the specified location. Please re-select the key file and try again.", @"SSL key file not found message") callback:nil];
return;
}
if (sslCertificateFileLocationEnabled && sslCertificateFileLocation &&
![fileManager fileExistsAtPath:[sslCertificateFileLocation stringByExpandingTildeInPath]])
{
[self setSslCertificateFileLocationEnabled:NSOffState];
[self setSslCertificateFileLocation:nil];
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"SSL Certificate File not found", @"SSL certificate file check error") message:NSLocalizedString(@"A SSL certificate location was specified, but no file was found in the specified location. Please re-select the certificate and try again.", @"SSL certificate file not found message") callback:nil];
return;
}
if (sslCACertFileLocationEnabled && sslCACertFileLocation &&
![fileManager fileExistsAtPath:[sslCACertFileLocation stringByExpandingTildeInPath]])
{
[self setSslCACertFileLocationEnabled:NSOffState];
[self setSslCACertFileLocation:nil];
[NSAlert createWarningAlertWithTitle:NSLocalizedString(@"SSL Certificate Authority File not found", @"SSL certificate authority file check error") message:NSLocalizedString(@"A SSL Certificate Authority certificate location was specified, but no file was found in the specified location. Please re-select the Certificate Authority certificate and try again.", @"SSL CA certificate file not found message") callback:nil];
return;
}
}
// Basic details have validated - start the connection process animating
isConnecting = YES;
cancellingConnection = NO;
errorShowing = NO;
// Disable the favorites outline view to prevent further connections attempts
[favoritesOutlineView setEnabled:NO];
[helpButton setHidden:YES];
[connectButton setEnabled:NO];
[testConnectButton setEnabled:NO];
[progressIndicator startAnimation:self];
[progressIndicatorText setHidden:NO];
// Start the current tab's progress indicator
[dbDocument setIsProcessing:YES];
// If the password(s) are marked as having been originally sourced from a keychain, check whether they
// have been changed or not; if not, leave the mark in place and remove the password from the field
// for increased security.
if (connectionKeychainItemName && !isTestingConnection) {
if ([[keychain getPasswordForName:connectionKeychainItemName account:connectionKeychainItemAccount] isEqualToString:[self password]]) {
[self setPassword:@"SequelAceSecretPassword"];
[[standardPasswordField undoManager] removeAllActionsWithTarget:standardPasswordField];
[[socketPasswordField undoManager] removeAllActionsWithTarget:socketPasswordField];
[[sshPasswordField undoManager] removeAllActionsWithTarget:sshPasswordField];
}
}
if (connectionSSHKeychainItemName && !isTestingConnection) {
if ([[keychain getPasswordForName:connectionSSHKeychainItemName account:connectionSSHKeychainItemAccount] isEqualToString:[self sshPassword]]) {
[self setSshPassword:@"SequelAceSecretPassword"];
[[sshSSHPasswordField undoManager] removeAllActionsWithTarget:sshSSHPasswordField];
}
}
// Inform the delegate that we are starting the connection process
if (delegate && [delegate respondsToSelector:@selector(connectionControllerInitiatingConnection:)]) {
[delegate connectionControllerInitiatingConnection:self];
}
// Trim whitespace and newlines from the host field before attempting to connect
[self setHost:[[self host] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
// Initiate the SSH connection process for tunnels
if ([self type] == SPSSHTunnelConnection) {
[self performSelector:@selector(initiateSSHTunnelConnection) withObject:nil afterDelay:0.0];
return;
}
// ...or start the MySQL connection process directly
[self performSelector:@selector(initiateMySQLConnection) withObject:nil afterDelay:0.0];
}
/**
* Cancels the current connection - both SSH and MySQL.
*/
- (IBAction)cancelConnection:(id)sender
{
[connectButton setEnabled:NO];
[progressIndicatorText setStringValue:NSLocalizedString(@"Cancelling...", @"cancelling task status message")];
[progressIndicatorText display];
cancellingConnection = YES;
// Cancel the MySQL connection - handing it off to a background thread - if one is present
if (mySQLConnection) {
[mySQLConnection setDelegate:nil];
[NSThread detachNewThreadWithName:SPCtxt(@"SPConnectionController cancellation background disconnect",dbDocument) target:mySQLConnection selector:@selector(disconnect) object:nil];
}
// Cancel the SSH tunnel if present
if (sshTunnel) {
[sshTunnel disconnect];
}
// Restore the connection interface
[self _restoreConnectionInterface];
}
#pragma mark -
#pragma mark Interface interaction
/**
* Registered to be the double click action of the favorites outline view.
*/
- (void)nodeDoubleClicked:(id)sender
{
SPTreeNode *node = [favoritesOutlineView itemForDoubleAction];
if (node) {
if (node == quickConnectItem) {
return;
}
// Only proceed to initiate a connection if a leaf node (i.e. a favorite and not a group) was double clicked.
if (![node isGroup]) {
[self initiateConnection:self];
}
// Otherwise start editing the group node's name
else {
[favoritesOutlineView editColumn:0 row:[favoritesOutlineView selectedRow] withEvent:nil select:YES];
}
}
}
/**
* Opens the SSH/SSL key selection window, ready to select a key file.
*/
- (IBAction)chooseKeyLocation:(NSButton *)sender
{
NSString *directoryPath = nil;
NSString *filePath = nil;
NSView *accessoryView = nil;
// If the button was toggled off, ensure editing is ended
if ([sender state] == NSOffState) {
[self _startEditingConnection];
}
// Switch details by sender.
// First, SSH keys:
if (sender == sshSSHKeyButton) {
// If the custom key location is currently disabled - after the button
// action - leave it disabled and return without showing the sheet.
if (!sshKeyLocationEnabled) {
[self setSshKeyLocation:nil];
return;
}
filePath = nil;
directoryPath = @"~/.ssh";
accessoryView = sshKeyLocationHelp;
}
// SSL key file location:
else if (sender == standardSSLKeyFileButton || sender == socketSSLKeyFileButton || sender == sslOverSSHKeyFileButton) {
if ([sender state] == NSOffState) {
[self setSslKeyFileLocation:nil];
return;
}
accessoryView = sslKeyFileLocationHelp;
}
// SSL certificate file location:
else if (sender == standardSSLCertificateButton || sender == socketSSLCertificateButton || sender == sslOverSSHCertificateButton) {
if ([sender state] == NSOffState) {
[self setSslCertificateFileLocation:nil];
return;
}
accessoryView = sslCertificateLocationHelp;
}
// SSL CA certificate file location:
else if (sender == standardSSLCACertButton || sender == socketSSLCACertButton || sender == sslOverSSHCACertButton) {
if ([sender state] == NSOffState) {
[self setSslCACertFileLocation:nil];
return;
}
accessoryView = sslCACertLocationHelp;
}
keySelectionPanel = [NSOpenPanel openPanel]; // retain/release needed on OS X ≤ 10.6 according to Apple doc
[keySelectionPanel setCanChooseFiles:YES];
[keySelectionPanel setCanChooseDirectories:YES];
[keySelectionPanel setCanCreateDirectories:YES];
[keySelectionPanel setShowsHiddenFiles:[prefs boolForKey:SPHiddenKeyFileVisibilityKey]];
[keySelectionPanel setAccessoryView:accessoryView];
//on os x 10.11+ the accessory view will be hidden by default and has to be made visible
if(accessoryView && [keySelectionPanel respondsToSelector:@selector(setAccessoryViewDisclosed:)]) {
[keySelectionPanel setAccessoryViewDisclosed:YES];
}
[keySelectionPanel setDelegate:self];
[keySelectionPanel beginSheetModalForWindow:[dbDocument parentWindow] completionHandler:^(NSInteger returnCode){
NSString *selectedFilePath=[[self->keySelectionPanel URL] path];
NSError *err=nil;
NSMutableString *classStr = [NSMutableString string];
[classStr appendStringOrNil:NSStringFromClass(self->keySelectionPanel.URL.class)];
SPLog(@"self->keySelectionPanel.URL.class: %@", classStr);
// check it's really a URL
if(![self->keySelectionPanel.URL isKindOfClass:[NSURL class]]){
SPLog(@"self->keySelectionPanel.URL is not a valid URL: %@", classStr);
CLS_LOG(@"self->keySelectionPanel.URL is not a valid URL: %@", classStr);
NSView *helpView = [[[SPAppDelegate preferenceController] generalPreferencePane] modifyAndReturnBookmarkHelpView];
NSString *alertMessage = [NSString stringWithFormat:NSLocalizedString(@"The selected file is not a valid file.\n\nPlease try again.\n\nClass: %@", @"error while selecting file message"),
classStr];
[NSAlert createAccessoryWarningAlertWithTitle:NSLocalizedString(@"File Selection Error", @"error while selecting file message") message:alertMessage accessoryView:helpView callback:^{
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: @"self->keySelectionPanel.URL is not a valid URL",
@"func": [NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__],
@"class": classStr
};
SPLog(@"userInfo: %@", userInfo);
[FIRCrashlytics.crashlytics recordError:[NSError errorWithDomain:@"chooseFileConnectionController" code:1 userInfo:userInfo]];
}];
}
else{
SPLog(@"calling addBookmarkForUrl");
CLS_LOG(@"calling addBookmarkForUrl");
// this needs to be read-only to handle keys with 400 perms so we add the bitwise OR NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess
if([SecureBookmarkManager.sharedInstance addBookmarkForUrl:self->keySelectionPanel.URL options:(NSURLBookmarkCreationWithSecurityScope|NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess) isForStaleBookmark:NO] == YES){
SPLog(@"addBookmarkForUrl success");
CLS_LOG(@"addBookmarkForUrl success");
}
else{
SPLog(@"addBookmarkForUrl failed");
CLS_LOG(@"addBookmarkForUrl failed");
// JCS - should we stop here?
// No just the act of selecting the file in the NSOpenPanel calls startAccessingSecurityScopedResource
// the only downside of this failing is that we won't have a bookmark,
// and therefore no access on the next app start
}
}
// SSH key file selection
if (sender == self->sshSSHKeyButton) {
if (returnCode == NSModalResponseCancel) {
[self setSshKeyLocationEnabled:NSOffState];
[self setSshKeyLocation:nil];
return;
}
[self setSshKeyLocation:selectedFilePath];
}
// SSL key file selection
else if (sender == self->standardSSLKeyFileButton || sender == self->socketSSLKeyFileButton || sender == self->sslOverSSHKeyFileButton) {
if (returnCode == NSModalResponseCancel) {
[self setSslKeyFileLocationEnabled:NSOffState];
[self setSslKeyFileLocation:nil];
return;
}
if( [self validateKeyFile:self->keySelectionPanel.URL error:&err] == NO ){
NSLog(@"Problem with key file - %@ : %@",[err localizedDescription], [err localizedRecoverySuggestion]);
[self showValidationAlertForError:err];
return; // don't copy the bad key
}
[self setSslKeyFileLocation:selectedFilePath];
}
// SSL certificate file selection
else if (sender == self->standardSSLCertificateButton || sender == self->socketSSLCertificateButton || sender == self->sslOverSSHCertificateButton) {
if (returnCode == NSModalResponseCancel) {
[self setSslCertificateFileLocationEnabled:NSOffState];
[self setSslCertificateFileLocation:nil];
return;
}
if( [self validateCertFile:self->keySelectionPanel.URL error:&err] == NO ){
NSLog(@"Problem with cert file - %@ : %@",[err localizedDescription], [err localizedRecoverySuggestion]);
[self showValidationAlertForError:err];
return; // don't copy the bad cert
}
[self setSslCertificateFileLocation:selectedFilePath];
}
// SSL CA certificate file selection
else if (sender == self->standardSSLCACertButton || sender == self->socketSSLCACertButton || sender == self->sslOverSSHCACertButton) {
if (returnCode == NSModalResponseCancel) {
[self setSslCACertFileLocationEnabled:NSOffState];
[self setSslCACertFileLocation:nil];
return;
}
[self setSslCACertFileLocation:selectedFilePath];
}
[self _startEditingConnection];
}];
}
-(void)showValidationAlertForError:(NSError*)err{
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = [err localizedDescription];
alert.informativeText = [err localizedRecoverySuggestion];
[alert addButtonWithTitle:NSLocalizedString(@"OK", @"OK button")];
[alert beginSheetModalForWindow:[dbDocument parentWindow] completionHandler:nil];
}
-(BOOL)validateKeyFile:(NSURL *)url error:(NSError **)outError{
NSError *err = nil;
NSData *file = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&err];
if(err) {
*outError = err;
return NO;
}
NSString *stringFromData = [[NSString alloc] initWithData:file encoding:NSASCIIStringEncoding];
// SEE: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/stringsParagraphBreaks.html#//apple_ref/doc/uid/TP40005016-SW3
// need to handle \n, \r, \r\n,
BOOL __block foundValidFirstLine = NO;
BOOL __block foundValidLastLine = NO;
if(stringFromData){
NSRange range = NSMakeRange(0, stringFromData.length);
[stringFromData enumerateSubstringsInRange:range
options:NSStringEnumerationByParagraphs
usingBlock:^(NSString * _Nullable paragraph, NSRange paragraphRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
if ([paragraph containsString:@"PRIVATE KEY-----"] && [paragraph containsString:@"-----BEGIN"]) {
foundValidFirstLine = YES;
}
if ([paragraph containsString:@"PRIVATE KEY-----"] && [paragraph containsString:@"-----END"]) {
foundValidLastLine = YES;
}
}];
}
if(foundValidFirstLine == YES && foundValidLastLine == YES){
return YES;
}
else{
*outError = [NSError errorWithDomain:NSCocoaErrorDomain code:0 userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"“%@” is not a valid private key file.", @"connection view : ssl : key file picker : wrong format error title"),[url lastPathComponent]],
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Make sure the file contains a RSA private key and is using PEM encoding.", @"connection view : ssl : key file picker : wrong format error description"),
NSURLErrorKey: url
}];
return NO;
}
}
-(BOOL)validateCertFile:(NSURL *)url error:(NSError **)outError{
NSError *err = nil;
NSData *file = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&err];
if(err) {
*outError = err;
return NO;
}
NSString *stringFromData = [[NSString alloc] initWithData:file encoding:NSASCIIStringEncoding];
// SEE: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/stringsParagraphBreaks.html#//apple_ref/doc/uid/TP40005016-SW3
// need to handle \n, \r, \r\n,
BOOL __block foundValidFirstLine = NO;
BOOL __block foundValidLastLine = NO;
if(stringFromData){
NSRange range = NSMakeRange(0, stringFromData.length);
[stringFromData enumerateSubstringsInRange:range
options:NSStringEnumerationByParagraphs
usingBlock:^(NSString * _Nullable paragraph, NSRange paragraphRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
if ([paragraph containsString:@"CERTIFICATE-----"] && [paragraph containsString:@"-----BEGIN"]) {
foundValidFirstLine = YES;
}
if ([paragraph containsString:@"CERTIFICATE-----"] && [paragraph containsString:@"-----END"]) {
foundValidLastLine = YES;
}
}];
}
if(foundValidFirstLine == YES && foundValidLastLine == YES){
return YES;
}
else{
*outError = [NSError errorWithDomain:NSCocoaErrorDomain code:0 userInfo:@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"“%@” is not a valid client certificate file.", @"connection view : ssl : client cert file picker : wrong format error title"),[url lastPathComponent]],
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Make sure the file contains a X.509 client certificate and is using PEM encoding.", @"connection view : ssl : client cert picker : wrong format error description"),
NSURLErrorKey: url
}];
return NO;
}
}
// quick check to stop users selecting .pub files
- (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url{
if([url.pathExtension isEqualToString:@"pub"]){
return NO;
}
return YES;
}
- (BOOL)panel:(id)sender validateURL:(NSURL *)url error:(NSError **)outError
{
// see https://developer.apple.com/documentation/foundation/nsurl/1410597-checkresourceisreachableandretur?language=objc
// If your app must perform operations on the file, such as opening it or copying resource properties,
//it is more efficient to attempt the operation and handle any failure that may occur.
//unknown, accept by default
return YES;
/* And now, an intermission from the mysql source code:
if (!cert_file && key_file)
cert_file= key_file;
if (!key_file && cert_file)
key_file= cert_file;
*/
}
/**
* Show connection help webpage.
*/
- (IBAction)showHelp:(id)sender
{
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:SPLOCALIZEDURL_CONNECTIONHELP]];
}
/**
* Resize parts of the interface to reflect SSL status.
*/
- (IBAction)updateSSLInterface:(id)sender
{
[self _startEditingConnection];
[self resizeTabViewToConnectionType:[self type] animating:YES];
}
/**
* Toggle hidden file visiblity in response to accessory view changes
*/
- (IBAction)updateKeyLocationFileVisibility:(id)sender
{
[keySelectionPanel setShowsHiddenFiles:[prefs boolForKey:SPHiddenKeyFileVisibilityKey]];
}
/**
* Update the interface in response to external split view size changes.
*/
- (void)updateSplitViewSize
{
if ([dbDocument getConnection]) {
return;
}
[connectionSplitView setDelegate:nil];
[connectionSplitView setPosition:[[[databaseConnectionView subviews] firstObject] frame].size.width ofDividerAtIndex:0];
[connectionSplitView setDelegate:self];
}
- (IBAction)updateClearTextPlugin:(id)sender
{
[self _startEditingConnection];
}
#pragma mark -
#pragma mark Connection details interaction and display
/**
* Control tab view resizing based on the supplied connection type,
* with an option defining whether it should be animated or not.
*/
- (void)resizeTabViewToConnectionType:(NSUInteger)theType animating:(BOOL)animate
{
NSRect frameRect, targetResizeRect;
// Use a magic number which needs to be added to the form when calculating resizes -
// including the height of the button areas below.
NSInteger additionalFormHeight = 92;
frameRect = [connectionResizeContainer frame];
switch (theType) {
case SPTCPIPConnection:
targetResizeRect = [standardConnectionFormContainer frame];
if ([self useSSL]) additionalFormHeight += [standardConnectionSSLDetailsContainer frame].size.height;
break;
case SPSocketConnection:
targetResizeRect = [socketConnectionFormContainer frame];
if ([self useSSL]) additionalFormHeight += [socketConnectionSSLDetailsContainer frame].size.height;
break;
case SPSSHTunnelConnection:
targetResizeRect = [sshConnectionFormContainer frame];
if ([self useSSL]) additionalFormHeight += [sshConnectionSSLDetailsContainer frame].size.height;
break;
}
frameRect.size.height = targetResizeRect.size.height + additionalFormHeight;
if (animate && initComplete) {
[[connectionResizeContainer animator] setFrame:frameRect];
}
else {
[connectionResizeContainer setFrame:frameRect];
}
}
#pragma mark -
#pragma mark Favorites interaction
/**
* Sorts the favorites table view based on the selected sort by item.
*/
- (void)sortFavorites:(id)sender
{
SPFavoritesSortItem previousSortItem = currentSortItem;
currentSortItem = (SPFavoritesSortItem)[[sender menu] indexOfItem:sender];
[prefs setInteger:currentSortItem forKey:SPFavoritesSortedBy];
// Perform sorting
[self _sortFavorites];
if (previousSortItem > SPFavoritesSortUnsorted) [[[sender menu] itemAtIndex:previousSortItem] setState:NSOffState];
[[[sender menu] itemAtIndex:currentSortItem] setState:NSOnState];
}
/**
* Reverses the favorites table view sorting based on the selected criteria.
*/
- (void)reverseSortFavorites:(NSMenuItem *)sender
{
reverseFavoritesSort = (![sender state]);
[prefs setBool:reverseFavoritesSort forKey:SPFavoritesSortedInReverse];
// Perform re-sorting
[self _sortFavorites];
[sender setState:reverseFavoritesSort];
}
/**
* Sets fields for the chosen favorite.
*/
- (void)updateFavoriteSelection:(id)sender
{
// Clear the keychain referral items as appropriate
[self setConnectionKeychainID:nil];
SPTreeNode *node = [self selectedFavoriteNode];
if ([node isGroup]) node = nil;
// Update key-value properties from the selected favourite, using empty strings where not found
NSDictionary *fav = [[node representedObject] nodeFavorite];
// Keep a copy of the favorite as it currently stands
currentFavorite = [fav copy];
[connectionResizeContainer setHidden:NO];
[self _stopEditingConnection];
// Set up the type, also storing it in the previous type store to prevent type "changes" triggering actions
NSUInteger connectionType = ([fav objectForKey:SPFavoriteTypeKey] ? [[fav objectForKey:SPFavoriteTypeKey] integerValue] : SPTCPIPConnection);
previousType = connectionType;
[self setType:connectionType];
// Standard details
[self setName:([fav objectForKey:SPFavoriteNameKey] ? [fav objectForKey:SPFavoriteNameKey] : @"")];
[self setHost:([fav objectForKey:SPFavoriteHostKey] ? [fav objectForKey:SPFavoriteHostKey] : @"")];
[self setSocket:([fav objectForKey:SPFavoriteSocketKey] ? [fav objectForKey:SPFavoriteSocketKey] : @"")];
[self setUser:([fav objectForKey:SPFavoriteUserKey] ? [fav objectForKey:SPFavoriteUserKey] : @"")];
[self setColorIndex:([fav objectForKey:SPFavoriteColorIndexKey]? [[fav objectForKey:SPFavoriteColorIndexKey] integerValue] : -1)];
[self setPort:([fav objectForKey:SPFavoritePortKey] ? [fav objectForKey:SPFavoritePortKey] : @"")];
[self setDatabase:([fav objectForKey:SPFavoriteDatabaseKey] ? [fav objectForKey:SPFavoriteDatabaseKey] : @"")];
[self setUseCompression:([fav objectForKey:SPFavoriteUseCompressionKey] ? [[fav objectForKey:SPFavoriteUseCompressionKey] boolValue] : YES)];
// Time Zone details
switch ([fav objectForKey:SPFavoriteTimeZoneModeKey] ? [[fav objectForKey:SPFavoriteTimeZoneModeKey] intValue] : SPConnectionTimeZoneModeUseServerTZ) {
case SPConnectionTimeZoneModeUseSystemTZ: {
[standardTimeZoneField selectItemWithTag:SPUseSystemTimeZoneTag];
[socketTimeZoneField selectItemWithTag:SPUseSystemTimeZoneTag];
[sshTimeZoneField selectItemWithTag:SPUseSystemTimeZoneTag];
[self setTimeZoneMode:SPConnectionTimeZoneModeUseSystemTZ];
[self setTimeZoneIdentifier:@""];
break;
}
case SPConnectionTimeZoneModeUseFixedTZ: {
NSString *tzIdentifier = [fav objectForKey:SPFavoriteTimeZoneIdentifierKey];
[standardTimeZoneField selectItemWithTitle:tzIdentifier];
[socketTimeZoneField selectItemWithTitle:tzIdentifier];
[sshTimeZoneField selectItemWithTitle:tzIdentifier];
[self setTimeZoneMode:SPConnectionTimeZoneModeUseFixedTZ];
[self setTimeZoneIdentifier:tzIdentifier];
break;
}
default: {
[standardTimeZoneField selectItemWithTag:SPUseServerTimeZoneTag];
[socketTimeZoneField selectItemWithTag:SPUseServerTimeZoneTag];
[sshTimeZoneField selectItemWithTag:SPUseServerTimeZoneTag];
[self setTimeZoneMode:SPConnectionTimeZoneModeUseServerTZ];
[self setTimeZoneIdentifier:@""];
break;
}
}
//Special prefs
[self setAllowDataLocalInfile:([fav objectForKey:SPFavoriteAllowDataLocalInfileKey] ? [[fav objectForKey:SPFavoriteAllowDataLocalInfileKey] intValue] : NSOffState)];
// Clear text plugin
[self setEnableClearTextPlugin:([fav objectForKey:SPFavoriteEnableClearTextPluginKey] ? [[fav objectForKey:SPFavoriteEnableClearTextPluginKey] intValue] : NSOffState)];
// SSL details
[self setUseSSL:([fav objectForKey:SPFavoriteUseSSLKey] ? [[fav objectForKey:SPFavoriteUseSSLKey] intValue] : NSOffState)];
[self setSslKeyFileLocationEnabled:([fav objectForKey:SPFavoriteSSLKeyFileLocationEnabledKey] ? [[fav objectForKey:SPFavoriteSSLKeyFileLocationEnabledKey] intValue] : NSOffState)];
[self setSslKeyFileLocation:([fav objectForKey:SPFavoriteSSLKeyFileLocationKey] ? [fav objectForKey:SPFavoriteSSLKeyFileLocationKey] : @"")];
[self setSslCertificateFileLocationEnabled:([fav objectForKey:SPFavoriteSSLCertificateFileLocationEnabledKey] ? [[fav objectForKey:SPFavoriteSSLCertificateFileLocationEnabledKey] intValue] : NSOffState)];
[self setSslCertificateFileLocation:([fav objectForKey:SPFavoriteSSLCertificateFileLocationKey] ? [fav objectForKey:SPFavoriteSSLCertificateFileLocationKey] : @"")];
[self setSslCACertFileLocationEnabled:([fav objectForKey:SPFavoriteSSLCACertFileLocationEnabledKey] ? [[fav objectForKey:SPFavoriteSSLCACertFileLocationEnabledKey] intValue] : NSOffState)];
[self setSslCACertFileLocation:([fav objectForKey:SPFavoriteSSLCACertFileLocationKey] ? [fav objectForKey:SPFavoriteSSLCACertFileLocationKey] : @"")];
// SSH details
[self setSshHost:([fav objectForKey:SPFavoriteSSHHostKey] ? [fav objectForKey:SPFavoriteSSHHostKey] : @"")];
[self setSshUser:([fav objectForKey:SPFavoriteSSHUserKey] ? [fav objectForKey:SPFavoriteSSHUserKey] : @"")];
[self setSshKeyLocationEnabled:([fav objectForKey:SPFavoriteSSHKeyLocationEnabledKey] ? [[fav objectForKey:SPFavoriteSSHKeyLocationEnabledKey] intValue] : NSOffState)];
[self setSshKeyLocation:([fav objectForKey:SPFavoriteSSHKeyLocationKey] ? [fav objectForKey:SPFavoriteSSHKeyLocationKey] : @"")];
[self setSshPort:([fav objectForKey:SPFavoriteSSHPortKey] ? [fav objectForKey:SPFavoriteSSHPortKey] : @"")];
// Trigger an interface update
[self resizeTabViewToConnectionType:[self type] animating:(sender == self)];
// Check whether the password exists in the keychain, and if so add it; also record the
// keychain details so we can pass around only those details if the password doesn't change
connectionKeychainItemName = !fav ? nil : [keychain nameForFavoriteName:[fav objectForKey:SPFavoriteNameKey] id:[fav objectForKey:SPFavoriteIDKey]];
connectionKeychainItemAccount = !fav ? nil : [keychain accountForUser:[fav objectForKey:SPFavoriteUserKey] host:(([self type] == SPSocketConnection) ? @"localhost" : [fav objectForKey:SPFavoriteHostKey]) database:[fav objectForKey:SPFavoriteDatabaseKey]];
if(fav) {
[self setPassword:[keychain getPasswordForName:connectionKeychainItemName account:connectionKeychainItemAccount]];
}
if (!fav || ![[self password] length]) {
[self setPassword:nil];
}
// Store the selected favorite ID for use with the document on connection
if ([fav objectForKey:SPFavoriteIDKey]) [self setConnectionKeychainID:[[fav objectForKey:SPFavoriteIDKey] stringValue]];
// And the same for the SSH password
connectionSSHKeychainItemName = !fav ? nil : [keychain nameForSSHForFavoriteName:[fav objectForKey:SPFavoriteNameKey] id:[fav objectForKey:SPFavoriteIDKey]];
connectionSSHKeychainItemAccount = !fav ? nil : [keychain accountForSSHUser:[fav objectForKey:SPFavoriteSSHUserKey] sshHost:[fav objectForKey:SPFavoriteSSHHostKey]];
if(fav) {
[self setSshPassword:[keychain getPasswordForName:connectionSSHKeychainItemName account:connectionSSHKeychainItemAccount]];
}
if (!fav || ![[self sshPassword] length]) {
[self setSshPassword:nil];
}
[prefs setInteger:[[fav objectForKey:SPFavoriteIDKey] integerValue] forKey:SPLastFavoriteID];
[self updateFavoriteNextKeyView];
}
/**
* Set the next KeyView to password field if the password is empty
*/
- (void)updateFavoriteNextKeyView
{
switch ([self type])
{
case SPTCPIPConnection:
[favoritesOutlineView setNextKeyView:(![[standardPasswordField stringValue] length]) ? standardPasswordField : standardNameField];
break;
case SPSocketConnection:
[favoritesOutlineView setNextKeyView:(![[socketPasswordField stringValue] length]) ? socketPasswordField : socketNameField];
break;
case SPSSHTunnelConnection:
if (![[sshPasswordField stringValue] length]) {
[favoritesOutlineView setNextKeyView:sshPasswordField];
}
else if (![[sshSSHPasswordField stringValue] length]) {
[favoritesOutlineView setNextKeyView:sshSSHPasswordField];
}
else {
[favoritesOutlineView setNextKeyView:sshNameField];
}
break;
}
}
/**
* Returns the selected favorite data dictionary or nil if nothing is selected.
*/
- (NSMutableDictionary *)selectedFavorite
{
SPTreeNode *node = [self selectedFavoriteNode];
return (![node isGroup]) ? [(SPFavoriteNode *)[node representedObject] nodeFavorite] : nil;
}
/**
* Returns the selected favorite node or nil if nothing is selected.
*/
- (SPTreeNode *)selectedFavoriteNode
{
NSArray *nodes = [self selectedFavoriteNodes];
return (SPTreeNode *)[nodes safeObjectAtIndex:0];
}
/**
* Returns an array of selected favorite nodes.