Apple now require all future apps to be sandboxed and so I followed the instructions to sandbox an app. The build succeeded but then my system(rm -rf ~/.Trash/*) command stopped working. Nothing happened. What I find confusing here is why this system command does not work with App Sandboxing/Entitlements on. Here is are my entitlement settings:
Entitlements: Checked
App Sandboxing: Checked
And here is my current code:
- (void)viewDidLoad {
[self emptyTrash];
}
- (void)emptyTrash {
system(rm -rf ~/.Trash/*);
}
Thanks for your help!
Take a look at documentation.
Mac OS X path-finding APIs, above the POSIX layer, return paths
relative to the container instead of relative to the user’s home
directory. If your app, before you sandbox it, accesses locations in
the user’s actual home directory (~) and you are using Cocoa or Core
Foundation APIs, then, after you enable sandboxing, your path-finding
code automatically uses your app’s container instead.
you can use
struct passwd *getpwuid(uid_t uid);
struct passwd {
char *pw_name; /* user name */
char *pw_passwd; /* encrypted password */
uid_t pw_uid; /* user uid */
gid_t pw_gid; /* user gid */
__darwin_time_t pw_change; /* password change time */
char *pw_class; /* user access class */
char *pw_gecos; /* Honeywell login info */
char *pw_dir; /* home directory */
char *pw_shell; /* default shell */
__darwin_time_t pw_expire; /* account expiration */
}
#include <pwd.h>
#include <sys/types.h>
char *HomeDirectory = getpwuid(getuid())->pw_dir;
NSLog(#"%s", HomeDirectory);
system([[NSString stringWithFormat:#"rm -rf %s/.Trash/",HomeDirectory] UTF8String]);
Related
I am using libwebsockets library. This exposes certain methods for writing into a log file.
lwsl_warn(...), lwsl_err(...) and lwsl_err(...)
to name the most common.
The output is color coded using ANSI sequences.
Is there a way to set the default color scheme (other than recompiling the library)?
Thanks.
I poked around in the libwebsockets source and found my answer:
The colors are hard coded - so the answer to my original question is "no".
However, the color scheme is not hard to find and edit. It resides in two source files - one of these is compiled depending on options:
libwebsockets/lib/core/logs.c
and
libwebsockets/lib/plat/optee/lws-plat-optee.c
All it takes is to edit the self-explanatory table:
static const char * const colours[] = {
"[31;1m", /* LLL_ERR */
"[36;1m", /* LLL_WARN */
"[35;1m", /* LLL_NOTICE */
"[32;1m", /* LLL_INFO */
"[34;1m", /* LLL_DEBUG */
"[33;1m", /* LLL_PARSER */
"[33m", /* LLL_HEADER */
"[33m", /* LLL_EXT */
"[33m", /* LLL_CLIENT */
"[33;1m", /* LLL_LATENCY */
"[0;1m", /* LLL_USER */
"[31m", /* LLL_THREAD */
};
Then build as before. Once in the libwebsockets/build directory do the following:
make clean
make && sudo make install
sudo ldconfig
... and enjoy!
I'm writing a console app that requests a password and I'd like to use the same symbol as the macOS ssh command, but it doesn't show up in the Character Viewer (⌘⌃Space) under the word KEY. The closest is 🔑or 🗝. Seems to be Mac specific as I don't see it in the source code for OpenSSH. Anyone know to produce this symbol?
That's not a character, it's the insertion point (the text cursor), and it's drawn by the terminal app, not ssh. It looks like you're using iTerm; if you run this in Terminal, you'll see that it displays a different icon. The key icon you're looking for is in iTerm's Resources folder (key.tiff).
The key cursor gets enabled whenever ECHO is turned off on the terminal. For example, in C:
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
int main (){
struct termios termInfo, save;
// Fetch the current attributes
if (tcgetattr(STDIN_FILENO, &termInfo) == -1) {
perror("tcgetattr");
exit(1);
}
save = termInfo;
// turn off ECHO, and ECHONL on
termInfo.c_lflag &= ~ECHO;
termInfo.c_lflag |= ECHONL; // echo newline even if echo is off
// Set it
tcsetattr(STDIN_FILENO, TCSASOFT|TCSADRAIN, &termInfo);
printf("Password: ");
// Consume characters until the user presses enter
while (fgetc(stdin) != '\n') {}
printf("Accepted\n");
// Set it back to the original values
tcsetattr(STDIN_FILENO, TCSASOFT|TCSADRAIN, &save);
}
This will display the key icon you're looking for.
I have a really basic little command line app that grabs the mouse coordinates the next time the mouse is clicked.
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
CGFloat displayScale = 1.0f;
if ([[NSScreen mainScreen] respondsToSelector:#selector(backingScaleFactor)])
{
displayScale = [NSScreen mainScreen].backingScaleFactor;
}
CGPoint loc = CGEventGetLocation(event);
CFRelease(event);
printf("%dx%d\n", (int)roundf(loc.x * displayScale), (int)roundf(loc.y * displayScale) );
exit(0);
return event;
}
int main(int argc, const char * argv[]) {
#autoreleasepool {
CFMachPortRef eventTap;
CGEventMask eventMask;
CFRunLoopSourceRef runLoopSource;
eventMask = 1 << kCGEventLeftMouseDown;
eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap,
1, eventMask, myCGEventCallback, #"mydata");
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRunLoopRun();
}
return 0;
}
I'm building it with cmake with the following file:
cmake_minimum_required(VERSION 3.0.0)
project (location)
set(CMAKE_C_FLAGS "-arch x86_64 -mmacosx-version-min=10.12 -std=gnu11 -fobjc-arc -fmodules")
This all worked fine until the upgrade to Mojave.
A bit of poking around shows this is down to the latest set of security updates and some hints (except CGEventTapCreate() is not returning null) about settings some values in Info.plist to allow the app to use the accessibility API. But I'm struggling to work out where to put it as I just have a single .m file with the code.
Edit
This needs to run as a none root user (company policy)
if the only way to get it to ask for permission then it can be extended to be a "GUI" app with a minimal UI
This app is just to grab the upper left hand corner of a region of the screen to feed to a second app that streams that area of screen to a second device. The code for the streamer is common across Win/Linux/MacOS so trying to keep the screen coordinate collection totally separate
As you surmise, event taps won't work on Mojave without having accessibility access. From the documentation:
Event taps receive key up and key down events if one of the following
conditions is true: The current process is running as the root user.
Access for assistive devices is enabled. In OS X v10.4, you can enable
this feature using System Preferences, Universal Access panel,
Keyboard view.
A GUI app will prompt the user to enable accessibility the first time it's needed, but it looks like a CLI app doesn't do that (which makes sense).
There is no way to enable this programatically or through a script; the user must do it themselves.
Running your tool as root should work - can you enforce that?
Otherwise, you can direct the user to the correct place in System Preferences:
tell application "System Preferences"
reveal anchor "Privacy_Accessibility" of pane id "com.apple.preference.security"
activate
end tell
It may be possible using Carbon, if your app isn't sandboxed.
Finally, a quick test shows this is at least possible using IOHID. I shameless borrowed the KeyboardWatcher class from this answer. Then, modified the device type:
[self watchDevicesOfType:kHIDUsage_GD_Keyboard];
into:
[self watchDevicesOfType:kHIDUsage_GD_Mouse];
Finally, my callback looks like this:
static void Handle_DeviceEventCallback (void *inContext, IOReturn inResult, void *inSender, IOHIDValueRef value)
{
IOHIDElementRef element = IOHIDValueGetElement(value);
IOHIDElementType elemType = IOHIDElementGetType(element);
if (elemType == kIOHIDElementTypeInput_Button)
{
int elementValue = (int) IOHIDValueGetIntegerValue(value);
// 1 == down 0 == up
if (elementValue == 1)
{
CGEventRef ourEvent = CGEventCreate(NULL);
CGPoint point = CGEventGetLocation(ourEvent);
printf("Mouse Position: %.2f, y = %.2f \n", (float) point.x, (float) point.y);
}
}
}
That is really a quick hack job, but it demonstrates this is possible and hopefully you can refine it to your needs.
I've found the CGEventTap documentation is out of date beginning with Mojave. Running as root used to act as a bypass for certain entitlements, but in Mojave this was tightened down. One bizarre side effect, as you noticed, is that root can still acquire the mach port for the tap; its just that no events can be read from it. If you try your application without running as root you should get the expected popup asking for permission.
If you do not get the popup, or need to run as root for other purposes, you can manually add your application to the trusted TCC database via SystemPreferences -> Security & Privacy -> Privacy -> Accessibility
settings some values in Info.plist to allow the app to use the accessibility API
I believe you mean adding entitlements (which are also a plist). The entitlement that allows an application to use the Accessibility API is the com.apple.private.tcc.allow entitlement (with a value of kTCCServiceAccessibility). As you can probably guess from the name it is only allowed on Apple signed binaries.
You can add these entitlements to your own app if you disable System Integrity Protection (SIP) and boot the kernel with the option amfi_get_out_of_my_way=1, but I wouldn't recommend it (and certainly any customers of yours wouldn't want to). With just SIP disabled you could manually add an entry to the TCC database to grant privileges, but still wouldn't recommend it.
Possible Alternative
You can use an event monitor:
NSEventMask mask = (NSLeftMouseDownMask | NSRightMouseDownMask | NSOtherMouseDownMask);
mouseEventMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask: mask
handler:^(NSEvent *event){
// get the current coordinates with this
NSPoint coords = [NSEvent mouseLocation];
// event cooordinates would be event.absoluteX and event.absoluteY
... do stuff
}];
The documentation does mention:
Key-related events may only be monitored if accessibility is enabled or if your application is trusted for accessibility access (see AXIsProcessTrusted).
But I don't think that applies to mouse events.
Is it possible to replace the Mac OS X login window, /System/Library/CoreServices/loginwindow.app, with a custom login window application? (See my rational for doing so.)
I'm afraid my Cocoa programming skills are rudimentary. I do find it interesting that, when I run probe CGSession (which is a undocumented utility that performs fast user switching) to see what functions it uses, by doing
nm -mg /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession
that one of the linked function is:
(undefined [lazy bound]) external _CGSCreateLoginSession (from ApplicationServices)
I haven't found documentation on the ApplicationServices framework. I suspect I'm getting deep into Service Provider Interfaces instead of Application Programmer Interfaces.
I did find this really interesting snippet: (google cache) (direct link to down page; it appears the site is undergoing re-organization) from an application that claims to switch to the login window even if fast user switching is disabled.
#include "CGSInternal.h"
int main (int argc, const char * argv[]) {
// switch to the login window
CGSCreateLoginSession(NULL);
return 0;
}
I take CG to mean CoreGraphics, and don't understand what that has to do with logging in (except with perhaps putting a login dialog up over the current user's work).
Even if it is not possible to achieve a replacement for the login window, I'd be interested to know what can be done along these lines (by people who don't work for Apple).
The login window application is defined as part of the launchd configuration in /System/Library/LaunchDaemons/com.apple.loginwindow.plist.
In theory you can replace the login window with your own but I don't know what you have to do in the new app - I think the login window does a bit more then authentication and setting up the user session -> amongst others, it looks like its doing some launchd related chores.
I've compiled an application that calls CGSCreateLoginSession and once you run it it transitions to the login window via the rotating cube. I imagine this is why it requires CoreGraphics - it's just a graphics function that calls logout at the end.
You could try an InputManager and see it the login window loads the code -> if it does, you could then alter the loginwindow NIB (LoginWindowUI.nib) and add some buttons to display a new window with the user browser. Once the student chooses a picture of him/herself you could autofill the username and password fields in the loginwindow.
Node this is all theory, and it looks very fragile and unsafe.
Good luck.
Later edit
Please note this is very unsafe so use with care - I did hose my system a couple of times when trying out this stuff
Here's a proof-of-concept implementation that injects code in the loginwindow.
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <strings.h>
#include <syslog.h>
#import <Cocoa/Cocoa.h>
#include <execinfo.h>
#interface LLApp:NSApplication
#end
#implementation LLApp
- (void)run
{
syslog(LOG_ERR, "LLApp being run");
[super run];
}
#end
void my_openlog(const char *ident, int logopt, int facility);
typedef struct interpose_s
{
void * new_func;
void * orig_func;
} interpose_t;
int MyNSApplicationMain(int argc, const char ** argv);
static const interpose_t interposers[] __attribute__ ((section("__DATA, __interpose"))) = {
{ (void *) my_openlog, (void *) openlog },
};
void my_openlog(const char *ident, int logopt, int facility)
{
openlog(ident, logopt, facility);
if(!strcmp(ident, "/System/Library/CoreServices/loginwindow.app/Contents/MacOS/loginwindow"))
{
[LLApp poseAsClass:[NSApplication class]];
}
else
{
syslog(LOG_ERR, "Ignoring unknown indent: >%s<", ident);
}
return;
}
The code compiles with:
gcc -Wall -dynamiclib -undefined dynamic_lookup -o ~/Desktop/libinterposers.dylib testin.m -framework Cocoa
Code loading is based on interposing so the launchd definition of loginwindow has to contain an additional entry (to enable interposing in the dynamic linker), i.e.:
<key>EnvironmentVariables</key>
<dict>
<key>DYLD_INSERT_LIBRARIES</key>
<string>path_to/Desktop/libinterposers.dylib</string>
</dict>
yes, you can use the SFAuthorizationPluginView
here the reference link at ADC
I'm trying to find documented (or, undocumented, if that's my only option) APIs on OS X to query a list of windows from the window server and then cause the windows to move and resize. Can anyone point me in the right direction? I guess I'd be starting with something like FindWindowEx and MoveWindow under Win32.
Note that I want to do this from an external process - I'm not asking how to control just my own app's window size and position.
Use the Accessibility API. Using this API you can connect to a process, obtain a list of windows (actually an array), get the positions and sizes of each window and also change window properties if you like.
However, an application can only be using this API if the user has enabled access for assistive devices in his preferences (System Prefs -> Universal Access), in which case all applications may use this API, or if your application is a trusted assitive application (when it is trusted, it may use the API, even if this option is not checked). The Accessibility API itself offers the necessary functions to make your application trusted - basically you must become root (using security services to request root permissions of the user) and then mark your process as trusted. Once your application has been marked trusted, it must be restarted as the trusted state is only checked on start-up and can't change while the app is running. The trust state is permanent, unless the user moves the application somewhere else or the hash of the application binary changes (e.g. after an update). If the user has assistive devices enabled in his prefs, all applications are treated as if they were trusted. Usually your app would check if this option is enabled, if it is, go on and do your stuff. If not, it would check if it is already trusted, if it is, again just do your stuff. If not try to make itself trusted and then restart the application unless the user declined root authorization. The API offers all necessary functions to check all this.
There exist private functions to do the same using the Mac OS window manager, but the only advantage that would buy you is that you don't need to be a trusted Accessibility application (which is a one time operation on first launch in most cases). The disadvantages are that this API may change any time (it has already changed in the past), it's all undocumented and functions are only known through reverse engineering. The Accessibility however is public, it is documented and it hasn't change much since the first OS X version that introduced it (some new functions were added in 10.4 and again in 10.5, but not much else has changed).
Here's a code example. It will wait 5 seconds, so you can switch to a different window before it does anything else (otherwise it will always work with the terminal window, rather boring for testing). Then it will get the front most process, the front most window of this process, print it's position and size and finally move it by 25 pixels to the right. You compile it on command line like that (assuming it is named test.c)
gcc -framework Carbon -o test test.c
Please note that I do not perform any error checking in the code for simplicity (there are various places that could cause the program to crash if something goes wrong and certain things may/can go wrong). Here's the code:
/* Carbon includes everything necessary for Accessibilty API */
#include <Carbon/Carbon.h>
static bool amIAuthorized ()
{
if (AXAPIEnabled() != 0) {
/* Yehaa, all apps are authorized */
return true;
}
/* Bummer, it's not activated, maybe we are trusted */
if (AXIsProcessTrusted() != 0) {
/* Good news, we are already trusted */
return true;
}
/* Crap, we are not trusted...
* correct behavior would now be to become a root process using
* authorization services and then call AXMakeProcessTrusted() to make
* ourselves trusted, then restart... I'll skip this here for
* simplicity.
*/
return false;
}
static AXUIElementRef getFrontMostApp ()
{
pid_t pid;
ProcessSerialNumber psn;
GetFrontProcess(&psn);
GetProcessPID(&psn, &pid);
return AXUIElementCreateApplication(pid);
}
int main (
int argc,
char ** argv
) {
int i;
AXValueRef temp;
CGSize windowSize;
CGPoint windowPosition;
CFStringRef windowTitle;
AXUIElementRef frontMostApp;
AXUIElementRef frontMostWindow;
if (!amIAuthorized()) {
printf("Can't use accessibility API!\n");
return 1;
}
/* Give the user 5 seconds to switch to another window, otherwise
* only the terminal window will be used
*/
for (i = 0; i < 5; i++) {
sleep(1);
printf("%d", i + 1);
if (i < 4) {
printf("...");
fflush(stdout);
} else {
printf("\n");
}
}
/* Here we go. Find out which process is front-most */
frontMostApp = getFrontMostApp();
/* Get the front most window. We could also get an array of all windows
* of this process and ask each window if it is front most, but that is
* quite inefficient if we only need the front most window.
*/
AXUIElementCopyAttributeValue(
frontMostApp, kAXFocusedWindowAttribute, (CFTypeRef *)&frontMostWindow
);
/* Get the title of the window */
AXUIElementCopyAttributeValue(
frontMostWindow, kAXTitleAttribute, (CFTypeRef *)&windowTitle
);
/* Get the window size and position */
AXUIElementCopyAttributeValue(
frontMostWindow, kAXSizeAttribute, (CFTypeRef *)&temp
);
AXValueGetValue(temp, kAXValueCGSizeType, &windowSize);
CFRelease(temp);
AXUIElementCopyAttributeValue(
frontMostWindow, kAXPositionAttribute, (CFTypeRef *)&temp
);
AXValueGetValue(temp, kAXValueCGPointType, &windowPosition);
CFRelease(temp);
/* Print everything */
printf("\n");
CFShow(windowTitle);
printf(
"Window is at (%f, %f) and has dimension of (%f, %f)\n",
windowPosition.x,
windowPosition.y,
windowSize.width,
windowSize.height
);
/* Move the window to the right by 25 pixels */
windowPosition.x += 25;
temp = AXValueCreate(kAXValueCGPointType, &windowPosition);
AXUIElementSetAttributeValue(frontMostWindow, kAXPositionAttribute, temp);
CFRelease(temp);
/* Clean up */
CFRelease(frontMostWindow);
CFRelease(frontMostApp);
return 0;
}
Sine Ben asked how you get a list of all windows in the comments, here's how:
Instead of kAXFocusedWindowAttribute you use kAXWindowsAttribute for the AXUIElementCopyAttributeValue function. The result is then no AXUIElementRef, but a CFArray of AXUIElementRef elements, one for each window of this application.
I agree that Accessibility is the best way forward. But if you want quick-and-dirty, AppleScript will work as well.