aboutsummaryrefslogtreecommitdiffstats
path: root/Source
diff options
context:
space:
mode:
Diffstat (limited to 'Source')
-rw-r--r--Source/CMMCPConnection.h17
-rw-r--r--Source/CMMCPConnection.m251
-rw-r--r--Source/KeyChain.m56
-rw-r--r--Source/SPPreferenceController.h4
-rw-r--r--Source/SPPreferenceController.m115
-rw-r--r--Source/SPSSHTunnel.h54
-rw-r--r--Source/SPSSHTunnel.m359
-rw-r--r--Source/SSHTunnel.h57
-rw-r--r--Source/SSHTunnel.m531
-rw-r--r--Source/TableDocument.h21
-rw-r--r--Source/TableDocument.m438
-rw-r--r--Source/TunnelPassphraseRequester.m96
12 files changed, 1171 insertions, 828 deletions
diff --git a/Source/CMMCPConnection.h b/Source/CMMCPConnection.h
index 8867ed82..566d628a 100644
--- a/Source/CMMCPConnection.h
+++ b/Source/CMMCPConnection.h
@@ -26,6 +26,8 @@
#import <Cocoa/Cocoa.h>
#import <MCPKit_bundled/MCPKit_bundled.h>
#import "CMMCPResult.h"
+#import "KeyChain.h"
+#import "SPSSHTunnel.h"
@interface NSObject (CMMCPConnectionDelegate)
@@ -41,13 +43,17 @@
id delegate;
BOOL nibLoaded;
+ SPSSHTunnel *connectionTunnel;
NSString *connectionLogin;
+ NSString *connectionKeychainName;
+ NSString *connectionKeychainAccount;
NSString *connectionPassword;
NSString *connectionHost;
int connectionPort;
NSString *connectionSocket;
float lastQueryExecutionTime;
int connectionTimeout;
+ int currentSSHTunnelState;
BOOL useKeepAlive;
float keepAliveInterval;
@@ -58,15 +64,18 @@
}
- (id) init;
-- (id) initToHost:(NSString *) host withLogin:(NSString *) login password:(NSString *) pass usingPort:(int) port;
-- (id) initToSocket:(NSString *) socket withLogin:(NSString *) login password:(NSString *) pass;
+- (id) initToHost:(NSString *) host withLogin:(NSString *) login usingPort:(int) port;
+- (id) initToSocket:(NSString *) socket withLogin:(NSString *) login;
- (void) initSPExtensions;
-- (BOOL) connectWithLogin:(NSString *) login password:(NSString *) pass host:(NSString *) host port:(int) port socket:(NSString *) socket;
+- (BOOL) setPassword:(NSString *)thePassword;
+- (BOOL) setPasswordKeychainName:(NSString *)theName account:(NSString *)theAccount;
+- (BOOL) setSSHTunnel:(SPSSHTunnel *)theTunnel;
+- (BOOL) connect;
- (void) disconnect;
- (BOOL) reconnect;
+- (void) setParentWindow:(NSWindow *)theWindow;
- (IBAction) closeSheet:(id)sender;
+ (NSStringEncoding) encodingForMySQLEncoding:(const char *) mysqlEncoding;
-- (void) setParentWindow:(NSWindow *)theWindow;
- (BOOL) selectDB:(NSString *) dbName;
- (CMMCPResult *) queryString:(NSString *) query;
- (CMMCPResult *) queryString:(NSString *) query usingEncoding:(NSStringEncoding) encoding;
diff --git a/Source/CMMCPConnection.m b/Source/CMMCPConnection.m
index ab9bf6e6..b7fc230f 100644
--- a/Source/CMMCPConnection.m
+++ b/Source/CMMCPConnection.m
@@ -52,7 +52,10 @@ static void forcePingTimeout(int signalNumber);
@implementation CMMCPConnection
/*
- * Override the normal init methods, extending them to also init additional details.
+ * Override the normal init methods, extending them to also init additional details,
+ * and to store details of the initialised connection to allow reconnection as method.
+ * Note this also behaves differently from the standard MCPKit connection methods -
+ * passwords are passed separately, and connections are not automatically made on init.
*/
- (id) init
{
@@ -61,16 +64,47 @@ static void forcePingTimeout(int signalNumber);
serverVersionString = nil;
return self;
}
-- (id) initToHost:(NSString *) host withLogin:(NSString *) login password:(NSString *) pass usingPort:(int) port
+- (id) initToHost:(NSString *) host withLogin:(NSString *) login usingPort:(int) port
{
[self initSPExtensions];
- self = [super initToHost:host withLogin:login password:pass usingPort:port];
+
+ self = [super init];
+ mEncoding = NSISOLatin1StringEncoding;
+ mConnection = mysql_init(mConnection);
+ mConnected = NO;
+ if (mConnection == NULL) {
+ [self autorelease];
+ return nil;
+ }
+
+ mConnectionFlags = kMCPConnectionDefaultOption;
+
+ connectionHost = [[NSString alloc] initWithString:host];
+ connectionLogin = [[NSString alloc] initWithString:login];
+ connectionPort = port;
+ connectionSocket = nil;
+
return self;
}
-- (id) initToSocket:(NSString *) socket withLogin:(NSString *) login password:(NSString *) pass
+- (id) initToSocket:(NSString *) socket withLogin:(NSString *) login
{
[self initSPExtensions];
- self = [super initToSocket:socket withLogin:login password:pass];
+ self = [super init];
+ mEncoding = NSISOLatin1StringEncoding;
+ mConnection = mysql_init(mConnection);
+ mConnected = NO;
+ if (mConnection == NULL) {
+ [self autorelease];
+ return nil;
+ }
+
+ mConnectionFlags = kMCPConnectionDefaultOption;
+
+ connectionHost = nil;
+ connectionLogin = [[NSString alloc] initWithString:login];
+ connectionSocket = [[NSString alloc] initWithString:socket];
+ connectionPort = 0;
+
return self;
}
@@ -81,12 +115,11 @@ static void forcePingTimeout(int signalNumber);
- (void) initSPExtensions
{
parentWindow = nil;
- connectionLogin = nil;
connectionPassword = nil;
- connectionHost = nil;
- connectionPort = 0;
- connectionSocket = nil;
+ connectionKeychainName = nil;
+ connectionKeychainAccount = nil;
keepAliveTimer = nil;
+ connectionTunnel = nil;
connectionTimeout = [[[NSUserDefaults standardUserDefaults] objectForKey:@"ConnectionTimeout"] intValue];
if (!connectionTimeout) connectionTimeout = 10;
useKeepAlive = [[[NSUserDefaults standardUserDefaults] objectForKey:@"UseKeepAlive"] doubleValue];
@@ -99,49 +132,131 @@ static void forcePingTimeout(int signalNumber);
}
}
+/*
+ * Sets the password to be stored locally.
+ * Providing a keychain name is much more secure.
+ */
+- (BOOL) setPassword:(NSString *)thePassword
+{
+ if (connectionPassword) [connectionPassword release], connectionPassword = nil;
+ if (connectionKeychainName) [connectionKeychainName release], connectionKeychainName = nil;
+ if (connectionKeychainAccount) [connectionKeychainAccount release], connectionKeychainAccount = nil;
+
+ connectionPassword = [[NSString alloc] initWithString:thePassword];
+
+ return YES;
+}
/*
- * Override the normal connection method, extending it to also store details of the
- * current connection to allow reconnection as necessary. This also sets the connection timeout
- * - used for pings, not for long-running commands.
+ * Sets the keychain name to use to retrieve the password. This is the recommended and
+ * secure way of supplying a password to the SSH tunnel.
*/
-- (BOOL) connectWithLogin:(NSString *) login password:(NSString *) pass host:(NSString *) host port:(int) port socket:(NSString *) socket
-{
- if (connectionLogin) [connectionLogin release];
- if (login) connectionLogin = [[NSString alloc] initWithString:login];
- if (connectionPassword) [connectionPassword release];
- if (pass) connectionPassword = [[NSString alloc] initWithString:pass];
- if (connectionHost) [connectionHost release];
- if (host) connectionHost = [[NSString alloc] initWithString:host];
- connectionPort = port;
- if (connectionSocket) [connectionSocket release];
- if (socket) connectionSocket = [[NSString alloc] initWithString:socket];
+- (BOOL) setPasswordKeychainName:(NSString *)theName account:(NSString *)theAccount
+{
+ if (connectionPassword) [connectionPassword release], connectionPassword = nil;
+ if (connectionKeychainName) [connectionKeychainName release], connectionKeychainName = nil;
+ if (connectionKeychainAccount) [connectionKeychainAccount release], connectionKeychainAccount = nil;
+
+ connectionKeychainName = [[NSString alloc] initWithString:theName];
+ connectionKeychainAccount = [[NSString alloc] initWithString:theAccount];
+
+ return YES;
+}
+
+
+/*
+ * Set a SSH tunnel object to connect through. This object will be retained locally,
+ * and will be automatically connected/connection checked/reconnected/disconnected
+ * together with the main connection.
+ */
+- (BOOL) setSSHTunnel:(SPSSHTunnel *)theTunnel
+{
+ connectionTunnel = theTunnel;
+ [connectionTunnel retain];
+
+ currentSSHTunnelState = [connectionTunnel state];
+ [connectionTunnel setConnectionStateChangeSelector:@selector(sshTunnelStateChange:) delegate:self];
+
+ return YES;
+}
+
+/*
+ * Add a new connection method, intended for use with the init methods above.
+ * Uses the stored details to instantiate a connection to the specified server,
+ * including custom timeouts - used for pings, not for long-running commands.
+ */
+- (BOOL) connect
+{
+ const char *theLogin = [self cStringFromString:connectionLogin];
+ const char *theHost;
+ const char *thePass;
+ const char *theSocket;
+ void *theRet;
+
+ // Ensure that a password method has been provided
+ if (connectionKeychainName == nil && connectionPassword == nil) return NO;
+
+ // Start the keepalive timer
+ [self startKeepAliveTimerResettingState:YES];
+
+ // Disconnect if a connection is already active
+ if (mConnected) {
+ [self disconnect];
+ mConnection = mysql_init(NULL);
+ if (mConnection == NULL) return NO;
+ }
+ // Ensure the custom timeout option is set
if (mConnection != NULL) {
mysql_options(mConnection, MYSQL_OPT_CONNECT_TIMEOUT, (const void *)&connectionTimeout);
}
+
+ // Set the host as appropriate
+ if (!connectionHost || ![connectionHost length]) {
+ theHost = NULL;
+ } else {
+ theHost = [self cStringFromString:connectionHost];
+ }
+
+ // Use the default socket if none is set, or set appropriately
+ if (connectionSocket == nil || ![connectionSocket length]) {
+ theSocket = kMCPConnectionDefaultSocket;
+ } else {
+ theSocket = [self cStringFromString:connectionSocket];
+ }
+
+ // Select the password from the provided method
+ if (connectionKeychainName) {
+ KeyChain *keychain;
+ keychain = [[KeyChain alloc] init];
+ thePass = [self cStringFromString:[keychain getPasswordForName:connectionKeychainName account:connectionKeychainAccount]];
+ [keychain release];
+ } else {
+ thePass = [self cStringFromString:connectionPassword];
+ }
- [self startKeepAliveTimerResettingState:YES];
- return [super connectWithLogin:login password:pass host:host port:port socket:socket];
+ // Connect
+ theRet = mysql_real_connect(mConnection, theHost, theLogin, thePass, NULL, connectionPort, theSocket, mConnectionFlags);
+ thePass = NULL;
+ if (theRet != mConnection) {
+ return mConnected = NO;
+ }
+
+ mConnected = YES;
+ mEncoding = [MCPConnection encodingForMySQLEncoding:mysql_character_set_name(mConnection)];
+ [self timeZone]; // Getting the timezone used by the server.
+ return mConnected;
}
/*
- * Override the stored disconnection method to ensure that disconnecting clears stored details.
+ * Override the stored disconnection method to ensure that disconnecting clears stored timers.
*/
- (void) disconnect
{
[super disconnect];
-
- if (connectionLogin) [connectionLogin release];
- connectionLogin = nil;
- if (connectionPassword) [connectionPassword release];
- connectionPassword = nil;
- if (connectionHost) [connectionHost release];
- connectionHost = nil;
- connectionPort = 0;
- if (connectionSocket) [connectionSocket release];
- connectionSocket = nil;
+
+ if (connectionTunnel) [connectionTunnel disconnect];
if( serverVersionString != nil ) {
serverVersionString = nil;
@@ -233,20 +348,45 @@ static void forcePingTimeout(int signalNumber);
mConnection = NULL;
}
mConnected = NO;
-
- // Attempt to reinitialise the connection - if this fails, it will still be set to NULL.
- if (mConnection == NULL) {
- mConnection = mysql_init(NULL);
+
+ // If there is a tunnel, ensure it's disconnected and attempt to reconnect it in blocking fashion
+ if (connectionTunnel) {
+ [connectionTunnel setConnectionStateChangeSelector:nil delegate:nil];
+ if ([connectionTunnel state] != SPSSH_STATE_IDLE) [connectionTunnel disconnect];
+ [connectionTunnel connect];
+ NSDate *tunnelStartDate = [NSDate date];
+
+ // Allow the tunnel to attempt to connect in a loop
+ while (1) {
+ if ([connectionTunnel state] == SPSSH_STATE_CONNECTED) {
+ connectionPort = [connectionTunnel localPort];
+ break;
+ }
+ if ([[NSDate date] timeIntervalSinceDate:tunnelStartDate] > (connectionTimeout + 1)) {
+ [connectionTunnel disconnect];
+ break;
+ }
+ [NSThread sleepForTimeInterval:0.25];
+ }
+ currentSSHTunnelState = [connectionTunnel state];
+ [connectionTunnel setConnectionStateChangeSelector:@selector(sshTunnelStateChange:) delegate:self];
}
- if (mConnection != NULL) {
+ if (!connectionTunnel || [connectionTunnel state] == SPSSH_STATE_CONNECTED) {
- // Set a connection timeout for the new connection
- mysql_options(mConnection, MYSQL_OPT_CONNECT_TIMEOUT, (const void *)&connectionTimeout);
+ // Attempt to reinitialise the connection - if this fails, it will still be set to NULL.
+ if (mConnection == NULL) {
+ mConnection = mysql_init(NULL);
+ }
+
+ if (mConnection != NULL) {
- // Attempt to reestablish the connection - using own method so everything gets set up as standard.
- // Will store the supplied details again, which isn't a problem.
- [self connectWithLogin:connectionLogin password:connectionPassword host:connectionHost port:connectionPort socket:connectionSocket];
+ // Set a connection timeout for the new connection
+ mysql_options(mConnection, MYSQL_OPT_CONNECT_TIMEOUT, (const void *)&connectionTimeout);
+
+ // Attempt to reestablish the connection
+ [self connect];
+ }
}
// If the connection was successfully established, reselect the old database and encoding if appropriate.
@@ -289,10 +429,27 @@ static void forcePingTimeout(int signalNumber);
/*
* Set the parent window of the connection for use with dialogs.
*/
-- (void)setParentWindow:(NSWindow *)theWindow {
+- (void)setParentWindow:(NSWindow *)theWindow
+{
parentWindow = theWindow;
}
+/*
+ * Handle any state changes in the associated SSH Tunnel
+ */
+- (void)sshTunnelStateChange:(SPSSHTunnel *)theTunnel
+{
+ int newState = [theTunnel state];
+
+ // Restart the tunnel if it dies
+ if (mConnected && newState == SPSSH_STATE_IDLE && currentSSHTunnelState == SPSSH_STATE_CONNECTED) {
+ currentSSHTunnelState = newState;
+ [self reconnect];
+ }
+
+ currentSSHTunnelState = newState;
+}
+
/*
* Ends and existing modal session
diff --git a/Source/KeyChain.m b/Source/KeyChain.m
index ef3afba3..032db61e 100644
--- a/Source/KeyChain.m
+++ b/Source/KeyChain.m
@@ -35,20 +35,54 @@
- (void)addPassword:(NSString *)password forName:(NSString *)name account:(NSString *)account
{
OSStatus status;
+ SecTrustedApplicationRef sequelProRef, sequelProHelperRef;
+ SecAccessRef passwordAccessRef;
+ SecKeychainAttribute attributes[4];
+ SecKeychainAttributeList attList;
// Check if password already exists before adding
if (![self passwordExistsForName:name account:account]) {
- status = SecKeychainAddGenericPassword(
- NULL, // default keychain
- strlen([name UTF8String]), // length of service name
- [name UTF8String], // service name
- strlen([account UTF8String]), // length of account name
- [account UTF8String], // account name
- strlen([password UTF8String]), // length of password
- [password UTF8String], // pointer to password data
- NULL // the item reference
- );
+
+ // Create a trusted access list with two items - ourselves and the SSH pass app.
+ NSString *helperPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TunnelPassphraseRequester"];
+ if ((SecTrustedApplicationCreateFromPath(NULL, &sequelProRef) == noErr) &&
+ (SecTrustedApplicationCreateFromPath([helperPath UTF8String], &sequelProHelperRef) == noErr)) {
+
+ NSArray *trustedApps = [NSArray arrayWithObjects:(id)sequelProRef, (id)sequelProHelperRef, nil];
+ status = SecAccessCreate((CFStringRef)name, (CFArrayRef)trustedApps, &passwordAccessRef);
+ if (status != noErr) {
+ NSLog(@"Error (%i) while trying to create access list for name: %@ account: %@", status, name, account);
+ passwordAccessRef = NULL;
+ }
+ }
+ // Set up the item attributes
+ attributes[0].tag = kSecGenericItemAttr;
+ attributes[0].data = "application password";
+ attributes[0].length = 20;
+ attributes[1].tag = kSecLabelItemAttr;
+ attributes[1].data = (unichar *)[name UTF8String];
+ attributes[1].length = strlen([name UTF8String]);
+ attributes[2].tag = kSecAccountItemAttr;
+ attributes[2].data = (unichar *)[account UTF8String];
+ attributes[2].length = strlen([account UTF8String]);
+ attributes[3].tag = kSecServiceItemAttr;
+ attributes[3].data = (unichar *)[name UTF8String];
+ attributes[3].length = strlen([name UTF8String]);
+ attList.count = 4;
+ attList.attr = attributes;
+
+ // Create the keychain item
+ status = SecKeychainItemCreateFromContent(
+ kSecGenericPasswordItemClass, // Generic password type
+ &attList, // The attribute list created for the keychain item
+ strlen([password UTF8String]), // Length of password
+ [password UTF8String], // Password data
+ NULL, // Default keychain
+ passwordAccessRef, // Access list for this keychain
+ NULL); // The item reference
+
+ if (passwordAccessRef) CFRelease(passwordAccessRef);
if (status != noErr) {
NSLog(@"Error (%i) while trying to add password for name: %@ account: %@", status, name, account);
}
@@ -120,7 +154,7 @@
}
}
- CFRelease(itemRef);
+ if (itemRef) CFRelease(itemRef);
}
}
diff --git a/Source/SPPreferenceController.h b/Source/SPPreferenceController.h
index 7fb849a0..bc0ff1b2 100644
--- a/Source/SPPreferenceController.h
+++ b/Source/SPPreferenceController.h
@@ -49,6 +49,10 @@
IBOutlet NSTextField *userField;
IBOutlet NSTextField *databaseField;
IBOutlet NSSecureTextField *passwordField;
+ IBOutlet NSTextField *sshHostField;
+ IBOutlet NSTextField *sshUserField;
+ IBOutlet NSSecureTextField *sshPasswordField;
+ IBOutlet NSTextField *sshPortField;
KeyChain *keychain;
IBOutlet NSTextField *editorFontName;
diff --git a/Source/SPPreferenceController.m b/Source/SPPreferenceController.m
index 829f887c..ce05117e 100644
--- a/Source/SPPreferenceController.m
+++ b/Source/SPPreferenceController.m
@@ -257,13 +257,15 @@
NSString *user = [favoritesController valueForKeyPath:@"selection.user"];
NSString *host = [favoritesController valueForKeyPath:@"selection.host"];
NSString *database = [favoritesController valueForKeyPath:@"selection.database"];
+ NSString *sshUser = [favoritesController valueForKeyPath:@"selection.sshUser"];
+ NSString *sshHost = [favoritesController valueForKeyPath:@"selection.sshHost"];
int favoriteid = [[favoritesController valueForKeyPath:@"selection.id"] intValue];
// Remove passwords from the Keychain
[keychain deletePasswordForName:[NSString stringWithFormat:@"Sequel Pro : %@ (%i)", name, favoriteid]
account:[NSString stringWithFormat:@"%@@%@/%@", user, host, database]];
[keychain deletePasswordForName:[NSString stringWithFormat:@"Sequel Pro SSHTunnel : %@ (%i)", name, favoriteid]
- account:[NSString stringWithFormat:@"%@@%@/%@", user, host, database]];
+ account:[NSString stringWithFormat:@"%@@%@", sshUser, sshHost]];
// Reset last used favorite
if ([favoritesTableView selectedRow] == [prefs integerForKey:@"LastFavoriteIndex"]) {
@@ -288,15 +290,18 @@
- (IBAction)duplicateFavorite:(id)sender
{
if ([favoritesTableView numberOfSelectedRows] == 1) {
- NSString *keychainName, *keychainAccount, *password;
+ NSString *keychainName, *keychainAccount, *password, *keychainSSHName, *keychainSSHAccount, *sshPassword;
NSMutableDictionary *favorite = [NSMutableDictionary dictionaryWithDictionary:[[favoritesController arrangedObjects] objectAtIndex:[favoritesTableView selectedRow]]];
NSNumber *favoriteid = [NSNumber numberWithInt:[[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]] hash]];
- // Select the keychain password for duplication
+ // Select the keychain passwords for duplication
keychainName = [NSString stringWithFormat:@"Sequel Pro : %@ (%i)", [favorite objectForKey:@"name"], [[favorite objectForKey:@"id"] intValue]];
keychainAccount = [NSString stringWithFormat:@"%@@%@/%@",
[favorite objectForKey:@"user"], [favorite objectForKey:@"host"], [favorite objectForKey:@"database"]];
password = [keychain getPasswordForName:keychainName account:keychainAccount];
+ keychainSSHName = [NSString stringWithFormat:@"Sequel Pro SSHTunnel : %@ (%i)", [favorite objectForKey:@"name"], [[favorite objectForKey:@"id"] intValue]];
+ keychainSSHAccount = [NSString stringWithFormat:@"%@@%@", [favorite objectForKey:@"sshUser"], [favorite objectForKey:@"sshHost"]];
+ sshPassword = [keychain getPasswordForName:keychainSSHName account:keychainSSHAccount];
// Update the unique ID
[favorite setObject:favoriteid forKey:@"id"];
@@ -304,12 +309,16 @@
// Alter the name for clarity
[favorite setObject:[NSString stringWithFormat:@"%@ Copy", [favorite objectForKey:@"name"]] forKey:@"name"];
- // Create a new keychain item if appropriate
+ // Create new keychain items if appropriate
if (password && [password length]) {
keychainName = [NSString stringWithFormat:@"Sequel Pro : %@ (%i)", [favorite objectForKey:@"name"], [[favorite objectForKey:@"id"] intValue]];
[keychain addPassword:password forName:keychainName account:keychainAccount];
}
- password = nil;
+ if (sshPassword && [sshPassword length]) {
+ keychainSSHName = [NSString stringWithFormat:@"Sequel Pro SSHTunnel : %@ (%i)", [favorite objectForKey:@"name"], [[favorite objectForKey:@"id"] intValue]];
+ [keychain addPassword:sshPassword forName:keychainSSHName account:keychainSSHAccount];
+ }
+ password = nil, sshPassword = nil;
[favoritesController addObject:favorite];
@@ -547,6 +556,7 @@
// If no selection is present, blank the field.
if ([[favoritesTableView selectedRowIndexes] count] == 0) {
[passwordField setStringValue:@""];
+ [sshPasswordField setStringValue:@""];
return;
}
@@ -558,6 +568,14 @@
[favoritesController valueForKeyPath:@"selection.database"]];
[passwordField setStringValue:[keychain getPasswordForName:keychainName account:keychainAccount]];
+
+ // Retrieve the SSH keychain password if appropriate.
+ NSString *keychainSSHName = [NSString stringWithFormat:@"Sequel Pro SSHTunnel : %@ (%i)", [favoritesController valueForKeyPath:@"selection.name"], [[favoritesController valueForKeyPath:@"selection.id"] intValue]];
+ NSString *keychainSSHAccount = [NSString stringWithFormat:@"%@@%@",
+ [favoritesController valueForKeyPath:@"selection.sshUser"],
+ [favoritesController valueForKeyPath:@"selection.sshHost"]];
+
+ [sshPasswordField setStringValue:[keychain getPasswordForName:keychainSSHName account:keychainSSHAccount]];
}
#pragma mark -
@@ -651,46 +669,67 @@
{
NSString *oldKeychainName, *newKeychainName;
NSString *oldKeychainAccount, *newKeychainAccount;
- NSString *oldPassword;
- // Only proceed for name, host, user or database changes
- if (control != nameField && control != hostField && control != userField && control != passwordField && control != databaseField)
+ // Only proceed for name, host, user or database changes, for both standard and SSH
+ if (control != nameField && control != hostField && control != userField && control != passwordField && control != databaseField
+ && control != sshHostField && control != sshUserField && control != sshPasswordField)
return YES;
- // Set the current keychain name and account strings
- oldKeychainName = [NSString stringWithFormat:@"Sequel Pro : %@ (%i)", [favoritesController valueForKeyPath:@"selection.name"], [[favoritesController valueForKeyPath:@"selection.id"] intValue]];
- oldKeychainAccount = [NSString stringWithFormat:@"%@@%@/%@",
- [favoritesController valueForKeyPath:@"selection.user"],
- [favoritesController valueForKeyPath:@"selection.host"],
- [favoritesController valueForKeyPath:@"selection.database"]];
-
- // Retrieve the old password
- oldPassword = [keychain getPasswordForName:oldKeychainName account:oldKeychainAccount];
-
- // If no details have changed, skip processing
- if ([nameField stringValue] == [favoritesController valueForKeyPath:@"selection.name"]
- && [hostField stringValue] == [favoritesController valueForKeyPath:@"selection.host"]
- && [userField stringValue] == [favoritesController valueForKeyPath:@"selection.user"]
- && [databaseField stringValue] == [favoritesController valueForKeyPath:@"selection.database"]
- && [passwordField stringValue] == oldPassword) {
- oldPassword = nil;
- return YES;
+ // If account/password details have changed, update the keychain to match
+ if ([nameField stringValue] != [favoritesController valueForKeyPath:@"selection.name"]
+ || [hostField stringValue] != [favoritesController valueForKeyPath:@"selection.host"]
+ || [userField stringValue] != [favoritesController valueForKeyPath:@"selection.user"]
+ || [databaseField stringValue] != [favoritesController valueForKeyPath:@"selection.database"]
+ || control == passwordField) {
+
+ // Get the current keychain name and account strings
+ oldKeychainName = [NSString stringWithFormat:@"Sequel Pro : %@ (%i)", [favoritesController valueForKeyPath:@"selection.name"], [[favoritesController valueForKeyPath:@"selection.id"] intValue]];
+ oldKeychainAccount = [NSString stringWithFormat:@"%@@%@/%@",
+ [favoritesController valueForKeyPath:@"selection.user"],
+ [favoritesController valueForKeyPath:@"selection.host"],
+ [favoritesController valueForKeyPath:@"selection.database"]];
+
+ // Set up the new keychain name and account strings
+ newKeychainName = [NSString stringWithFormat:@"Sequel Pro : %@ (%i)", [nameField stringValue], [[favoritesController valueForKeyPath:@"selection.id"] intValue]];
+ newKeychainAccount = [NSString stringWithFormat:@"%@@%@/%@",
+ [userField stringValue],
+ [hostField stringValue],
+ [databaseField stringValue]];
+
+ // Delete the old keychain item
+ [keychain deletePasswordForName:oldKeychainName account:oldKeychainAccount];
+
+ // Add the new keychain item if the password field has a value
+ if ([[passwordField stringValue] length])
+ [keychain addPassword:[passwordField stringValue] forName:newKeychainName account:newKeychainAccount];
}
- oldPassword = nil;
- // Set up the new keychain name and account strings
- newKeychainName = [NSString stringWithFormat:@"Sequel Pro : %@ (%i)", [nameField stringValue], [[favoritesController valueForKeyPath:@"selection.id"] intValue]];
- newKeychainAccount = [NSString stringWithFormat:@"%@@%@/%@",
- [userField stringValue],
- [hostField stringValue],
- [databaseField stringValue]];
- // Delete the old keychain item
- [keychain deletePasswordForName:oldKeychainName account:oldKeychainAccount];
+ // If SSH account/password details have changed, update the keychain to match
+ if ([nameField stringValue] != [favoritesController valueForKeyPath:@"selection.name"]
+ || [sshHostField stringValue] != [favoritesController valueForKeyPath:@"selection.sshHost"]
+ || [sshUserField stringValue] != [favoritesController valueForKeyPath:@"selection.sshUser"]
+ || control == sshPasswordField) {
+
+ // Get the current keychain name and account strings
+ oldKeychainName = [NSString stringWithFormat:@"Sequel Pro SSHTunnel : %@ (%i)", [favoritesController valueForKeyPath:@"selection.name"], [[favoritesController valueForKeyPath:@"selection.id"] intValue]];
+ oldKeychainAccount = [NSString stringWithFormat:@"%@@%@",
+ [favoritesController valueForKeyPath:@"selection.sshUser"],
+ [favoritesController valueForKeyPath:@"selection.sshHost"]];
+
+ // Set up the new keychain name and account strings
+ newKeychainName = [NSString stringWithFormat:@"Sequel Pro SSHTunnel : %@ (%i)", [nameField stringValue], [[favoritesController valueForKeyPath:@"selection.id"] intValue]];
+ newKeychainAccount = [NSString stringWithFormat:@"%@@%@",
+ [sshUserField stringValue],
+ [sshHostField stringValue]];
- // Add the new keychain item if the password field has a value
- if ([[passwordField stringValue] length])
- [keychain addPassword:[passwordField stringValue] forName:newKeychainName account:newKeychainAccount];
+ // Delete the old keychain item
+ [keychain deletePasswordForName:oldKeychainName account:oldKeychainAccount];
+
+ // Add the new keychain item if the password field has a value
+ if ([[sshPasswordField stringValue] length])
+ [keychain addPassword:[sshPasswordField stringValue] forName:newKeychainName account:newKeychainAccount];
+ }
// Proceed with editing
return YES;
diff --git a/Source/SPSSHTunnel.h b/Source/SPSSHTunnel.h
new file mode 100644
index 00000000..91bd08de
--- /dev/null
+++ b/Source/SPSSHTunnel.h
@@ -0,0 +1,54 @@
+#import <Cocoa/Cocoa.h>
+
+enum spsshtunnel_states
+{
+ SPSSH_STATE_IDLE = 0,
+ SPSSH_STATE_CONNECTING = 1,
+ SPSSH_STATE_WAITING_FOR_AUTH = 2,
+ SPSSH_STATE_CONNECTED = 3
+};
+
+enum spsshtunnel_password_modes
+{
+ SPSSH_PASSWORD_USES_KEYCHAIN = 0,
+ SPSSH_PASSWORD_ASKS_UI = 1
+};
+
+
+@interface SPSSHTunnel : NSObject
+{
+ NSTask *task;
+ NSPipe *standardError;
+ id delegate;
+ SEL stateChangeSelector;
+ NSConnection *passwordConnection;
+ NSString *lastError;
+ NSString *passwordConnectionName;
+ NSString *passwordConnectionVerifyHash;
+ NSString *sshHost;
+ NSString *sshLogin;
+ NSString *remoteHost;
+ NSString *password;
+ NSString *keychainName;
+ NSString *keychainAccount;
+ BOOL passwordInKeychain;
+ int sshPort;
+ int remotePort;
+ int localPort;
+ int connectionState;
+}
+
+- (id) initToHost:(NSString *) theHost port:(int) thePort login:(NSString *) theLogin tunnellingToPort:(int) targetPort onHost:(NSString *) targetHost;
+- (BOOL) setConnectionStateChangeSelector:(SEL)theStateChangeSelector delegate:(id)theDelegate;
+- (BOOL) setPassword:(NSString *)thePassword;
+- (BOOL) setPasswordKeychainName:(NSString *)theName account:(NSString *)theAccount;
+- (int) state;
+- (NSString *) lastError;
+- (int) localPort;
+- (void) connect;
+- (void) launchTask:(id) dummy;
+- (void)disconnect;
+- (void) standardErrorHandler:(NSNotification*)aNotification;
+- (NSString *) getPasswordWithVerificationHash:(NSString *)theHash;
+
+@end
diff --git a/Source/SPSSHTunnel.m b/Source/SPSSHTunnel.m
new file mode 100644
index 00000000..619657c3
--- /dev/null
+++ b/Source/SPSSHTunnel.m
@@ -0,0 +1,359 @@
+//
+// SPSSHTunnel.m
+// sequel-pro
+//
+// Created by Rowan Beentje on April 26, 2009. Inspired by code by
+// Yann Bizuel for SSH Tunnel Manager 2.
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// More info at <http://code.google.com/p/sequel-pro/>
+
+#import "SPSSHTunnel.h"
+#import <netinet/in.h>
+
+
+@implementation SPSSHTunnel
+
+/*
+ * Initialise with the supplied connection details. Host, login and port should all be provided.
+ * The password can either be set later via setPassword:, which stores the password locally and is
+ * therefore not recommended, or via setPasswordKeychainName:, which will use the keychain on-demand
+ * and is therefore preferred.
+ */
+- (id) initToHost:(NSString *) theHost port:(int) thePort login:(NSString *) theLogin tunnellingToPort:(int) targetPort onHost:(NSString *) targetHost
+{
+ if (!theHost || !thePort || !theLogin || !targetPort || !targetHost) return nil;
+
+ self = [super init];
+
+ // Store the connection settings as appropriate
+ sshHost = [[NSString alloc] initWithString:theHost];
+ sshLogin = [[NSString alloc] initWithString:theLogin];
+ sshPort = thePort;
+ if ([theHost isEqualToString:targetHost]) {
+ remoteHost = [[NSString alloc] initWithString:@"127.0.0.1"];
+ } else {
+ remoteHost = [[NSString alloc] initWithString:targetHost];
+ }
+ remotePort = targetPort;
+ delegate = nil;
+ stateChangeSelector = nil;
+ lastError = nil;
+
+ passwordConnection = nil;
+ password = nil;
+ keychainName = nil;
+ keychainAccount = nil;
+ passwordInKeychain = NO;
+ task = nil;
+ localPort = 0;
+ connectionState = SPSSH_STATE_IDLE;
+
+ return self;
+}
+
+/*
+ * Sets the connection callback selector; a function to be called whenever the tunnel state changes.
+ * The callback function will be called and passed this SSH Tunnel object..
+ */
+- (BOOL) setConnectionStateChangeSelector:(SEL)theStateChangeSelector delegate:(id)theDelegate
+{
+ delegate = theDelegate;
+ stateChangeSelector = theStateChangeSelector;
+
+ return true;
+}
+
+/*
+ * Sets the password to be stored (and returned to the tunnel authenticator) locally.
+ * Providing a keychain name is much more secure.
+ */
+- (BOOL) setPassword:(NSString *)thePassword
+{
+ if (passwordInKeychain) return NO;
+ password = [[NSString alloc] initWithString:thePassword];
+ passwordConnection = [[NSConnection defaultConnection] retain];
+ [passwordConnection runInNewThread];
+ [passwordConnection removeRunLoop:[NSRunLoop currentRunLoop]];
+ [passwordConnection setRootObject:self];
+ passwordConnectionName = [NSString stringWithFormat:@"SequelPro-%f", [[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]] hash]];
+ passwordConnectionVerifyHash = [NSString stringWithFormat:@"%f", [[NSString stringWithFormat:@"%f%i", [[NSDate date] timeIntervalSince1970]] hash]];
+ if ([passwordConnection registerName:passwordConnectionName] == NO) {
+ [password release], password = nil;
+ return NO;
+ }
+
+ return YES;
+}
+
+/*
+ * Sets the keychain name to use to retrieve the password. This is the recommended and
+ * secure way of supplying a password to the SSH tunnel.
+ */
+- (BOOL) setPasswordKeychainName:(NSString *)theName account:(NSString *)theAccount
+{
+ if (passwordConnection) [passwordConnection release], passwordConnection = nil;
+ if (password) [password release], password = nil;
+
+ passwordInKeychain = YES;
+ keychainName = [[NSString alloc] initWithString:theName];
+ keychainAccount = [[NSString alloc] initWithString:theAccount];
+
+ return YES;
+}
+
+/*
+ * Get the state of the connection.
+ */
+- (int) state
+{
+ return connectionState;
+}
+
+/*
+ * Returns the last error string, if any.
+ */
+- (NSString *) lastError
+{
+ return [NSString stringWithString:lastError];
+}
+
+/*
+ * Initiate the SSH tunnel connection, launching the task in a background thread.
+ */
+- (void) connect
+{
+ localPort = 0;
+ if (connectionState != SPSSH_STATE_IDLE || (!passwordInKeychain && !password)) return;
+ [NSThread detachNewThreadSelector:@selector(launchTask:) toTarget: self withObject: nil ];
+}
+
+/*
+ * Launch the NSTask which wraps the SSH process, and use it to initiate the
+ * tunnel to the remote server.
+ * Sets up and tears down as appropriate for usage in a background thread.
+ */
+- (void) launchTask:(id) dummy
+{
+ if (connectionState != SPSSH_STATE_IDLE || task) return;
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ NSMutableArray *taskArguments;
+ NSMutableDictionary *taskEnvironment;
+ NSString *authenticationAppPath;
+
+ connectionState = SPSSH_STATE_CONNECTING;
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+
+ int connectionTimeout = [[[NSUserDefaults standardUserDefaults] objectForKey:@"ConnectionTimeout"] intValue];
+ if (!connectionTimeout) connectionTimeout = 10;
+ BOOL useKeepAlive = [[[NSUserDefaults standardUserDefaults] objectForKey:@"UseKeepAlive"] doubleValue];
+ double keepAliveInterval = [[[NSUserDefaults standardUserDefaults] objectForKey:@"KeepAliveInterval"] doubleValue];
+ if (!keepAliveInterval) keepAliveInterval = 0;
+
+ // If no local port has yet been chosen, choose one
+ if (!localPort) {
+ int tempSocket;
+ struct sockaddr_in tempSocketAddress;
+ int addressLength = sizeof(tempSocketAddress);
+ if((tempSocket = socket(AF_INET, SOCK_STREAM, 0)) > 0) {
+ memset(&tempSocketAddress, 0, sizeof(tempSocketAddress));
+ tempSocketAddress.sin_family = AF_INET;
+ tempSocketAddress.sin_addr.s_addr = htonl(INADDR_ANY);
+ tempSocketAddress.sin_port = 0;
+ if (bind(tempSocket, (struct sockaddr *)&tempSocketAddress, addressLength) >= 0) {
+ if (getsockname(tempSocket, (struct sockaddr *)&tempSocketAddress, (uint32_t *)&addressLength) >= 0) {
+ localPort = ntohs(tempSocketAddress.sin_port);
+ }
+ }
+ close(tempSocket);
+ }
+
+ // Abort if no local free port could be allocated
+ if (!localPort) {
+ connectionState = SPSSH_STATE_IDLE;
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+ if (lastError) [lastError release];
+ lastError = [[NSString alloc] initWithString:NSLocalizedString(@"No local port could be allocated for the SSH Tunnel.", @"SSH tunnel could not be created because no local port could be allocated")];
+ [pool release];
+ return;
+ }
+ }
+
+ // Set up the NSTask
+ task = [[NSTask alloc] init];
+ [task setLaunchPath: @"/usr/bin/ssh"];
+
+ // Set up the arguments for the task
+ taskArguments = [ NSMutableArray array ];
+ [taskArguments addObject:@"-N"]; // Tunnel only
+ [taskArguments addObject:@"-v"]; // Verbose mode for messages
+// [taskArguments addObject:@"-C"]; // TODO: compression?
+ [taskArguments addObject:@"-o ExitOnForwardFailure=yes"];
+ [taskArguments addObject:[NSString stringWithFormat:@"-o ConnectTimeout=%i", connectionTimeout]];
+ if (useKeepAlive && keepAliveInterval) {
+ [taskArguments addObject:@"-o TCPKeepAlive=no"];
+ [taskArguments addObject:[NSString stringWithFormat:@"-o ServerAliveInterval=%i", ceil(keepAliveInterval)]];
+ [taskArguments addObject:@"-o ServerAliveCountMax=1"];
+ }
+ [taskArguments addObject:[NSString stringWithFormat:@"-p %i", sshPort]];
+ [taskArguments addObject:[NSString stringWithFormat:@"%@@%@", sshLogin, sshHost]];
+ [taskArguments addObject:[NSString stringWithFormat:@"-L %i/%@/%i", localPort, remoteHost, remotePort]];
+ [task setArguments:taskArguments];
+
+ // Set up the environment for the task
+ authenticationAppPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TunnelPassphraseRequester"];
+ taskEnvironment = [NSMutableDictionary dictionaryWithDictionary:[[NSProcessInfo processInfo] environment]];
+ [taskEnvironment removeObjectForKey: @"SSH_AGENT_PID"];
+ [taskEnvironment removeObjectForKey: @"SSH_AUTH_SOCK"];
+ [taskEnvironment setObject:authenticationAppPath forKey:@"SSH_ASKPASS"];
+ [taskEnvironment setObject:@":0" forKey:@"DISPLAY"];
+ if (passwordInKeychain) {
+ [taskEnvironment setObject:[[NSNumber numberWithInt:SPSSH_PASSWORD_USES_KEYCHAIN] stringValue] forKey:@"SP_PASSWORD_METHOD"];
+ [taskEnvironment setObject:keychainName forKey:@"SP_KEYCHAIN_ITEM_NAME"];
+ [taskEnvironment setObject:keychainAccount forKey:@"SP_KEYCHAIN_ITEM_ACCOUNT"];
+ } else {
+ [taskEnvironment setObject:[[NSNumber numberWithInt:SPSSH_PASSWORD_ASKS_UI] stringValue] forKey:@"SP_PASSWORD_METHOD"];
+ [taskEnvironment setObject:passwordConnectionName forKey:@"SP_CONNECTION_NAME"];
+ [taskEnvironment setObject:passwordConnectionVerifyHash forKey:@"SP_CONNECTION_VERIFY_HASH"];
+ }
+ [task setEnvironment:taskEnvironment];
+
+ // Set up the standard error pipe
+ standardError = [[NSPipe alloc] init];
+ [task setStandardError:standardError];
+ [[ NSNotificationCenter defaultCenter] addObserver:self
+ selector:@selector(standardErrorHandler:)
+ name:@"NSFileHandleDataAvailableNotification"
+ object:[standardError fileHandleForReading]];
+ [[standardError fileHandleForReading] waitForDataInBackgroundAndNotify];
+
+ // Launch and run the tunnel
+ [task launch];
+
+ // TODO: The below code doesn't actually appear to work. We will probably have to switch to system()/exec() for grouped children...
+ // Apply the process group to the child task to ensure it quits with the parent process.
+ // Note that if run from within Xcode, Xcode is the parent process!
+/* pid_t group = setsid();
+ if (group == -1) group = getpgrp();
+ if(setpgid([task processIdentifier], group) == -1) {
+ connectionState = SPSSH_STATE_IDLE;
+ [task terminate];
+ if (lastError) [lastError release];
+ lastError = [[NSString alloc] initWithFormat:NSLocalizedString(@"The SSH Tunnel could not safely be marked as belonging to Sequel Pro, and so has been shut down for security reasons. Please try again.\n\n(Error %i)", @"SSH tunnel could not be security marked by Sequel Pro"), errno];
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+ }*/
+
+ // Listen for output
+ [task waitUntilExit];
+ if (connectionState != SPSSH_STATE_IDLE) {
+ connectionState = SPSSH_STATE_IDLE;
+ lastError = [[NSString alloc] initWithString:NSLocalizedString(@"The SSH Tunnel has unexpectedly closed.", @"SSH tunnel unexpectedly closed")];
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+ }
+
+ // On tunnel close, clean up
+ [[NSNotificationCenter defaultCenter] removeObserver:self
+ name:@"NSFileHandleDataAvailableNotification"
+ object:[standardError fileHandleForReading]];
+ [task release], task = nil;
+ [standardError release], standardError = nil;
+
+ [pool release];
+}
+
+/*
+ * Disconnects the tunnel
+ */
+- (void)disconnect
+{
+ if (connectionState == SPSSH_STATE_IDLE) return;
+ [task terminate];
+ connectionState = SPSSH_STATE_IDLE;
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+}
+
+/*
+ * Processes messages recieved from the SSH task
+ */
+- (void)standardErrorHandler:(NSNotification*)aNotification
+{
+ NSString *notificationText;
+ NSEnumerator *enumerator;
+ NSArray *messages;
+ NSString *message;
+
+ notificationText = [[NSString alloc] initWithData:[[aNotification object] availableData] encoding:NSASCIIStringEncoding];
+
+ if ([notificationText length]) {
+ messages = [notificationText componentsSeparatedByString:@"\n"];
+ enumerator = [messages objectEnumerator];
+ while (message = [enumerator nextObject]) {
+
+ if ([message rangeOfString:@"Entering interactive session."].location != NSNotFound) {
+ connectionState = SPSSH_STATE_CONNECTED;
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+ }
+
+ if ([message rangeOfString:@"Connection established"].location != NSNotFound) {
+ connectionState = SPSSH_STATE_WAITING_FOR_AUTH;
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+ }
+
+ if ([message rangeOfString:@"closed by remote host." ].location != NSNotFound) {
+ connectionState = SPSSH_STATE_IDLE;
+ [task terminate];
+ if (lastError) [lastError release];
+ lastError = [[NSString alloc] initWithString:NSLocalizedString(@"The SSH Tunnel was closed 'by the remote host'. This may indicate a networking issue or a network timeout.", @"SSH tunnel was closed by remote host message")];
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+ }
+ if ([message rangeOfString:@"Operation timed out" ].location != NSNotFound) {
+ connectionState = SPSSH_STATE_IDLE;
+ [task terminate];
+ if (lastError) [lastError release];
+ lastError = [[NSString alloc] initWithFormat:NSLocalizedString(@"The SSH Tunnel was unable to connect to host %@, or the request timed out.\n\nBe sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently %i seconds).", @"SSH tunnel failed or timed out message"), sshHost, [[[NSUserDefaults standardUserDefaults] objectForKey:@"ConnectionTimeoutValue"] intValue]];
+ if (delegate) [delegate performSelectorOnMainThread:stateChangeSelector withObject:self waitUntilDone:NO];
+ }
+ }
+ }
+
+ if (connectionState != SPSSH_STATE_IDLE) {
+ [[standardError fileHandleForReading] waitForDataInBackgroundAndNotify];
+ }
+
+ [notificationText release];
+}
+
+/*
+ * Returns the local port assigned for use by the tunnel
+ */
+- (int) localPort
+{
+ return localPort;
+}
+
+/*
+ * Method to request the password for the current connection, as used by TunnelPassphraseRequester;
+ * called with a verification hash to check against the stored hash, to provide basic security. Note
+ * that this is easily bypassed, but if bypassed the password can already easily be retrieved in the same way.
+ */
+- (NSString *)getPasswordWithVerificationHash:(NSString *)theHash
+{
+ if (passwordInKeychain) return nil;
+ if (theHash != passwordConnectionVerifyHash) return nil;
+ return password;
+}
+
+@end
diff --git a/Source/SSHTunnel.h b/Source/SSHTunnel.h
deleted file mode 100644
index ffe29624..00000000
--- a/Source/SSHTunnel.h
+++ /dev/null
@@ -1,57 +0,0 @@
-#import <Cocoa/Cocoa.h>
-
-@interface SSHTunnel : NSObject
-{
- int code;
- NSArray *tunnelsLocal;
- NSArray *tunnelsRemote;
-
- BOOL shouldStop;
- NSTask *task;
- BOOL connAuth;
- BOOL autoConnect;
- NSPipe *stdErrPipe;
- NSString *connName;
- NSString *status;
- NSString *connPort;
- BOOL connRemote;
- BOOL compression;
- BOOL v1;
- NSString * encryption;
- BOOL socks4;
- NSNumber *socks4p;
- NSString *connUser;
- NSString *connHost;
-}
--(id)initWithName:(NSString*)aName;
--(id)initWithDictionary:(NSDictionary*)aDictionary;
-+(id)tunnelWithName:(NSString*)aName;
-+(NSArray*)tunnelsFromArray:(NSArray*)anArray;
-
--(void)addLocalTunnel:(NSDictionary*)aDictionary;
-- (void)removeLocal:(int)index;
--(void)addRemoteTunnel:(NSDictionary*)aDictionary;
-- (void)removeRemote:(int)index;
-- (void)setLocalValue:(NSString*)aValue ofTunnel:(int)index forKey:(NSString*)key;
-- (void)setRemoteValue:(NSString*)aValue ofTunnel:(int)index forKey:(NSString*)key;
-
-#pragma mark -
-#pragma mark Execution related
-- (void)startTunnel;
-- (void)stopTunnel;
-- (void)toggleTunnel;
-- (void)launchTunnel:(id)foo;
-- (void)stdErr:(NSNotification*)aNotification;
-- (BOOL)isRunning;
-
-#pragma mark -
-#pragma mark Getting tunnel informations
-- (NSString*)status;
-- (NSArray*)arguments;
-- (NSDictionary*)dictionary;
-
-#pragma mark -
-#pragma mark Key/Value coding
-- (NSImage*)icon;
-
-@end
diff --git a/Source/SSHTunnel.m b/Source/SSHTunnel.m
deleted file mode 100644
index 617db8a7..00000000
--- a/Source/SSHTunnel.m
+++ /dev/null
@@ -1,531 +0,0 @@
-//
-// SSHTunnel.m
-// SSH Tunnel Manager 2
-//
-// Created by Yann Bizeul on Wed Nov 19 2003.
-// Copyright (c) 2003 __MyCompanyName__. All rights reserved.
-//
-
-#import "SSHTunnel.h"
-#include <unistd.h>
-
-// start diff lorenz textor
-/*
-#define T_START NSLocalizedString(@"T_START",@"")
-#define T_STOP NSLocalizedString(@"T_STOP",@"")
-#define S_IDLE NSLocalizedString(@"S_IDLE",@"")
-#define S_CONNECTING NSLocalizedString(@"S_CONNECTING",@"")
-#define S_CONNECTED NSLocalizedString(@"S_CONNECTED",@"")
-#define S_AUTH NSLocalizedString(@"S_AUTH",@"")
-#define S_PORT NSLocalizedString(@"S_PORT",@"")
-*/
-#define T_START @"START: %@"
-#define T_STOP @"STOP: %@"
-#define S_IDLE @"Idle"
-#define S_CONNECTING @"Connecting..."
-#define S_CONNECTED @"Connected"
-#define S_AUTH @"Authenticated"
-#define S_PORT "Port %@ forwarded"
-// end diff lorenz textor
-
-@implementation SSHTunnel
-
-#pragma mark -
-#pragma mark Initialization
--(id)init
-{
- return [ self initWithName:@"New Tunnel"];
-}
--(id)initWithName:(NSString*)aName
-{
- NSDictionary *dictionary = [ NSDictionary dictionaryWithObjectsAndKeys:
- [ NSNumber numberWithBool: NO ],@"compression",
- [ NSNumber numberWithBool: YES ],@"connAuth",
- @"", @"connHost",
- aName, @"connName",
- @"", @"connPort",
- [ NSNumber numberWithBool: NO ],@"connRemote",
- @"", @"connUser",
- @"3des", @"encryption",
- [ NSNumber numberWithBool: NO ],@"socks4",
- [ NSNumber numberWithInt: 1080 ], @"socks4p",
- [ NSArray array ], @"tunnelsLocal",
- [ NSArray array ], @"tunnelsRemote",
- [ NSNumber numberWithBool: NO ],@"v1", nil
- ];
- return [ self initWithDictionary: dictionary ];
-}
--(id)initWithDictionary:(NSDictionary*)aDictionary
-{
- NSEnumerator *e;
- NSString *key;
-
- self = [ super init ];
- e = [[ aDictionary allKeys ] objectEnumerator ];
- while (key = [ e nextObject ])
- {
- [ self setValue: [ aDictionary objectForKey: key ] forKey: key ];
- }
- code = 0;
- if ([[ self valueForKey: @"autoConnect" ] boolValue ])
- [ self startTunnel ];
- return self;
-}
-+(id)tunnelWithName:(NSString*)aName
-{
- return [[ SSHTunnel alloc ] initWithName: aName ];
-}
-+(SSHTunnel*)tunnelFromDictionary:(NSDictionary*)aDictionary
-{
- return [[ SSHTunnel alloc ] initWithDictionary: aDictionary ];
-}
-+(NSArray*)tunnelsFromArray:(NSArray*)anArray
-{
- NSMutableArray *newArray;
- SSHTunnel *currentTunnel;
- NSEnumerator *e;
- NSDictionary *currentTunnelDictionary;
-
- newArray = [ NSMutableArray array ];
- e = [ anArray objectEnumerator ];
- while (currentTunnelDictionary = [ e nextObject ])
- {
- currentTunnel = [ SSHTunnel tunnelFromDictionary: currentTunnelDictionary ];
- [ newArray addObject: currentTunnel ];
- }
- return [[ newArray copy ] autorelease ];
-}
-
-#pragma mark -
-#pragma mark Adding and removing port redir.
--(void)addLocalTunnel:(NSDictionary*)aDictionary;
-{
- NSMutableArray *tempTunnelsLocal = [ NSMutableArray arrayWithArray: tunnelsLocal ];
- [ tempTunnelsLocal addObject: aDictionary ];
- [ tunnelsLocal release ];
- tunnelsLocal = [ tempTunnelsLocal copy ];
-}
-- (void)removeLocal:(int)index
-{
- NSMutableArray *tempLocalTunnels = [ tunnelsLocal mutableCopy ];
- [ tempLocalTunnels removeObjectAtIndex: index ];
- [ tunnelsLocal release ];
- tunnelsLocal = [ tempLocalTunnels copy ];
- [ tempLocalTunnels release ];
-}
--(void)addRemoteTunnel:(NSDictionary*)aDictionary;
-{
- NSMutableArray *tempTunnelsRemote = [ NSMutableArray arrayWithArray: tunnelsRemote ];
- [ tempTunnelsRemote addObject: aDictionary ];
- [ tunnelsRemote release ];
- tunnelsRemote = [ tempTunnelsRemote copy ];
-}
-- (void)removeRemote:(int)index
-{
- NSMutableArray *tempRemoteTunnels = [ tunnelsRemote mutableCopy ];
- [ tempRemoteTunnels removeObjectAtIndex: index ];
- [ tunnelsRemote release ];
- tunnelsRemote = [ tempRemoteTunnels copy ];
- [ tempRemoteTunnels release ];
-}
-- (void)setLocalValue:(NSString*)aValue ofTunnel:(int)index forKey:(NSString*)key
-{
- NSMutableArray *tempLocalTunnel;
- NSMutableDictionary *tempCurrentTunnel;
-
- tempLocalTunnel = [tunnelsLocal mutableCopy];
- tempCurrentTunnel = [[ tempLocalTunnel objectAtIndex: index ] mutableCopy ];
-
- [ tempCurrentTunnel setObject: aValue forKey: key ];
- [ tempLocalTunnel replaceObjectAtIndex:index withObject:[tempCurrentTunnel copy ]];
- [ tempCurrentTunnel release ];
- [ tunnelsLocal release ];
- tunnelsLocal = [ tempLocalTunnel copy ];
-}
-- (void)setRemoteValue:(NSString*)aValue ofTunnel:(int)index forKey:(NSString*)key
-{
- NSMutableArray *tempRemoteTunnel;
- NSMutableDictionary *tempCurrentTunnel;
-
- tempRemoteTunnel = [tunnelsRemote mutableCopy];
- tempCurrentTunnel = [[ tempRemoteTunnel objectAtIndex: index ] mutableCopy ];
-
- [ tempCurrentTunnel setObject: aValue forKey: key ];
- [ tempRemoteTunnel replaceObjectAtIndex:index withObject:[tempCurrentTunnel copy ]];
- [ tempCurrentTunnel release ];
- [ tunnelsRemote release ];
- tunnelsRemote = [ tempRemoteTunnel copy ];
-}
-
-#pragma mark -
-#pragma mark Execution related
-- (void)startTunnel
-{
-// NSDictionary *t;
-// NSEnumerator *e;
-// BOOL asRoot = NO;
-
- if ([ self isRunning ])
- return;
-
- shouldStop = NO;
- /*
- [ arguments addObject: @"-N" ];
- [ arguments addObject: @"-v" ];
- [ arguments addObject: @"-p" ];
- if ([ connPort length ])
- [ arguments addObject: connPort];
- else
- [ arguments addObject: @"22" ];
-
- if (connRemote)
- [ arguments addObject: @"-g" ];
- if (compression)
- [ arguments addObject: @"-C" ];
- if (v1)
- [ arguments addObject: @"-1" ];
-
- [ arguments addObject: @"-c"];
- if (encryption)
- [ arguments addObject: encryption];
- else
- [ arguments addObject: @"3des"];
-
- if (socks4 && socks4p != nil)
- {
- [ arguments addObject: @"-D" ];
- [ arguments addObject: [ socks4p stringValue ]];
- }
- [ arguments addObject: [ NSString stringWithFormat: @"%@@%@",
- connUser, connHost ]
- ];
-
- NSString *hostPort;
- e = [ tunnelsLocal objectEnumerator ];
- while (t = [ e nextObject ])
- {
- [ arguments addObject: @"-L" ];
- if ([[ t objectForKey:@"hostport"] isEqualTo: @"" ])
- hostPort = [ t objectForKey:@"port" ];
- else
- hostPort = [ t objectForKey:@"hostport" ];
- [ arguments addObject: [NSString stringWithFormat:@"%@/%@/%@",
- [ t objectForKey:@"port"],
- [ t objectForKey:@"host"],
- hostPort
- ] ];
- if ([[ t objectForKey:@"port"] intValue] < 1024)
- asRoot=YES;
- }
-
- e = [ tunnelsRemote objectEnumerator ];
- while (t = [ e nextObject ])
- {
- [ arguments addObject: @"-R" ];
- if ([[ t objectForKey:@"hostport"] isEqualTo: @"" ])
- hostPort = [ t objectForKey:@"port" ];
- else
- hostPort = [ t objectForKey:@"hostport" ];
- [ arguments addObject: [NSString stringWithFormat:@"%@/%@/%@",
- [ t objectForKey:@"port"],
- [ t objectForKey:@"host"],
- hostPort
- ]];
- }
- args = [ NSMutableDictionary dictionary ];
- [ args setObject: arguments forKey:@"arguments" ];
- [ args setObject: [ NSNumber numberWithBool: connAuth ] forKey: @"handleAuth" ];
- [ args setObject: connName forKey:@"tunnelName" ];
- [ args setObject: [ NSNumber numberWithBool: asRoot ] forKey: @"asRoot" ];
-
-
- [ NSThread detachNewThreadSelector:@selector(launchTunnel:)
- toTarget: self
- withObject: args ];
- */
- [ NSThread detachNewThreadSelector:@selector(launchTunnel:)
- toTarget: self
- withObject: nil ];
-// [ arguments release ];
-
-}
-- (void)stopTunnel
-{
- if (! [ self isRunning ])
- return;
- shouldStop=YES;
- [ self setValue: nil forKey: @"status" ];
- [ task terminate ];
- code = 0;
- [[ NSNotificationCenter defaultCenter] postNotificationName:@"STMStatusChanged" object:self ];
-}
-
-- (void)toggleTunnel
-{
- if ([ self isRunning ])
- [ self stopTunnel ];
- else
- [ self startTunnel ];
-}
-
-- (void)launchTunnel:(id)foo;
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
- if (task)
- [ task release ];
- task = [[ NSTask alloc ] init ];
- NSMutableDictionary *environment = [ NSMutableDictionary dictionaryWithDictionary: [[ NSProcessInfo processInfo ] environment ]];
- NSString *pathToAuthentifier = [[ NSBundle mainBundle ] pathForResource: @"askForPass" ofType: @"sh" ];
- if (socks4)
- [ task setLaunchPath: [[ NSBundle mainBundle ] pathForResource: @"ssh" ofType: @"" ]];
- else
- [ task setLaunchPath: @"/usr/bin/ssh" ];
- [ task setArguments: [ self arguments ]];
- if (connAuth)
- {
- [ environment removeObjectForKey: @"SSH_AGENT_PID" ];
- [ environment removeObjectForKey: @"SSH_AUTH_SOCK" ];
- [ environment setObject: pathToAuthentifier forKey: @"SSH_ASKPASS" ];
- [ environment setObject:@":0" forKey:@"DISPLAY" ];
- }
- [ environment setObject: connName forKey: @"TUNNEL_NAME" ];
- [ task setEnvironment: environment ];
-
- stdErrPipe = [[ NSPipe alloc ] init ];
- [ task setStandardError: stdErrPipe ];
-
- [[ NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(stdErr:)
- name: @"NSFileHandleDataAvailableNotification"
- object:[ stdErrPipe fileHandleForReading]];
-
- [[ stdErrPipe fileHandleForReading] waitForDataInBackgroundAndNotify ];
-
- NSLog(T_START,connName);
- [ self setValue: S_CONNECTING forKey: @"status" ];
- code = 1;
- [ task launch ];
- [[ NSNotificationCenter defaultCenter] postNotificationName:@"STMStatusChanged" object:self ];
- [ task waitUntilExit ];
- sleep(1);
- code = 0;
- [ self setValue: S_IDLE forKey: @"status" ];
- NSLog(T_STOP,connName);
- [[ NSNotificationCenter defaultCenter] removeObserver:self
- name: @"NSFileHandleDataAvailableNotification"
- object:[ stdErrPipe fileHandleForReading]];
- [ task release ];
- task = nil;
- [ stdErrPipe release ];
- stdErrPipe = nil;
- [[ NSNotificationCenter defaultCenter] postNotificationName:@"STMStatusChanged" object:self ];
- if (! shouldStop)
- [ self startTunnel ];
- [ pool release ];
-}
-
-- (void)stdErr:(NSNotification*)aNotification
-{
- NSData *data = [[ aNotification object ] availableData ];
- NSString *log = [[ NSString alloc ] initWithData: data encoding: NSASCIIStringEncoding ];
- BOOL wait = YES;
- if ([ log length ])
- {
- //NSLog(log);
- NSArray *lines = [ log componentsSeparatedByString:@"\n" ];
- NSEnumerator *e = [ lines objectEnumerator ];
- NSString *line;
- while (line = [ e nextObject ])
- {
- if ([ line rangeOfString:@"Entering interactive session." ].location != NSNotFound)
- {
- code = 2;
- [ self setValue: S_CONNECTED forKey: @"status"];
- }
- if ([ line rangeOfString:@"Authentication succeeded" ].location != NSNotFound)
- [ self setValue: S_AUTH forKey: @"status"];
- if ([ line rangeOfString:@"Connections to local port" ].location != NSNotFound)
- {
- NSScanner *s;
- NSString *port;
- s = [ NSScanner scannerWithString:log];
- [ s scanUpToString: @"Connections to local port " intoString: nil ];
- [ s scanString: @"Connections to local port " intoString: nil ];
- [ s scanUpToString: @"forwarded" intoString:&port];
- [ self setValue: [ NSString stringWithFormat: @"Port %@ forwarded", port ] forKey: @"status"];
- }
- if ([ line rangeOfString:@"closed by remote host." ].location != NSNotFound)
- {
- [ task terminate];
- [ self setValue: @"Connection closed" forKey: @"status"];
- wait = NO;
- }
- [[ NSNotificationCenter defaultCenter] postNotificationName:@"STMStatusChanged" object:self ];
- }
- if (wait)
- [[ stdErrPipe fileHandleForReading ] waitForDataInBackgroundAndNotify ];
- }
- [ log release] ;
-}
-
-- (BOOL)isRunning
-{
- if ([ task isRunning ])
- return YES;
- return NO;
-}
-
-#pragma mark -
-#pragma mark Getting tunnel informations
-- (NSString *)status
-{
- if (status)
- return status;
- return S_IDLE;
-}
-- (NSArray*)arguments
-{
- NSMutableArray *arguments;
- NSEnumerator *e;
- NSDictionary *t;
- BOOL asRoot;
-
- arguments = [ NSMutableArray array ];
- [ arguments addObject: @"-N" ];
- [ arguments addObject: @"-v" ];
- [ arguments addObject: @"-p" ];
- if ([ connPort length ])
- [ arguments addObject: connPort];
- else
- [ arguments addObject: @"22" ];
-
- if (connRemote)
- [ arguments addObject: @"-g" ];
- if (compression)
- [ arguments addObject: @"-C" ];
- if (v1)
- [ arguments addObject: @"-1" ];
-
- [ arguments addObject: @"-c"];
- if (encryption)
- [ arguments addObject: encryption];
- else
- [ arguments addObject: @"3des"];
-
- if (socks4 && socks4p != nil)
- {
- [ arguments addObject: @"-D" ];
- [ arguments addObject: [ socks4p stringValue ]];
- }
- [ arguments addObject: [ NSString stringWithFormat: @"%@@%@",
- connUser, connHost ]
- ];
-
- NSString *hostPort;
- e = [ tunnelsLocal objectEnumerator ];
- while (t = [ e nextObject ])
- {
- [ arguments addObject: @"-L" ];
- if ([[ t objectForKey:@"hostport"] isEqualTo: @"" ])
- hostPort = [ t objectForKey:@"port" ];
- else
- hostPort = [ t objectForKey:@"hostport" ];
- [ arguments addObject: [NSString stringWithFormat:@"%@/%@/%@",
- [ t objectForKey:@"port"],
- [ t objectForKey:@"host"],
- hostPort
- ] ];
- if ([[ t objectForKey:@"port"] intValue] < 1024)
- asRoot=YES;
- }
-
- e = [ tunnelsRemote objectEnumerator ];
- while (t = [ e nextObject ])
- {
- [ arguments addObject: @"-R" ];
- if ([[ t objectForKey:@"hostport"] isEqualTo: @"" ])
- hostPort = [ t objectForKey:@"port" ];
- else
- hostPort = [ t objectForKey:@"hostport" ];
- [ arguments addObject: [NSString stringWithFormat:@"%@/%@/%@",
- [ t objectForKey:@"port"],
- [ t objectForKey:@"host"],
- hostPort
- ]];
- }
-
- return [[ arguments copy ] autorelease ];
-}
-
-- (NSDictionary*)dictionary
-{
- return [ NSDictionary dictionaryWithObjectsAndKeys:
- [ NSNumber numberWithBool: compression ],@"compression",
- [ NSNumber numberWithBool: connAuth ],@"connAuth",
- [ NSNumber numberWithBool: autoConnect ],@"autoConnect",
- connHost, @"connHost",
- connName, @"connName",
- connPort, @"connPort",
- [ NSNumber numberWithBool: connRemote ],@"connRemote",
- connUser, @"connUser",
- encryption, @"encryption",
- [ NSNumber numberWithBool: socks4 ],@"socks4",
- socks4p, @"socks4p",
- tunnelsLocal, @"tunnelsLocal",
- tunnelsRemote, @"tunnelsRemote",
- [ NSNumber numberWithBool: v1 ],@"v1", nil
- ];
-}
-
-
-#pragma mark -
-#pragma mark Key/Value coding
-- (NSImage*)icon
-{
- switch (code)
- {
- case 0:
- return [ NSImage imageNamed: @"offState" ];
- break;
- case 1:
- return [ NSImage imageNamed: @"middleState" ];
- break;
- case 2:
- return [ NSImage imageNamed: @"onState" ];
- break;
- }
- return [ NSImage imageNamed: @"offState" ];
-}
-- (void)setValue:(id)value forUndefinedKey:(NSString *)key
-{
- NSLog(@"key %@ undefined",key);
-}
-- (id)valueForUndefinedKey:(NSString *)key
-{
- return nil;
-}
-
-#pragma mark -
-#pragma mark Misc.
--(void)dealloc
-{
- [ self stopTunnel ];
- [ tunnelsLocal release ];
- [ tunnelsRemote release ];
-
- [ task release ];
- [ stdErrPipe release ];
- [ connName release ];
- [ status release ];
- [ connPort release ];
- [ encryption release ];
- [ socks4p release ];
- [ connUser release ];
- [ connHost release ];
-
- // start diff lorenz textor
- [super dealloc];
- // end diff lorenz textor
-}
-@end
diff --git a/Source/TableDocument.h b/Source/TableDocument.h
index 738acdfb..e71e80ac 100644
--- a/Source/TableDocument.h
+++ b/Source/TableDocument.h
@@ -28,6 +28,7 @@
#import <Cocoa/Cocoa.h>
#import <MCPKit_bundled/MCPKit_bundled.h>
#import <WebKit/WebKit.h>
+#import "SPSSHTunnel.h"
@class CMMCPConnection, CMMCPResult;
@@ -65,8 +66,13 @@
IBOutlet id passwordField;
IBOutlet id portField;
IBOutlet id databaseField;
+ IBOutlet id sshCheckbox;
+ IBOutlet id sshHostField;
+ IBOutlet id sshUserField;
+ IBOutlet id sshPasswordField;
+ IBOutlet id sshPortField;
- IBOutlet id connectProgressBar;
+ IBOutlet NSProgressIndicator *connectProgressBar;
IBOutlet NSTextField *connectProgressStatusText;
IBOutlet id databaseNameField;
IBOutlet id databaseEncodingButton;
@@ -92,6 +98,11 @@
NSString *mySQLVersion;
NSUserDefaults *prefs;
+ NSString *connectionKeychainItemName;
+ NSString *connectionKeychainItemAccount;
+ NSString *connectionSSHKeychainItemName;
+ NSString *connectionSSHKeychainItemAccount;
+
NSMenu *selectEncodingMenu;
BOOL _supportsEncoding;
NSString *_encoding;
@@ -107,13 +118,17 @@
//start sheet
- (void)setShouldAutomaticallyConnect:(BOOL)shouldAutomaticallyConnect;
- (IBAction)connectToDB:(id)sender;
-- (IBAction)connect:(id)sender;
+- (IBAction)initiateConnection:(id)sender;
+- (void)initiateSSHTunnelConnection;
+- (void)sshTunnelCallback:(SPSSHTunnel *)theTunnel;
+- (void)initiateMySQLConnection:(SPSSHTunnel *)theTunnel;
+- (void)failConnectionWithErrorMessage:(NSString *)theErrorMessage;
- (IBAction)cancelConnectSheet:(id)sender;
- (IBAction)closeSheet:(id)sender;
- (IBAction)chooseFavorite:(id)sender;
+- (IBAction)toggleUseSSH:(id)sender;
- (IBAction)editFavorites:(id)sender;
- (id)selectedFavorite;
-- (NSString *)selectedFavoritePassword;
- (void)connectSheetAddToFavorites:(id)sender;
- (void)addToFavoritesName:(NSString *)name host:(NSString *)host socket:(NSString *)socket
user:(NSString *)user password:(NSString *)password
diff --git a/Source/TableDocument.m b/Source/TableDocument.m
index ff13096d..2b98c776 100644
--- a/Source/TableDocument.m
+++ b/Source/TableDocument.m
@@ -68,6 +68,11 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
_encoding = [@"utf8" retain];
chooseDatabaseButton = nil;
chooseDatabaseToolbarItem = nil;
+ connectionKeychainItemName = nil;
+ connectionKeychainItemAccount = nil;
+ connectionSSHKeychainItemName = nil;
+ connectionSSHKeychainItemAccount = nil;
+ selectedDatabase = nil;
printWebView = [[WebView alloc] init];
[printWebView setFrameLoadDelegate:self];
@@ -90,7 +95,7 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
// Register double click for the favorites view (double click favorite to connect)
[connectFavoritesTableView setTarget:self];
- [connectFavoritesTableView setDoubleAction:@selector(connect:)];
+ [connectFavoritesTableView setDoubleAction:@selector(initiateConnection:)];
// Find the Database -> Database Encoding menu (it's not in our nib, so we can't use interface builder)
selectEncodingMenu = [[[[[NSApp mainMenu] itemWithTag:1] submenu] itemWithTag:1] submenu];
@@ -224,7 +229,7 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
//start sheet
/**
- * Set whether the connection sheet should automaticall start connecting
+ * Set whether the connection sheet should automatically start connecting
*/
- (void)setShouldAutomaticallyConnect:(BOOL)shouldAutomaticallyConnect
{
@@ -240,151 +245,264 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
// load the details of the currently selected favorite into the text boxes in connect sheet
[self chooseFavorite:self];
-
+
// run the connect sheet (modal)
[NSApp beginSheet:connectSheet
modalForWindow:tableWindow
modalDelegate:self
- didEndSelector:@selector(connectSheetDidEnd:returnCode:contextInfo:)
+ didEndSelector:nil
contextInfo:nil];
// Connect automatically to the last used or default favourite
// connectSheet must open first.
if (_shouldOpenConnectionAutomatically) {
_shouldOpenConnectionAutomatically = false;
- [self connect:self];
+ [self initiateConnection:self];
}
}
+
/*
- invoked when user hits the connect-button of the connectSheet
- stops modal session with code:
- 1 when connected with success
- 2 when no connection to host
- 3 when no connection to db
- 4 when hostField and socketField are empty
+ * Starts the connection process; invoked when user hits the connect button
+ * of the connection sheet or double-clicks on a favourite of the connectSheet.
+ * Error-checks fields as required, and triggers connection of MySQL or any
+ * proxies in use.
*/
-- (IBAction)connect:(id)sender
+- (IBAction)initiateConnection:(id)sender
{
- int code;
-
+
+ // Error-check required fields before starting a connection
+ if (![[hostField stringValue] length] && ![[socketField stringValue] length]) {
+ [self failConnectionWithErrorMessage:NSLocalizedString(@"Insufficient details provided to establish a connection. Please provide at least a host or socket.", @"insufficient details informative message")];
+ return;
+ }
+ if ([sshCheckbox state] == NSOnState && (![[sshHostField stringValue] length] || ![[sshUserField stringValue] length])) {
+ [self failConnectionWithErrorMessage:NSLocalizedString(@"Please enter the hostname and username for the SSH Tunnel, or disable the SSH Tunnel.", @"message of panel when ssh details are incomplete")];
+ return;
+ }
+
+ // Basic details have validated - start the connection process animating
[connectProgressBar startAnimation:self];
[connectProgressStatusText setHidden:NO];
[connectProgressStatusText display];
-
- [selectedDatabase autorelease];
- selectedDatabase = nil;
-
- code = 0;
- if ( [[hostField stringValue] isEqualToString:@""] && [[socketField stringValue] isEqualToString:@""] ) {
- code = 4;
- } else {
- if ( ![[socketField stringValue] isEqualToString:@""] ) {
- //connect to socket
- mySQLConnection = [[CMMCPConnection alloc] initToSocket:[socketField stringValue]
- withLogin:[userField stringValue]
- password:[passwordField stringValue]];
- [hostField setStringValue:@"localhost"];
+
+ // 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) {
+ if ([[keyChainInstance getPasswordForName:connectionKeychainItemName account:connectionKeychainItemAccount] isEqualToString:[passwordField stringValue]]) {
+ [passwordField setStringValue:@""];
+ [[self undoManager] removeAllActionsWithTarget:passwordField];
} else {
- //connect to host
- mySQLConnection = [[CMMCPConnection alloc] initToHost:[hostField stringValue]
- withLogin:[userField stringValue]
- password:[passwordField stringValue]
- usingPort:[portField intValue]];
+ [connectionKeychainItemName release], connectionKeychainItemName = nil;
+ [connectionKeychainItemAccount release], connectionKeychainItemAccount = nil;
}
- [mySQLConnection setParentWindow:tableWindow];
-
- if ( ![mySQLConnection isConnected] )
- code = 2;
- if ( !code && ![[databaseField stringValue] isEqualToString:@""] ) {
- if ([mySQLConnection selectDB:[databaseField stringValue]]) {
- selectedDatabase = [[databaseField stringValue] retain];
- } else {
- code = 3;
- }
+ }
+ if (connectionSSHKeychainItemName) {
+ if ([[keyChainInstance getPasswordForName:connectionSSHKeychainItemName account:connectionSSHKeychainItemAccount] isEqualToString:[sshPasswordField stringValue]]) {
+ [sshPasswordField setStringValue:@""];
+ [[self undoManager] removeAllActionsWithTarget:sshPasswordField];
+ } else {
+ [connectionSSHKeychainItemName release], connectionSSHKeychainItemName = nil;
+ [connectionSSHKeychainItemAccount release], connectionSSHKeychainItemAccount = nil;
}
- if ( !code )
- code = 1;
}
-
- // close sheet
- [connectSheet orderOut:nil];
- [NSApp endSheet:connectSheet returnCode:code];
- [connectProgressBar stopAnimation:self];
- [connectProgressStatusText setHidden:YES];
+
+ // Initiate the SSH connection process if one has been set
+ if ([sshCheckbox state] == NSOnState) {
+ [self initiateSSHTunnelConnection];
+ return;
+ }
+
+ // ...or start the MySQL connection process directly
+ [self initiateMySQLConnection:nil];
}
--(void)connectSheetDidEnd:(NSWindow*)sheet returnCode:(int)code contextInfo:(void*)contextInfo
+/*
+ * Initiate the SSH connection process, while the connection sheet is still open.
+ * This should only be called as part of initiateConnection:, and will indirectly
+ * call initiateMySQLConnection if it's successful.
+ */
+- (void)initiateSSHTunnelConnection
+{
+ SPSSHTunnel *theTunnel;
+ [connectProgressStatusText setStringValue:NSLocalizedString(@"SSH connecting...", @"SSH connecting very short status message")];
+ [connectProgressStatusText display];
+
+ // Set up the tunnel details
+ theTunnel = [[SPSSHTunnel alloc] initToHost:[sshHostField stringValue] port:([sshPortField intValue]?[sshPortField intValue]:22) login:[sshUserField stringValue] tunnellingToPort:([portField intValue]?[portField intValue]:3306) onHost:[hostField stringValue]];
+
+ // Add keychain or plaintext password as appropriate - note the checks in initiateConnection.
+ if (connectionSSHKeychainItemName) {
+ [theTunnel setPasswordKeychainName:connectionSSHKeychainItemName account:connectionSSHKeychainItemAccount];
+ } else {
+ [theTunnel setPassword:[sshPasswordField stringValue]];
+ }
+
+ // Set the callback function on the tunnel
+ [theTunnel setConnectionStateChangeSelector:@selector(sshTunnelCallback:) delegate:self];
+
+ // Ask the tunnel to connect. This will call the callback below on success or failure, passing
+ // itself as an argument - retain count should be one at this point.
+ [theTunnel connect];
+}
+
+/*
+ * A callback function for the SSH Tunnel setup process - will be called on a connection
+ * state change, allowing connection to fail or proceed as appropriate. If successful,
+ * will call initiateMySQLConnection.
+ */
+- (void)sshTunnelCallback:(SPSSHTunnel *)theTunnel
+{
+ int newState = [theTunnel state];
+
+ if (newState == SPSSH_STATE_IDLE) {
+ [self failConnectionWithErrorMessage:[theTunnel lastError]];
+ } else if (newState == SPSSH_STATE_CONNECTED) {
+ [self initiateMySQLConnection:theTunnel];
+ }
+}
+
+/*
+ * Set up the MySQL connection, either through a successful tunnel or directly.
+ */
+- (void)initiateMySQLConnection:(SPSSHTunnel *)theTunnel
{
- [sheet orderOut:self];
-
CMMCPResult *theResult;
id version;
-
- if ( code == 1) {
- //connected with success
- //register as delegate
- [mySQLConnection setDelegate:self];
- // set encoding
- NSString *encodingName = [prefs objectForKey:@"DefaultEncoding"];
- if ( [encodingName isEqualToString:@"Autodetect"] ) {
- [self setConnectionEncoding:[self databaseEncoding] reloadingViews:NO];
+
+ if (theTunnel)
+ [connectProgressStatusText setStringValue:NSLocalizedString(@"MySQL connecting...", @"MySQL connecting very short status message")];
+ else
+ [connectProgressStatusText setStringValue:NSLocalizedString(@"Connecting...", @"Generic connecting very short status message")];
+ [connectProgressStatusText display];
+
+ // Initialise to socket if appropriate.
+ // Note it is currently possible to connect to a socket with a useless SSH tunnel set
+ // up; this will be improved upon in future UI/code work.
+ if (![[socketField stringValue] isEqualToString:@""]) {
+ mySQLConnection = [[CMMCPConnection alloc] initToSocket:[socketField stringValue]
+ withLogin:[userField stringValue]];
+ [hostField setStringValue:@"localhost"];
+
+ // Otherwise, initialise to host, using tunnel if appropriate
+ } else {
+ if (theTunnel) {
+ mySQLConnection = [[CMMCPConnection alloc] initToHost:@"127.0.0.1"
+ withLogin:[userField stringValue]
+ usingPort:[theTunnel localPort]];
+ [mySQLConnection setSSHTunnel:theTunnel];
+ [theTunnel release];
} else {
- [self setConnectionEncoding:[self mysqlEncodingFromDisplayEncoding:encodingName] reloadingViews:NO];
+ mySQLConnection = [[CMMCPConnection alloc] initToHost:[hostField stringValue]
+ withLogin:[userField stringValue]
+ usingPort:[portField intValue]];
}
- //get mysql version
- theResult = [mySQLConnection queryString:@"SHOW VARIABLES LIKE 'version'"];
- version = [[theResult fetchRowAsArray] objectAtIndex:1];
- if ( [version isKindOfClass:[NSData class]] ) {
- // starting with MySQL 4.1.14 the mysql variables are returned as nsdata
- mySQLVersion = [[NSString alloc] initWithData:version encoding:[mySQLConnection encoding]];
+ }
+ [mySQLConnection setParentWindow:tableWindow];
+
+ // Set the password as appropriate
+ if (connectionKeychainItemName) {
+ [mySQLConnection setPasswordKeychainName:connectionKeychainItemName account:connectionKeychainItemAccount];
+ } else {
+ [mySQLConnection setPassword:[passwordField stringValue]];
+ }
+
+ // Connect
+ [mySQLConnection connect];
+
+ if (![mySQLConnection isConnected]) {
+ [self failConnectionWithErrorMessage:[NSString stringWithFormat:NSLocalizedString(@"Unable to connect to host %@, or the request timed out.\n\nBe sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently %i seconds).\n\nMySQL said: %@", @"message of panel when connection to host failed"), [hostField stringValue], [[prefs objectForKey:@"ConnectionTimeoutValue"] intValue], [mySQLConnection getLastErrorMessage]]];
+ if (theTunnel) [theTunnel disconnect];
+ return;
+ }
+ if (![[databaseField stringValue] isEqualToString:@""]) {
+ if ([mySQLConnection selectDB:[databaseField stringValue]]) {
+ if (selectedDatabase) [selectedDatabase release], selectedDatabase = nil;
+ selectedDatabase = [[databaseField stringValue] retain];
} else {
- mySQLVersion = [[NSString stringWithString:version] retain];
+ [self failConnectionWithErrorMessage:[NSString stringWithFormat:NSLocalizedString(@"Connected to host, but unable to connect to database %@.\n\nBe sure that the database exists and that you have the necessary privileges.\n\nMySQL said: %@", @"message of panel when connection to db failed"), [databaseField stringValue], [mySQLConnection getLastErrorMessage]]];
+ if (theTunnel) [theTunnel disconnect];
+ return;
}
-
- [self setDatabases:self];
-
- // For each of the main controllers assigned the current connection
- [tablesListInstance setConnection:mySQLConnection];
- [tableSourceInstance setConnection:mySQLConnection];
- [tableContentInstance setConnection:mySQLConnection];
- [tableRelationsInstance setConnection:mySQLConnection];
- [customQueryInstance setConnection:mySQLConnection];
- [tableDumpInstance setConnection:mySQLConnection];
- [spExportControllerInstance setConnection:mySQLConnection];
- [tableDataInstance setConnection:mySQLConnection];
- [extendedTableInfoInstance setConnection:mySQLConnection];
- [databaseDataInstance setConnection:mySQLConnection];
-
- // Set the cutom query editor's MySQL version
- [customQueryInstance setMySQLversion:mySQLVersion];
-
- [self setFileName:[NSString stringWithFormat:@"(MySQL %@) %@@%@ %@", mySQLVersion, [userField stringValue],
- [hostField stringValue], [databaseField stringValue]]];
- [tableWindow setTitle:[NSString stringWithFormat:@"(MySQL %@) %@/%@", mySQLVersion, [self name], [databaseField stringValue]]];
-
- // Connected Growl notification
- [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Connected"
- description:[NSString stringWithFormat:NSLocalizedString(@"Connected to %@",@"description for connected growl notification"), [tableWindow title]]
- notificationName:@"Connected"];
-
- } else if (code == 2) {
- //can't connect to host
- NSBeginAlertSheet(NSLocalizedString(@"Connection failed!", @"connection failed"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil,
- @selector(sheetDidEnd:returnCode:contextInfo:), @"connect",
- [NSString stringWithFormat:NSLocalizedString(@"Unable to connect to host %@, or the request timed out.\n\nBe sure that the address is correct and that you have the necessary privileges, or try increasing the connection timeout (currently %i seconds).\n\nMySQL said: %@", @"message of panel when connection to host failed"), [hostField stringValue], [[prefs objectForKey:@"ConnectionTimeoutValue"] intValue], [mySQLConnection getLastErrorMessage]]);
- } else if (code == 3) {
- //can't connect to db
- NSBeginAlertSheet(NSLocalizedString(@"Connection failed!", @"connection failed"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil,
- @selector(sheetDidEnd:returnCode:contextInfo:), @"connect",
- [NSString stringWithFormat:NSLocalizedString(@"Connected to host, but unable to connect to database %@.\n\nBe sure that the database exists and that you have the necessary privileges.\n\nMySQL said: %@", @"message of panel when connection to db failed"), [databaseField stringValue], [mySQLConnection getLastErrorMessage]]);
- } else if (code == 4) {
- //no host is given
- NSBeginAlertSheet(NSLocalizedString(@"Insufficient connection details", @"insufficient details message"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil,
- @selector(sheetDidEnd:returnCode:contextInfo:), @"connect", NSLocalizedString(@"Insufficient details provided to establish a connection. Please provide at least a host or socket.", @"insufficient details informative message"));
}
+ // Successful connection! Close the connection sheet
+ [connectSheet orderOut:nil];
+ [NSApp endSheet:connectSheet];
+ [connectProgressBar stopAnimation:self];
+ [connectProgressStatusText setHidden:YES];
+
+ // Set up the connection.
+ // Register as a delegate
+ [mySQLConnection setDelegate:self];
+
+ // Set encoding
+ NSString *encodingName = [prefs objectForKey:@"DefaultEncoding"];
+ if ( [encodingName isEqualToString:@"Autodetect"] ) {
+ [self setConnectionEncoding:[self databaseEncoding] reloadingViews:NO];
+ } else {
+ [self setConnectionEncoding:[self mysqlEncodingFromDisplayEncoding:encodingName] reloadingViews:NO];
+ }
+
+ // Get the mysql version
+ theResult = [mySQLConnection queryString:@"SHOW VARIABLES LIKE 'version'"];
+ version = [[theResult fetchRowAsArray] objectAtIndex:1];
+ if ( [version isKindOfClass:[NSData class]] ) {
+ // starting with MySQL 4.1.14 the mysql variables are returned as nsdata
+ mySQLVersion = [[NSString alloc] initWithData:version encoding:[mySQLConnection encoding]];
+ } else {
+ mySQLVersion = [[NSString stringWithString:version] retain];
+ }
+
+ [self setDatabases:self];
+
+ // For each of the main controllers assign the current connection
+ [tablesListInstance setConnection:mySQLConnection];
+ [tableSourceInstance setConnection:mySQLConnection];
+ [tableContentInstance setConnection:mySQLConnection];
+ [tableRelationsInstance setConnection:mySQLConnection];
+ [customQueryInstance setConnection:mySQLConnection];
+ [tableDumpInstance setConnection:mySQLConnection];
+ [spExportControllerInstance setConnection:mySQLConnection];
+ [tableDataInstance setConnection:mySQLConnection];
+ [extendedTableInfoInstance setConnection:mySQLConnection];
+ [databaseDataInstance setConnection:mySQLConnection];
+
+ // Set the cutom query editor's MySQL version
+ [customQueryInstance setMySQLversion:mySQLVersion];
+
+ [self setFileName:[NSString stringWithFormat:@"(MySQL %@) %@@%@ %@", mySQLVersion, [userField stringValue],
+ [hostField stringValue], [databaseField stringValue]]];
+ [tableWindow setTitle:[NSString stringWithFormat:@"(MySQL %@) %@/%@", mySQLVersion, [self name], [databaseField stringValue]]];
+
+ // Connected Growl notification
+ [[SPGrowlController sharedGrowlController] notifyWithTitle:@"Connected"
+ description:[NSString stringWithFormat:NSLocalizedString(@"Connected to %@",@"description for connected growl notification"), [tableWindow title]]
+ notificationName:@"Connected"];
+}
+
+/*
+ * Ends a connection attempt by stopping the connect sheet animation,
+ * stopping the document-modal sheet, and displaying a specified error
+ * message. The button on the error message will open the connection
+ * sheet again with the failed details.
+ */
+- (void)failConnectionWithErrorMessage:(NSString *)theErrorMessage
+{
+ // Clean up the interface
+ [connectProgressBar stopAnimation:self];
+ [connectProgressBar display];
+ [connectProgressStatusText setHidden:YES];
+ [connectProgressStatusText display];
+
+ // Stop the modal sheet
+ [connectSheet orderOut:nil];
+ [NSApp endSheet:connectSheet];
+
+ // Display the connection error message
+ NSBeginAlertSheet(NSLocalizedString(@"Connection failed!", @"connection failed title"), NSLocalizedString(@"OK", @"OK button"), nil, nil, tableWindow, self, nil, @selector(sheetDidEnd:returnCode:contextInfo:), @"connect", theErrorMessage);
}
- (IBAction)cancelConnectSheet:(id)sender
@@ -411,18 +529,69 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
if (![self selectedFavorite])
return;
- [nameField setStringValue:([self valueForKeyPath:@"selectedFavorite.name"] ? [self valueForKeyPath:@"selectedFavorite.name"] : @"")];
- [hostField setStringValue:([self valueForKeyPath:@"selectedFavorite.host"] ? [self valueForKeyPath:@"selectedFavorite.host"] : @"")];
- [userField setStringValue:([self valueForKeyPath:@"selectedFavorite.user"] ? [self valueForKeyPath:@"selectedFavorite.user"] : @"")];
- [passwordField setStringValue:([self selectedFavoritePassword] ? [self selectedFavoritePassword] : @"")];
- [databaseField setStringValue:([self valueForKeyPath:@"selectedFavorite.database"] ? [self valueForKeyPath:@"selectedFavorite.database"] : @"")];
- [socketField setStringValue:([self valueForKeyPath:@"selectedFavorite.socket"] ? [self valueForKeyPath:@"selectedFavorite.socket"] : @"")];
- [portField setStringValue:([self valueForKeyPath:@"selectedFavorite.port"] ? [self valueForKeyPath:@"selectedFavorite.port"] : @"")];
+ if (connectionKeychainItemName) [connectionKeychainItemName release], connectionKeychainItemName = nil;
+ if (connectionKeychainItemAccount) [connectionKeychainItemAccount release], connectionKeychainItemAccount = nil;
+ if (connectionSSHKeychainItemName) [connectionSSHKeychainItemName release], connectionSSHKeychainItemName = nil;
+ if (connectionSSHKeychainItemAccount) [connectionSSHKeychainItemAccount release], connectionSSHKeychainItemAccount = nil;
+
+ [nameField setStringValue:([self valueForKeyPath:@"selectedFavorite.name"] ? [self valueForKeyPath:@"selectedFavorite.name"] : @"")];
+ [hostField setStringValue:([self valueForKeyPath:@"selectedFavorite.host"] ? [self valueForKeyPath:@"selectedFavorite.host"] : @"")];
+ [socketField setStringValue:([self valueForKeyPath:@"selectedFavorite.socket"] ? [self valueForKeyPath:@"selectedFavorite.socket"] : @"")];
+ [userField setStringValue:([self valueForKeyPath:@"selectedFavorite.user"] ? [self valueForKeyPath:@"selectedFavorite.user"] : @"")];
+ [portField setStringValue:([self valueForKeyPath:@"selectedFavorite.port"] ? [self valueForKeyPath:@"selectedFavorite.port"] : @"")];
+ [databaseField setStringValue:([self valueForKeyPath:@"selectedFavorite.database"] ? [self valueForKeyPath:@"selectedFavorite.database"] : @"")];
+ [sshCheckbox setState:([self valueForKeyPath:@"selectedFavorite.useSSH"] ? ([[self valueForKeyPath:@"selectedFavorite.useSSH"] boolValue]?NSOnState:NSOffState) : NSOffState)];
+ [self toggleUseSSH:self];
+ [sshHostField setStringValue:([self valueForKeyPath:@"selectedFavorite.sshHost"] ? [self valueForKeyPath:@"selectedFavorite.sshHost"] : @"")];
+ [sshUserField setStringValue:([self valueForKeyPath:@"selectedFavorite.sshUser"] ? [self valueForKeyPath:@"selectedFavorite.sshUser"] : @"")];
+ [sshPortField setStringValue:([self valueForKeyPath:@"selectedFavorite.sshPort"] ? [self valueForKeyPath:@"selectedFavorite.sshPort"] : @"")];
+
+ // 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 = [[NSString stringWithFormat:@"Sequel Pro : %@ (%i)", [self valueForKeyPath:@"selectedFavorite.name"], [[self valueForKeyPath:@"selectedFavorite.id"] intValue]] retain];
+ connectionKeychainItemAccount = [[NSString stringWithFormat:@"%@@%@/%@",
+ [self valueForKeyPath:@"selectedFavorite.user"],
+ [self valueForKeyPath:@"selectedFavorite.host"],
+ [self valueForKeyPath:@"selectedFavorite.database"]] retain];
+ if ([keyChainInstance passwordExistsForName:connectionKeychainItemName account:connectionKeychainItemAccount]) {
+ [passwordField setStringValue:[keyChainInstance getPasswordForName:connectionKeychainItemName account:connectionKeychainItemAccount]];
+ } else {
+ [connectionKeychainItemName release], connectionKeychainItemName = nil;
+ [connectionKeychainItemAccount release], connectionKeychainItemAccount = nil;
+ [passwordField setStringValue:@""];
+ }
+
+ // And the same for the SSH password
+ connectionSSHKeychainItemName = [[NSString stringWithFormat:@"Sequel Pro SSHTunnel : %@ (%i)", [self valueForKeyPath:@"selectedFavorite.name"], [[self valueForKeyPath:@"selectedFavorite.id"] intValue]] retain];
+ connectionSSHKeychainItemAccount = [[NSString stringWithFormat:@"%@@%@",
+ [self valueForKeyPath:@"selectedFavorite.sshUser"],
+ [self valueForKeyPath:@"selectedFavorite.sshHost"]] retain];
+ if ([keyChainInstance passwordExistsForName:connectionSSHKeychainItemName account:connectionSSHKeychainItemAccount]) {
+ [sshPasswordField setStringValue:[keyChainInstance getPasswordForName:connectionSSHKeychainItemName account:connectionSSHKeychainItemAccount]];
+ } else {
+ [connectionSSHKeychainItemName release], connectionSSHKeychainItemName = nil;
+ [connectionSSHKeychainItemAccount release], connectionSSHKeychainItemAccount = nil;
+ [sshPasswordField setStringValue:@""];
+ }
[prefs setInteger:[favoritesController selectionIndex] forKey:@"LastFavoriteIndex"];
}
/**
+ * Updates the interface when the "Use SSH Tunnel" checkbox is ticked/unticked
+ */
+- (IBAction)toggleUseSSH:(id)sender
+{
+ BOOL sshIsEnabledValue = ([sshCheckbox state] == NSOnState);
+ [sshHostField setEnabled:sshIsEnabledValue];
+ [sshUserField setEnabled:sshIsEnabledValue];
+ [sshPasswordField setEnabled:sshIsEnabledValue];
+ [sshPortField setEnabled:sshIsEnabledValue];
+
+ if (sender == sshCheckbox) [favoritesController setSelectionIndexes:[NSIndexSet indexSet]];
+}
+
+/**
* Opens the preferences window, or brings it to the front, and switch to the favorites tab.
* If a favorite is selected in the connection sheet, it is also select in the prefs window.
*/
@@ -448,23 +617,6 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
return [favoritesController selection];
}
-/**
- * fetches the password [self selectedFavorite] from the keychain, returns nil if no selection.
- */
-- (NSString *)selectedFavoritePassword
-{
- if (![self selectedFavorite])
- return nil;
-
- NSString *keychainName = [NSString stringWithFormat:@"Sequel Pro : %@ (%i)", [self valueForKeyPath:@"selectedFavorite.name"], [[self valueForKeyPath:@"selectedFavorite.id"] intValue]];
- NSString *keychainAccount = [NSString stringWithFormat:@"%@@%@/%@",
- [self valueForKeyPath:@"selectedFavorite.user"],
- [self valueForKeyPath:@"selectedFavorite.host"],
- [self valueForKeyPath:@"selectedFavorite.database"]];
-
- return [keyChainInstance getPasswordForName:keychainName account:keychainAccount];
-}
-
- (void)connectSheetAddToFavorites:(id)sender
{
[self addToFavoritesName:[nameField stringValue] host:[hostField stringValue] socket:[socketField stringValue] user:[userField stringValue] password:[passwordField stringValue] port:[portField stringValue] database:[databaseField stringValue] useSSH:false sshHost:@"" sshUser:@"" sshPassword:@"" sshPort:@""];
@@ -518,6 +670,15 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
{
if ([contextInfo isEqualToString:@"connect"]) {
[sheet orderOut:self];
+
+ // Restore the passwords from keychain for editing if appropriate
+ if (connectionKeychainItemName) {
+ [passwordField setStringValue:[keyChainInstance getPasswordForName:connectionKeychainItemName account:connectionKeychainItemAccount]];
+ }
+ if (connectionSSHKeychainItemName) {
+ [sshPasswordField setStringValue:[keyChainInstance getPasswordForName:connectionSSHKeychainItemName account:connectionSSHKeychainItemAccount]];
+ }
+
[self connectToDB:nil];
return;
}
@@ -2039,7 +2200,9 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
if ([aNotification object] == nameField || [aNotification object] == hostField
|| [aNotification object] == userField || [aNotification object] == passwordField
|| [aNotification object] == databaseField || [aNotification object] == socketField
- || [aNotification object] == portField) {
+ || [aNotification object] == portField || [aNotification object] == sshHostField
+ || [aNotification object] == sshUserField || [aNotification object] == sshPasswordField
+ || [aNotification object] == sshPortField) {
[favoritesController setSelectionIndexes:[NSIndexSet indexSet]];
}
else if ([aNotification object] == databaseNameField) {
@@ -2047,6 +2210,7 @@ NSString *TableDocumentFavoritesControllerSelectionIndexDidChange = @"TableDocum
}
}
+
#pragma mark SplitView delegate methods
/**
diff --git a/Source/TunnelPassphraseRequester.m b/Source/TunnelPassphraseRequester.m
new file mode 100644
index 00000000..a39c4fd1
--- /dev/null
+++ b/Source/TunnelPassphraseRequester.m
@@ -0,0 +1,96 @@
+//
+// TunnelPassphraseRequester.m
+// sequel-pro
+//
+// Created by Rowan Beentje on May 4, 2009.
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// More info at <http://code.google.com/p/sequel-pro/>
+
+#import <Cocoa/Cocoa.h>
+#import "KeyChain.h"
+#import "SPSSHTunnel.h"
+
+int main(int argc, const char *argv[])
+{
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ NSDictionary *environment = [[NSProcessInfo processInfo] environment];
+
+ if (![environment objectForKey:@"SP_PASSWORD_METHOD"]) {
+ [pool release];
+ return 1;
+ }
+
+ // If the password method is set to use the keychain, use the supplied keychain name to
+ // request the password
+ if ([[environment objectForKey:@"SP_PASSWORD_METHOD"] intValue] == SPSSH_PASSWORD_USES_KEYCHAIN) {
+ KeyChain *keychain;
+ NSString *keychainName = [environment objectForKey:@"SP_KEYCHAIN_ITEM_NAME"];
+ NSString *keychainAccount = [environment objectForKey:@"SP_KEYCHAIN_ITEM_ACCOUNT"];
+
+ if (!keychainName || !keychainAccount) {
+ NSLog(@"SSH Tunnel: keychain authentication specified but insufficient internal details supplied");
+ [pool release];
+ return 1;
+ }
+
+ keychain = [[KeyChain alloc] init];
+ if (![keychain passwordExistsForName:keychainName account:keychainAccount]) {
+ NSLog(@"SSH Tunnel: specified keychain password not found");
+ [pool release];
+ return 1;
+ }
+
+ printf("%s\n", [[keychain getPasswordForName:keychainName account:keychainAccount] UTF8String]);
+ [pool release];
+ return 0;
+ }
+
+ // If the password method is set to request the password from the tunnel instance, do so.
+ if ([[environment objectForKey:@"SP_PASSWORD_METHOD"] intValue] == SPSSH_PASSWORD_ASKS_UI) {
+ SPSSHTunnel *sequelProTunnel;
+ NSString *password;
+ NSString *connectionName = [environment objectForKey:@"SP_CONNECTION_NAME"];
+ NSString *verificationHash = [environment objectForKey:@"SP_CONNECTION_VERIFY_HASH"];
+
+ if (!connectionName || !verificationHash) {
+ NSLog(@"SSH Tunnel: internal authentication specified but insufficient details supplied");
+ [pool release];
+ return 1;
+ }
+
+ sequelProTunnel = (SPSSHTunnel *)[NSConnection rootProxyForConnectionWithRegisteredName:connectionName host:nil];
+ if (!sequelProTunnel) {
+ NSLog(@"SSH Tunnel: unable to connect to Sequel Pro for internal authentication");
+ [pool release];
+ return 1;
+ }
+
+ password = [sequelProTunnel getPasswordWithVerificationHash:verificationHash];
+ if (!password) {
+ NSLog(@"SSH Tunnel: unable to successfully request password from Sequel Pro for internal authentication");
+ [pool release];
+ return 1;
+ }
+
+ printf("%s\n", [password UTF8String]);
+ [pool release];
+ return 0;
+ }
+
+ [pool release];
+ return 1;
+} \ No newline at end of file