In my Cocoa application I'm trying to use NSTask to run some basic Git commands. Whenever I run a command that requires permissions (SSH keys) to access a remote (e.g. git push, git pull), it fails with the following error:
Permission denied (publickey). The remote end hung up unexpectedly
Running the same commands from Terminal works just fine, so I'm thinking that this might be an issue with NSTask not setting an environment variable that would be used somewhere in the process of accessing the ssh keys. I tried manually setting the HOME and USER environment variables like this:
[task setEnvironment:[NSDictionary dictionaryWithObjectsAndKeys:NSHomeDirectory(), #"HOME", NSUserName(), #"USER", nil]];
But this has no effect. Is there any particular environment variable I have to set in NSTask for this to work properly?
EDIT: Thanks to Dustin's tip, I got a little bit further in figuring this out. I used the env command to list the environment variables for my current session and I found this:
SSH_AUTH_SOCK=/tmp/launch-DMQopt/Listeners
To test, I copied that path and set it as an environment variable of NSTask and ran the code again, and this time it worked! That said, I'm certain that SSH_AUTH_SOCK changes for each session so I can't just hardcode it. How do I dynamically generate/retrieve this variable?
You could try and follow the tutorial "Wrapping rsync or SSH in an NSTask" (from Ira), which does mention SSH_AUTH_SOCK variable:
Since writing this post I've realised that I omitted an important additional step in setting up the environment variables for the NSTask.
In order to make passwordless key-based authentication work it's necessary to grab the SSH_AUTH_SOCK variable from the user's environment and include this in the NSTask's environment.
So, when setting environment variables for example;
NSTask *task;
NSDictionary *environmentDict = [[NSProcessInfo processInfo] environment];
// Environment variables needed for password based authentication
NSMutableDictionary *env = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"NONE", #"DISPLAY", askPassPath, #"SSH_ASKPASS",
userName,#"AUTH_USERNAME",
hostName,#"AUTH_HOSTNAME",
nil];
// Environment variable needed for key based authentication
[env setObject:[environmentDict objectForKey:#"SSH_AUTH_SOCK"] forKey:#"SSH_AUTH_SOCK"];
// Setting the task's environment
[task setEnvironment:env];
However, the OP indragie comments:
I had tried this earlier but since it was being invoked with XCode, the SSH_AUTH_SOCK env var. wasn't being passed to it.
Opening the app from Finder corrects this issue.
With askPassPath being the path for the Askpass executable, which is included as part of the application’s main bundle. (In order to do this, find the executable under “Products” in xcode, and then drag it into “Copy Bundle Resources” on the main application’s target.)
// Get the path of the Askpass program, which is
// setup to be included as part of the main application bundle
NSString *askPassPath = [NSBundle pathForResource:#"Askpass"
ofType:#""
inDirectory:[[NSBundle mainBundle] bundlePath]];
Related
I am integrating FinderSync Extension in my Cocoa Application to show badges in files and folders. Look at the below two scenario:
When i run application using FinderSync Extension (like DemoFinderSync) look at the blue popup in the below image, in that case Extension is added in the System Preference with Check mark and called that principal class "FinderSync.m" as well.
When i run application using my Application Scheme (like DemoApp) look at the blue popup in the below image, in that case Extension is added in the System Preference but without check mark and that principal class "FinderSync.m" do not call and FinderSync Extension does not work in this case.
Does anybody have an idea how to enable Finder Extension in the System Preference using second scenario?
Non-debug scheme (#if !DEBUG):
system("pluginkit -e use -i com.domain.my-finder-extension");
When running under debugger give path to your extension directly:
NSString *pluginPath = [[[NSBundle mainBundle] builtInPlugInsPath] stringByAppendingPathComponent:#"My Finder Extension.appex"];
NSString *pluginkitString = [NSString stringWithFormat:#"pluginkit -e use -a \"%#\"", pluginPath];
system([pluginkitString cStringUsingEncoding:NSUTF8StringEncoding]);
Specify this in your applicationDidFinishLaunching method. You should also manually turn this on only once so that if user turned your extension off in the System Preferences you don't turn it on every time your application starts. I set an NSUserDefaults key the first time user launches my app that has the finder sync extension support.
I got the solution:
Code to Enable Extension (bundle ID)
system("pluginkit -e use -i YourAppBundleID")
Code to Disable Extension (bundle ID)
system("pluginkit -e ignore -i YourAppBundleID")
Before i used:
system("pluginkit -e use -i AppBundleID.FinderSync")
so just remove ".FinderSync" its working.
Linking an answer I found on the Apple developer forum:
https://forums.developer.apple.com/thread/77682
When your App is outside the Sandbox, you can use:
Objective-C:
system("pluginkit -e use -i <yourFinderExtensionBundleID>");
Swift:
let pipe = Pipe()
let task = Process()
task.launchPath = "/usr/bin/pluginkit"
task.arguments = ["-e", "use", "-i", "<yourFinderExtensionBundleID>"]
task.standardOutput = pipe
let file = pipe.fileHandleForReading
task.launch()
let result = NSString(data: file.readDataToEndOfFile(), encoding:
I am working on MAC Application in which I want to Remove Helper tool previously installed by my application.
I am using STPrivilegedTask to run my ShellScript.
Here is the code I am using to achieve this.
NSString *pathForUninstallFile = [[NSBundle mainBundle] pathForResource:#"Uninstall" ofType:#"sh"];
STPrivilegedTask *taskToRemoveHelperTool = [STPrivilegedTask launchedPrivilegedTaskWithLaunchPath:pathForUninstallFile arguments:[NSArray arrayWithObjects:#"Uninstall.sh", nil]];
and here is my ShellScript Unistall.sh
launchctl unload /Library/LaunchDaemons/com.bsecure.HelperTool.plist
rm /Library/LaunchDaemons/com.appleCompany.HelperTool.plist
rm /Library/PrivilegedHelperTools/com.appleCompany.HelperTool
security -q authorizationdb remove "com.appleCompany.readLicenseKey"
security -q authorizationdb remove "com.appleCompany.newMethod"
Now the above code works perfect but it ask user's Authorization Popup.
I want to run this script without this Authorization Popup.
I already search in another question but none of them work for me that's why I created this question.
So you want to run a task with escalated privileges without prompting the user for a password? If so, you're out of luck, it can't be done.
OK, I must be missing something very simple but here's what:
If I echo $PATH in the terminal, I'm getting /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/drkameleon which is correct
Now if I run an NSTask and try executing a simple bash script (/usr/bin/env bash myscript.sh) to echo $PATH, it prints /Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin
(I've even tried with getenv, or print the entire [[NSProcessInfo processInfo] environment] dictionary, but the PATH variable is simply... wrong)
What's going on? How can I have access to the real $PATH as seen in the terminal?
When executing a command via NSTask, not your bash, zshell or whatever kind of shell you are using, is started. Hence the PATH (and other environment variables) are different from your environment variables when echoing them in the terminal.
Reason: NSTask uses fork() and exec() for command execution.
IMHO, there are two possible solutions for the problem.
1. You could set the wanted PATH via the setEnvironment:method of NSTask
Here is some untested example code, which should do the trick:
NSTask *task = //Configure your task
NSDictionary* env = [task environment];
NSString* currentPATH = env["PATH"];
NSString* yourPathExtension = #"/your/path";
env["PATH"] = (currentPATH != nil) ? [yourPath stringByAppendingFormat:#":%#", currentPATH] : yourPathExtension;
[task setEnvironment:env];
This adds :<old-PATH> after the current PATH from NSTask.
2. You could start /bin/bash within NSTask
task setLaunchPath:#"/bin/bash"];
NSArray *args = [NSArray arrayWithObjects:#"-l",
#"-c",
#"<your command here>",
nil];
[task setArguments: args];
This task will start /bin/bash with the PATH configured via ~/.bashrc etc. and execute the command within the bash.
Pro: Your command has all the usual environment variables of your bash
Con: You rely on the users PATH variable which can be quite different from yours which may lead to unexpected behavior.
Which solution is the best one for you depends on your use case. In your provided example, both approaches should work fine.
In general, according to the NSTask and NSProcessInfo documentation, the environment variables are equal to the variables of the process from which the application has been started. Hence you might solve your problem when starting your application from the bash.
I am getting the list of running applications in Cocoa with the following code:
for (NSRunningApplication *app in [[NSWorkspace sharedWorkspace] runningApplications]) {
MNSLog(#"%#",[app localizedName]);
}
However an application I started from a terminal session is not appearing in the list ('Terminal' is well appearing). The application was started from the same user which is executing the cocoa code.Is my launched application under Terminal ? And in such a case how can I find its name and arguments ?Running ps in another terminal session show my process properly.
Use an NSTask to execute the ps Shell command. You can check the ps man page to determine which arguments you want to pass it based on the information you want to get back. Use NSPipe and NSFileHandle to get the results from the task.
If you want to do some filtering you can pipe the ps output through grep before your app picks up the result.
For your first question, I think NSWorkspace can only see apps that use the window server so you will only see Terminal, not the executables that it is running internally.
You can use sysctl or ps command to get a list of all BSD processes. Have look at unable to detect application running with another user
My app uses NSTask to execute shell scripts, one of those scripts launches an X11 app (specifically meld).
I would have expected this to work:
#!/bin/bash
source ~/.profile # setup $PATH/etc
meld .
But it fails with:
gtk.icon_theme_get_default().append_search_path(meld.paths.icon_dir())
Traceback (most recent call last):
File "/usr/local/bin/meld", line 132, in <module>
gtk.icon_theme_get_default().append_search_path(meld.paths.icon_dir())
AttributeError: 'NoneType' object has no attribute 'append_search_path'
As a proof of concept I changed the script to this, which works perfectly:
#!/usr/bin/ruby
exec 'osascript -e \'tell app "Terminal" to do script "meld ' + Dir.pwd + '" in front window\''
Does anyone what is causing the problem? Here is my code for executing the shell script:
NSTask *task = [[NSTask alloc] init];
task.launchPath = self.scriptURL.path;
task.standardOutput = [NSPipe pipe];
task.currentDirectoryPath = workingDirectoryURL.path;
[task launch];
X11 apps learn the display server's address using the DISPLAY environment variable.
On OS X, the DISPLAY value is randomized for security reasons, so you can't hard-code it, as you noticed. Instead, there is a launchd agent that tells launchd to set DISPLAY when it starts a process.
Somewhere between launchd and meld, the value of DISPLAY is being dropped or overwritten. Your job is to find out where.
Make sure the launchd agent is running. Run launchctl list and look for org.macosforge.xquartz.startx. Since meld is working from Terminal.app this part is probably correct.
Make sure DISPLAY is set in your app. It should be listed in [NSProcessInfo processInfo].environment.
Make sure DISPLAY is set in the NSTask you launch. Try running /usr/bin/env with an NSTask, and make sure DISPLAY appears in its output.
Make sure DISPLAY is set inside the script you run. Try echo $DISPLAY before and after sourcing ~/.profile. (Sometimes the .profile itself overwrites DISPLAY to an incorrect value because that's sometimes the right thing to do on other operating systems.)
EDIT: this is the code I used to copy DISPLAY from my GUI app to the shell script:
NSTask *task = ...
task.environment = [NSProcessInfo processInfo].environment;
[task.launch];
Change your script to spew the environment variables and compare "working" to "not-working".
There are subtle differences between how shells are initialized across the different execution models. Almost assuredly, the environment is the source of your issues.
Take a look at man launchctl
launchctl submit ... -p /usr/local/bin/meld -- .
to have launchd launch the job; that will set certain environment variables for you that are part of the per-user session.