Skip to content

Commit

Permalink
Reformatted source code; minor refactorings
Browse files Browse the repository at this point in the history
  • Loading branch information
hschmidt committed Jan 7, 2017
1 parent 3f67486 commit 587806b
Show file tree
Hide file tree
Showing 19 changed files with 176 additions and 153 deletions.
32 changes: 16 additions & 16 deletions EnvAgent/EnvAgent.m
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@
#import "Environment.h"
#import "Constants.h"

int main( int argc, const char** argv )
int main( int argc, const char **argv )
{
NSLog( @"Started agent %s (%u)", argv[0], getpid() );
NSLog( @"Started agent %s (%u)", argv[ 0 ], getpid() );

NSError* error = nil;
NSFileManager* fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];

/*
* Read current agent configuration.
*/
NSURL* libraryUrl = [fileManager URLForDirectory: NSLibraryDirectory
NSURL *libraryUrl = [fileManager URLForDirectory: NSLibraryDirectory
inDomain: NSUserDomainMask
appropriateForURL: nil
create: NO
Expand All @@ -42,33 +42,33 @@ int main( int argc, const char** argv )
return 1;
};

NSURL* agentConfsUrl = [libraryUrl URLByAppendingPathComponent: @"LaunchAgents"
NSURL *agentConfsUrl = [libraryUrl URLByAppendingPathComponent: @"LaunchAgents"
isDirectory: YES];

NSString* agentConfName = [agentLabel stringByAppendingString: @".plist"];
NSString *agentConfName = [agentLabel stringByAppendingString: @".plist"];

NSURL* agentConfUrl = [agentConfsUrl URLByAppendingPathComponent: agentConfName];
NSURL *agentConfUrl = [agentConfsUrl URLByAppendingPathComponent: agentConfName];

NSDictionary* curAgentConf = [NSDictionary dictionaryWithContentsOfURL: agentConfUrl];
NSDictionary *curAgentConf = [NSDictionary dictionaryWithContentsOfURL: agentConfUrl];

/*
* As per convention, the path to the preference pane is the first entry in
* WatchPaths. Normally, the preference pane bundle still exists and we
* simply export the environment. Otherwise, we uninstall the agent by
* removing the files created outside the bundle during installation.
*/
NSString* envPanePath = curAgentConf[ @"WatchPaths" ][0];
NSString *envPanePath = curAgentConf[ @"WatchPaths" ][ 0 ];
BOOL isDir;
if( [fileManager fileExistsAtPath: envPanePath isDirectory: &isDir] && isDir ) {
NSLog( @"Setting environment" );
Environment* environment = [Environment loadPlist];
Environment *environment = [Environment loadPlist];
[environment export];
} else {
NSLog( @"Uninstalling agent" );
/*
* Remove agent binary
*/
NSString* agentExecutablePath = curAgentConf[ @"ProgramArguments" ][0];
NSString *agentExecutablePath = curAgentConf[ @"ProgramArguments" ][ 0 ];
if( ![fileManager removeItemAtPath: agentExecutablePath error: &error] ) {
NSLog( @"Failed to remove agent executable (%@): %@", agentExecutablePath, error );
}
Expand All @@ -81,7 +81,7 @@ int main( int argc, const char** argv )
/*
* ... and its parent directory.
*/
NSString* envAgentAppSupport = [agentExecutablePath stringByDeletingLastPathComponent];
NSString *envAgentAppSupport = [agentExecutablePath stringByDeletingLastPathComponent];
if( ![fileManager removeItemAtPath: envAgentAppSupport error: &error] ) {
NSLog( @"Failed to remove agent configuration (%@): %@", agentConfUrl, error );
}
Expand All @@ -91,7 +91,7 @@ int main( int argc, const char** argv )
* be terminated and it works without the presence of agent executable
* or plist.
*/
NSTask* task = [NSTask launchedTaskWithLaunchPath: launchctlPath
NSTask *task = [NSTask launchedTaskWithLaunchPath: launchctlPath
arguments: @[ @"remove", agentLabel ]];
[task waitUntilExit];
if( [task terminationStatus] != 0 ) {
Expand All @@ -101,7 +101,7 @@ int main( int argc, const char** argv )
// Work around weird issue with launchd starting the agent a second time if it finishes within
// 10 seconds, the default ThrottleInterval. We reduce the ThrottleInterval to 1s in the plist
// and wait a little longer here to avoid hitting that condition.
[NSThread sleepForTimeInterval:1.1];
NSLog( @"Exiting agent %s (PID %u)", argv[0], getpid() );
[NSThread sleepForTimeInterval: 1.1];
NSLog( @"Exiting agent %s (PID %u)", argv[ 0 ], getpid() );
return 0;
}
21 changes: 11 additions & 10 deletions EnvLib/Environment.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,21 @@

#import <Foundation/Foundation.h>

@interface Environment : NSObject {
@private
NSDictionary* _dict;
@interface Environment: NSObject
{
@private
NSDictionary *_dict;
}

/**
* Returns the path of the file that contains the persistent environment.
*/
+ ( NSString* ) savedEnvironmentPath;
+ (NSString *) savedEnvironmentPath;

/**
* Returns environment with the variables from ~/.MacOSX/environment.plist.
*/
+ ( Environment* ) loadPlist;
+ (Environment *) loadPlist;

/**
* Initialize an environment with a copy of the given dictionary.
Expand All @@ -42,28 +43,28 @@
* of the environment variable (using the key 'name'), and one for its value
* (using the key 'value'.
*/
+ ( Environment* ) withArrayOfEntries: ( NSArray* ) array;
+ (Environment *) withArrayOfEntries: (NSArray *) array;

/**
* Saves the environment variables to ~/.MacOSX/environment.plist.
*/
- (BOOL) savePlist: (NSError**) error;
- (BOOL) savePlist: (NSError **) error;

/**
* Returns an array of the form expected by withArrayOfEntries: containing the
* receivers environment variables.
*/
- ( NSMutableArray* ) toArrayOfEntries;
- (NSMutableArray *) toArrayOfEntries;

/**
* Exports the receiver's environment variables to the current user session.
*/
- ( void ) export;
- (void) export;

/**
* Returns YES if the receiver contains the same variables as the argument,
* checking both the name and the value of each variable.
*/
- ( BOOL ) isEqualToEnvironment: ( Environment* ) other;
- (BOOL) isEqualToEnvironment: (Environment *) other;

@end
19 changes: 10 additions & 9 deletions EnvLib/Environment.m
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,23 @@

@implementation Environment

static NSString* savedEnvironmentPath;
static NSString *savedEnvironmentPath;

+ (void) initialize
{
savedEnvironmentPath = [@"~/.MacOSX/environment.plist" stringByExpandingTildeInPath];
}

+ (NSString*) savedEnvironmentPath
+ (NSString *) savedEnvironmentPath
{
return savedEnvironmentPath;
}

/**
* Designated initializer
*/
- initWithDictionary: (NSDictionary*) dict {
- initWithDictionary: (NSDictionary *) dict
{
if( self = [super init] ) {
_dict = dict;
}
Expand Down Expand Up @@ -70,7 +71,7 @@ + (Environment *) loadPlist
return [self withDictionary: mutDict];
}

- (BOOL) savePlist: (NSError**) error
- (BOOL) savePlist: (NSError **) error
{
NSLog( @"Saving environment to %@", savedEnvironmentPath );
return [_dict writeToFile: savedEnvironmentPath
Expand All @@ -80,12 +81,12 @@ - (BOOL) savePlist: (NSError**) error
error: error];
}

- (NSMutableArray*) toArrayOfEntries
- (NSMutableArray *) toArrayOfEntries
{
NSMutableArray *array = [NSMutableArray arrayWithCapacity: _dict.count];
[_dict enumerateKeysAndObjectsUsingBlock: ^ ( NSString *key, NSString *value, BOOL *stop ) {
[_dict enumerateKeysAndObjectsUsingBlock: ^( NSString *key, NSString *value, BOOL *stop ) {
[array addObject: @{ @"name": key, @"value": value }.mutableCopy];
}];
}];
return array;
}

Expand All @@ -101,7 +102,7 @@ + (Environment *) withArrayOfEntries: (NSArray *) array
}


- (void)export
- (void) export
{
NSMutableSet *oldVariables;
const char *pcOldVariables = getenv( agentName "_vars" );
Expand Down Expand Up @@ -159,7 +160,7 @@ - (void)export
envlib_setenv( agentName "_vars", pcNewVariables );
}

- (BOOL) isEqualToEnvironment: (Environment*) other
- (BOOL) isEqualToEnvironment: (Environment *) other
{
return [_dict isEqualToDictionary: other->_dict];
}
Expand Down
10 changes: 7 additions & 3 deletions EnvLib/Error.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@

#import <Foundation/Foundation.h>

NSError* LogError( NSError *error );
NSError* NewError( NSString* message );
NSError* LogNewError( NSString* message );
NSError *LogError( NSError *error );

NSError *NewError( NSString *message );

NSError *LogNewError( NSString *message );

BOOL NO_AssignError( NSError **dst, NSError *src );

BOOL NO_LogError( NSError **error );

#endif
6 changes: 3 additions & 3 deletions EnvLib/Error.m
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@
#import "Error.h"


NSError* LogError( NSError *error )
NSError *LogError( NSError *error )
{
NSLog( @"Error: %@", error );
return error;
}

NSError* NewError( NSString* message )
NSError *NewError( NSString *message )
{
return [NSError errorWithDomain: @"EnvLib"
code: 0
userInfo: @{NSLocalizedDescriptionKey : message}];
userInfo: @{ NSLocalizedDescriptionKey: message }];
}

BOOL NO_AssignError( NSError **dst, NSError *src )
Expand Down
11 changes: 7 additions & 4 deletions EnvLib/NSDictionary+EnvLib.m
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,15 @@ - (BOOL) writeToFile: (NSString *) path
reason: @"createAncestors implies createParent"
userInfo: nil];
}
if( createParent && ![[NSFileManager defaultManager] ensureParentDirectoryExistsOf: path
withIntermediateDirectories: createAncestors
error: error] ) return NO;
NSFileManager *manager = [NSFileManager defaultManager];
if( createParent && ![manager ensureParentDirectoryExistsOf: path
withIntermediateDirectories: createAncestors
error: error] ) {
return NO;
}
if( [self writeToFile: path atomically: atomically] ) return YES;

return NO_AssignError( error, NewError( [NSString stringWithFormat: @"Can't write to '%@'", path ] ) );
return NO_AssignError( error, NewError( [NSString stringWithFormat: @"Can't write to '%@'", path] ) );
}

@end
2 changes: 1 addition & 1 deletion EnvLib/NSFileManager+EnvLib.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

@interface NSFileManager (EnvLib)

- (BOOL) ensureParentDirectoryExistsOf: (NSString*) childPath
- (BOOL) ensureParentDirectoryExistsOf: (NSString *) childPath
withIntermediateDirectories: (BOOL) withIntermediateDirectories
error: (NSError **) error;

Expand Down
14 changes: 7 additions & 7 deletions EnvLib/NSFileManager+EnvLib.m
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,23 @@

@implementation NSFileManager (EnvLib)

- (BOOL) ensureParentDirectoryExistsOf: (NSString*) childPath
- (BOOL) ensureParentDirectoryExistsOf: (NSString *) childPath
withIntermediateDirectories: (BOOL) withIntermediateDirectories
error: (NSError **) error
{
NSString* parentPath = [childPath stringByDeletingLastPathComponent];
NSString *parentPath = [childPath stringByDeletingLastPathComponent];
BOOL isDir = NO;
if( ![self fileExistsAtPath: parentPath isDirectory: &isDir] ) {
if( ![self createDirectoryAtPath: parentPath
withIntermediateDirectories: withIntermediateDirectories
attributes: nil
error: error] ) {
if( ![self createDirectoryAtPath: parentPath
withIntermediateDirectories: withIntermediateDirectories
attributes: nil
error: error] ) {
return NO;
}
} else {
if( !isDir ) {
return NO_AssignError( error, NewError( [NSString stringWithFormat: @"Expected directory at '%@'",
parentPath] ) );
parentPath] ) );
}
}
return YES;
Expand Down
1 change: 1 addition & 0 deletions EnvLib/launchd_legacy.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#define launchd_legacy_h

void envlib_setenv( const char *key, const char *value );

void envlib_unsetenv( const char *key );

#endif /* launchd_legacy_h */
37 changes: 21 additions & 16 deletions EnvLib/launchd_xpc.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,37 +21,42 @@

// Much of this is taken from http://newosxbook.com/articles/jlaunchctl.html by Jonathan Levin.

struct xpc_global_data {
uint64_t a;
uint64_t xpc_flags;
mach_port_t task_bootstrap_port;
xpc_object_t xpc_bootstrap_pipe;
struct xpc_global_data
{
uint64_t a;
uint64_t xpc_flags;
mach_port_t task_bootstrap_port;
xpc_object_t xpc_bootstrap_pipe;
};

struct _os_alloc_once_s {
struct _os_alloc_once_s
{
long once;
void *ptr;
};

extern struct _os_alloc_once_s _os_alloc_once_table[];

#define OS_ALLOC_ONCE_KEY_LIBXPC 1 // from libSystem's alloc_once_private.h
#define OS_ALLOC_ONCE_KEY_LIBXPC 1 // from libSystem's alloc_once_private.h

extern int xpc_pipe_routine(xpc_object_t *pipe, xpc_object_t *request, xpc_object_t **response);
extern int xpc_dictionary_set_mach_send(xpc_object_t xdict, const char *key, mach_port_t);
extern char *xpc_strerror(int64_t);
extern int xpc_pipe_routine( xpc_object_t *pipe, xpc_object_t *request, xpc_object_t **response );

bool envlib_setenv_xpc( EnvEntry env[] ) {
extern int xpc_dictionary_set_mach_send( xpc_object_t xdict, const char *key, mach_port_t );

extern char *xpc_strerror( int64_t );

bool envlib_setenv_xpc( EnvEntry env[] )
{
// TODO: We really ought to figure out how to do this os_alloc_once stuff properly.
// We should be looking at the `flag` member of the struct and do sth if it's not set.
struct xpc_global_data *xpc_gd = (struct xpc_global_data *) _os_alloc_once_table[OS_ALLOC_ONCE_KEY_LIBXPC].ptr;
struct xpc_global_data *xpc_gd = (struct xpc_global_data *) _os_alloc_once_table[ OS_ALLOC_ONCE_KEY_LIBXPC ].ptr;

xpc_object_t envvars = xpc_dictionary_create( NULL, NULL, 0 );
for( EnvEntry* entry = env; entry->name; entry++ ) {
for( EnvEntry *entry = env; entry->name; entry++ ) {
if( entry->value ) {
xpc_dictionary_set_string( envvars, entry->name, entry->value);
xpc_dictionary_set_string( envvars, entry->name, entry->value );
} else {
xpc_dictionary_set_value( envvars, entry->name, xpc_null_create());
xpc_dictionary_set_value( envvars, entry->name, xpc_null_create() );
}
}
xpc_object_t dict = xpc_dictionary_create( NULL, NULL, 0 );
Expand All @@ -70,7 +75,7 @@ bool envlib_setenv_xpc( EnvEntry env[] ) {
if( rc == 0 && outDict ) {
int64_t err = xpc_dictionary_get_int64( outDict, "error" );
if( err ) {
NSLog( CFSTR( "Error: %lld - %s\n" ), err, xpc_strerror(err) );
NSLog( CFSTR( "Error: %lld - %s\n" ), err, xpc_strerror( err ) );
} else {
return true;
}
Expand Down
Loading

0 comments on commit 587806b

Please sign in to comment.