Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 740 lines (589 sloc) 25.345 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
/*
* $Id$
* MacPorts.Framework
*
* Authors:
* Randall H. Wood <rhwood@macports.org>
*
* Copyright (c) 2007 Randall H. Wood <rhwood@macports.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright owner nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

#import "MPInterpreter.h"
#import "MPMacPorts.h"
#include "BetterAuthorizationSampleLib.h"
#include "MPHelperCommon.h"
#include "MPHelperNotificationsProtocol.h"
static AuthorizationRef internalMacPortsAuthRef;
static NSString* PKGPath = @"/Library/Tcl";
static NSTask* aTask;

#pragma mark -

@implementation MPInterpreter

#pragma mark Notifications Code
int Notifications_Send(int objc, Tcl_Obj *CONST objv[], int global, Tcl_Interp *interpreter) {
NSString *name;
NSMutableString *msg;

//Our info dictionary is of size 5 and contains the following keys
//NOTIFICATION_NAME - e.g. MPWARN, MPDEBUG etc.
//CHANNEL - eg. stdout, stderr
//PREFIX - prefix string for this message e.g. DEBUG:
//METHOD - the function whose operation led to this notification eg. sync, selfupdate
//MESSAGE - the message logged to channel
NSMutableDictionary *info = [NSMutableDictionary dictionaryWithCapacity:5];
MPNotifications *mln = [MPNotifications sharedListener];

int tclCount;
int tclResult;
const char **tclElements;

name = [NSString stringWithUTF8String:Tcl_GetString(*objv)];
//NSLog(@"name is %@", name);
[info setObject:name forKey:MPNOTIFICATION_NAME];

//Name and Notification constants should match. Convention
//used is MPPriorityNotification. Is it ok to just return TCL_OK ?
if( [mln checkIfNotificationBlocked:name] ){
return TCL_OK;
}

++objv; --objc;
tclResult = Tcl_SplitList(interpreter, Tcl_GetString(*objv), &tclCount, &tclElements);
//NSLog(@"tclElements is %S and tclCount is %i", &tclElements, tclCount);

if (tclResult == TCL_OK) {

//I have sacrificed generality for simplicity in the code below
if (tclCount > 0) {
[info setObject:[NSString stringWithUTF8String:tclElements[0]] forKey:MPCHANNEL];

if(tclElements[1])
[info setObject:[NSString stringWithUTF8String:tclElements[1]] forKey:MPPREFIX];
else
[info setObject:@"None" forKey:MPPREFIX];
}
else {
[info setObject:@"None" forKey:MPCHANNEL];
[info setObject:@"None" forKey:MPPREFIX];
}


//Get ui_* message separately Hopefully this should never be null
++objv; --objc;
if(objv != NULL) {
msg = [NSMutableString stringWithUTF8String:Tcl_GetString(*objv)];
//NSLog(@"Message is %@", msg);

//strip off "--->" over here
NSArray * temp = [msg componentsSeparatedByString:@"--->"];
[msg setString:[temp componentsJoinedByString:@""]];
[info setObject:msg forKey:MPMESSAGE];
}

//Get the Tcl function that called this method
if (! [[mln performingTclCommand] isEqualToString:@""]) {
[info setObject:[mln performingTclCommand] forKey:MPMETHOD];
}
if (global != 0) {
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:name object:nil userInfo:info];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:name object:nil userInfo:info];
}


} else {
return TCL_ERROR;
}

return TCL_OK;
}

int Notifications_Command(ClientData clientData, Tcl_Interp *interpreter, int objc, Tcl_Obj *CONST objv[]) {
MPNotifications * mln = [MPNotifications sharedListener];

//Should I do the filtering in Notificaitons_Send instead?
if( [mln checkIfNotificationBlocked:MPALL] ) {
NSLog(@"ALL NOTIFICATIONS BLOCKED");
return TCL_OK;
}

NSString *action = nil;
int returnCode = TCL_ERROR;

++objv, --objc;

if (objc) {
action = [NSString stringWithUTF8String:Tcl_GetString(*objv)];
++objv, --objc;
if ([action isEqualToString:@"send"]) {
if ([[NSString stringWithUTF8String:Tcl_GetString(*objv)] isEqualToString:@"global"]) {
++objv, --objc;
returnCode = Notifications_Send(objc, objv, 1, interpreter);
} else {
returnCode = Notifications_Send(objc, objv, 0, interpreter);
}
}
}

return returnCode;
}

#pragma mark -

#pragma mark MPInterpreter Code

//This variable is set during initialization and is
//not changed thereafter. Is sole purpose is to enable
//passing the path to macports1.0 package to the helper
//tool
static NSString * tclInterpreterPkgPath = nil;

+(NSString*) PKGPath {
return PKGPath;
}

+(void) setPKGPath:(NSString*)newPath {
    if([PKGPath isNotEqualTo:newPath]) {
        [PKGPath release];
        PKGPath = [newPath copy];
        //I should check if interp is nil. *not needed now
        MPInterpreter *interp = (MPInterpreter*) [[[NSThread currentThread] threadDictionary] objectForKey:@"sharedMPInterpreter"];
        [interp resetTclInterpreterWithPath:PKGPath];
    }
}

#pragma mark -
#pragma mark Internal Methods
//Internal method for initializing actual C Tcl interpreter
//Should I be using a double pointer like is done for NSError ?
-(BOOL) initTclInterpreter:(Tcl_Interp * *)interp withPath:(NSString *)path {
BOOL result = NO;
*interp = Tcl_CreateInterp();

if(*interp == NULL) {
NSLog(@"Error in Tcl_CreateInterp, aborting.");
return result;
}

if(Tcl_Init(*interp) == TCL_ERROR) {
NSLog(@"Error in Tcl_Init: %s", Tcl_GetStringResult(*interp));
Tcl_DeleteInterp(*interp);
return result;
}

if (path == nil)
path = PKGPath;


NSString * mport_fastload = [[@"source [file join \"" stringByAppendingString:path]
stringByAppendingString:@"\" macports1.0 macports_fastload.tcl]"];
if(Tcl_Eval(*interp, [mport_fastload UTF8String]) != TCL_OK) {
NSLog(@"Error in Tcl_EvalFile macports_fastload.tcl: %s", Tcl_GetStringResult(*interp));
Tcl_DeleteInterp(*interp);
return result;
}


Tcl_CreateObjCommand(*interp, "notifications", Notifications_Command, NULL, NULL);
if (Tcl_PkgProvide(*interp, "notifications", "1.0") != TCL_OK) {
NSLog(@"Error in Tcl_PkgProvide: %s", Tcl_GetStringResult(*interp));
Tcl_DeleteInterp(*interp);
return result;
}

if( Tcl_EvalFile(*interp, [[[NSBundle bundleWithIdentifier:@"org.macports.frameworks.macports"]
pathForResource:@"init"
ofType:@"tcl"] UTF8String]) != TCL_OK) {
NSLog(@"Error in Tcl_EvalFile init.tcl: %s", Tcl_GetStringResult(*interp));
Tcl_DeleteInterp(*interp);
return result;
}

result = YES;
return result;
}

//Internal method for setting port Tcl_interpreter options
-(BOOL) setOptions:(NSArray *)options forTclInterpreter:(Tcl_Interp * *)interp {
BOOL result = NO;

//I wish I could use fast enumeration
if (options != nil) {
if ([options count] > 0 ) {
NSEnumerator * optionsEnum = [options objectEnumerator];
id opt;

while ((opt = [optionsEnum nextObject])) {
if (Tcl_Eval(*interp , [[NSString stringWithFormat:@"set ui_options(%@) \"yes\"", opt] UTF8String]) != TCL_OK) {
NSLog(@"Error in Tcl_Eval for set ui_options: %s", Tcl_GetStringResult(*interp));
return result;
}
}
result = YES;
return result;
}
}

return result;
}

//Wrapper method for above. Used when
-(BOOL) setOptionsForNewTclPort:(NSArray *)options {
BOOL result = NO;

//First delete our internal Tcl interpreter
Tcl_DeleteInterp(_interpreter);

if (tclInterpreterPkgPath == nil)
result = [self initTclInterpreter:&_interpreter withPath:PKGPath];
else
result = [self initTclInterpreter:&_interpreter withPath:tclInterpreterPkgPath];

BOOL tempResult = [self setOptions:options forTclInterpreter:&_interpreter];




return (result && tempResult) ;
}

-(BOOL) resetTclInterpreterWithPath:(NSString*) path {
    Tcl_DeleteInterp(_interpreter);
    return [self initTclInterpreter:&_interpreter withPath:PKGPath];
}

- (id) initWithPkgPath:(NSString *)path portOptions:(NSArray *)options {
if (self = [super init]) {
[self initTclInterpreter:&_interpreter withPath:path];

//set port options maybe I should do this elsewhere?
defaultPortOptions = [NSArray arrayWithObjects: MPDEBUGOPTION, nil];
if (options == nil)
options = defaultPortOptions;
[self setOptions:options forTclInterpreter:&_interpreter];

//Initialize helperToolInterpCommand
helperToolInterpCommand = @"";
helperToolCommandResult = @"";

//Initialize the MacPorts Tcl Package Path string
tclInterpreterPkgPath = [NSString stringWithString:path];

}
return self;
}


#pragma mark API methods
- (id) init {
return [self initWithPkgPath:PKGPath portOptions:nil];
}

+ (MPInterpreter*)sharedInterpreterWithPkgPath:(NSString *)path {
return [self sharedInterpreterWithPkgPath:path portOptions:nil];
}

+ (MPInterpreter*)sharedInterpreter{
return [self sharedInterpreterWithPkgPath:PKGPath];
}

+ (MPInterpreter*)sharedInterpreterWithPkgPath:(NSString *)path portOptions:(NSArray *)options {
@synchronized(self) {
        if ([PKGPath isNotEqualTo:path]) {
            [self setPKGPath:path];
        }
        
if ([[[NSThread currentThread] threadDictionary] objectForKey:@"sharedMPInterpreter"] == nil) {
[[self alloc] initWithPkgPath:path portOptions:options]; // assignment not done here
}
}
return [[[NSThread currentThread] threadDictionary] objectForKey:@"sharedMPInterpreter"];
}


+ (id)allocWithZone:(NSZone*)zone {
@synchronized(self) {
if ([[[NSThread currentThread] threadDictionary] objectForKey:@"sharedMPInterpreter"] == nil) {
[[[NSThread currentThread] threadDictionary] setObject:[super allocWithZone:zone] forKey:@"sharedMPInterpreter"];
return [[[NSThread currentThread] threadDictionary] objectForKey:@"sharedMPInterpreter"]; // assignment and return on first allocation
}
}
return nil; // subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone*)zone {
    return self;
}

- (id)retain {
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax; //denotes an object that cannot be released
}

- (void)release {

}

- (id)autorelease {
    return self;
}

#pragma Port Operations

#pragma Port Settings

#pragma Utilities
- (NSArray *)arrayFromTclListAsString:(NSString *)list {
NSMutableArray *array;
int tclCount;
int tclResult;
int i;
const char **tclElements;
tclResult = Tcl_SplitList(_interpreter, [list UTF8String], &tclCount, &tclElements);
if (tclResult == TCL_OK) {
array = [[NSMutableArray alloc] initWithCapacity:tclCount];
for (i = 0; i < tclCount; i++) {
[array addObject:[NSString stringWithUTF8String:tclElements[i]]];
}
} else {
array = [[[NSMutableArray alloc] init] autorelease];
}
Tcl_Free((char *)tclElements);
return [NSArray arrayWithArray:array];
}

- (NSDictionary *)dictionaryFromTclListAsString:(NSString *)list {
return [NSDictionary dictionaryWithDictionary:[self mutableDictionaryFromTclListAsString:list]];
}

- (NSMutableDictionary *)mutableDictionaryFromTclListAsString:(NSString *)list {
NSMutableDictionary *dictionary;
NSArray *array;
int i;
array = [self arrayFromTclListAsString:list];
dictionary = [[NSMutableDictionary alloc] initWithCapacity:[array count]];
unsigned int array_count = [array count];

for (i = 0; i < array_count; i += 2) {
[dictionary setObject:[array objectAtIndex:(i + 1)] forKey:[array objectAtIndex:i]];
}
return dictionary;
}

- (NSArray *)getVariableAsArray:(NSString *)variable {
return [self arrayFromTclListAsString:[NSString stringWithUTF8String:Tcl_GetVar(_interpreter, [variable UTF8String], TCL_LIST_ELEMENT)]];
}

- (NSString *)getVariableAsString:(NSString *)variable {
return [NSString stringWithUTF8String:Tcl_GetVar(_interpreter, [variable UTF8String], 0)];
}


#pragma mark -
#pragma mark -evaluateString* routines

- (NSString *)evaluateStringAsString:(NSString *)statement error:(NSError**)mportError{
//NSLog(@"Calling evaluateStringAsString with argument %@", statement);

int return_code = Tcl_Eval(_interpreter, [statement UTF8String]);

//Should I check for (return_code != TCL_Ok && return_code != TCL_RETURN) instead ?
if (return_code != TCL_OK) {

Tcl_Obj * interpObj = Tcl_GetObjResult(_interpreter);
int length, errCode;
NSString * errString = [NSString stringWithUTF8String:Tcl_GetStringFromObj(interpObj, &length)];
//NSLog(@"TclObj string is %@ with length %d", errString , length);
errCode = Tcl_GetErrno();
//NSLog(@"Errno Id is %@ with value %d", [NSString stringWithUTF8String:Tcl_ErrnoId()], errCode);
//NSLog(@"Errno Msg is %@", [NSString stringWithUTF8String:Tcl_ErrnoMsg(errCode)]);

//Handle errors here ... Framework users can do !mportError to find out if
//method was successful
NSString *descrip = NSLocalizedString(errString, @"");
NSDictionary *errDict;
//For now all error codes are TCL_ERROR

//Create underlying error - For now I'll create the underlying Posix Error
NSError *undError = [[[NSError alloc] initWithDomain:NSPOSIXErrorDomain
code:errCode
userInfo:nil] autorelease];
//Create and return custom domain error
NSArray *objArray = [NSArray arrayWithObjects:descrip, undError, nil];
NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,
NSUnderlyingErrorKey, nil];
errDict = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray];
if (mportError != NULL)
*mportError = [[[NSError alloc] initWithDomain:MPFrameworkErrorDomain
code:TCL_ERROR
userInfo:errDict] autorelease];
return nil;
}

return [NSString stringWithUTF8String:Tcl_GetStringResult(_interpreter)];
}

- (NSString *)evaluateStringWithPossiblePrivileges:(NSString *)statement error:(NSError **)mportError {
//N.B. I am going to insist that funciton users not pass in nil for the
//mportError parameter
NSString * result;

    [[MPNotifications sharedListener]
     sendIPCNotification:@"MPInfoNotification_&MP&_stdout_&MP&_None_&MP&_Starting up"];
    
    // Is this the best way to know if the running user can use macports without privileges?
    if ([[NSFileManager defaultManager] isWritableFileAtPath:PKGPath]) {
        result = [self evaluateStringWithMPPortProcess:statement error:mportError];
    } else {
        result = [self evaluateStringWithMPHelperTool:statement error:mportError];
    }

    [[MPNotifications sharedListener]
     sendIPCNotification:@"MPInfoNotification_&MP&_stdout_&MP&_None_&MP&_Shutting down"];
    
return result;
}

//NOTE: We expect the Framework client to initialize the AuthorizationRef
//Completely before calling any privileged operation. If not we will pass in
//a barely initialzed one. This method returns nil if there is an error
- (NSString *) evaluateStringWithMPHelperTool:(NSString *) statement error:(NSError **)mportError {
OSStatus err;
    BASFailCode failCode;
    NSString * bundleID;
    NSDictionary * request;
    CFDictionaryRef response;
NSString * result = nil;

response = NULL;

//Creating file path for IPC with helper tool
NSString * ipcFilePath = [NSString stringWithFormat:@"%@_%@", @kServerSocketPath, [NSDate date]];
NSString * ipcFilePathCopy = [NSString stringWithString:ipcFilePath];


//We need to use the notificationsObject to set up IPC with the helper tool
//I hope BAS's main method is blocking ... it should be since we obtain
//a return value
MPNotifications * notificationObject = [MPNotifications sharedListener];
//if ([notificationObject respondsToSelector:@selector(prepareIPCServerThread)]) {
NSLog(@"PREPARING SERVER THREAD");
[notificationObject prepareIPCServerThread];
//}

//if ([notificationObject respondsToSelector:@selector(startServerThread)]) {
NSThread * cThread = [NSThread currentThread];
NSLog(@"STARTING SERVER THREAD with previous thread %@", [cThread threadDictionary]);

//This is important to note ... the tcl command being executed is saved in the
//current thread's thread dictionary in the upper tier method that calls this one.
// This means we are only going to guarantee
//thread saftey for Framework clients at the the level of MPMacPorts, MPPorts etc. and above
NSDictionary * serverInfo = [NSDictionary dictionaryWithObjectsAndKeys:
ipcFilePathCopy, @"ipcFilePath",
[[MPNotifications sharedListener] performingTclCommand], @"currentMethod",
nil];

[NSThread detachNewThreadSelector:@selector(startIPCServerThread:)
toTarget:notificationObject
withObject:serverInfo];
//[notificationObject startIPCServerThread];
//}


//Retrieving the path for interpInit.tcl for our helper tool
NSString * interpInitPath = [[NSBundle bundleForClass:[MPInterpreter class]]
pathForResource:@"interpInit" ofType:@"tcl"];





request = [NSDictionary dictionaryWithObjectsAndKeys:
@kMPHelperEvaluateTclCommand, @kBASCommandKey,
statement, @kTclStringToBeEvaluated,
tclInterpreterPkgPath, @kTclInterpreterInitPath ,
interpInitPath, @kInterpInitFilePath,
ipcFilePath, @kServerFileSocketPath , nil];

assert(request != NULL);

bundleID = [[NSBundle bundleForClass:[self class]] bundleIdentifier];

assert(bundleID != NULL);


//In order to make the framework work normally by default ... we do a bare initialization
//of internalMacPortsAuthRef if the delegate hasn't initialzed it already
if (internalMacPortsAuthRef == NULL) {
OSStatus res = AuthorizationCreate (NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &internalMacPortsAuthRef);
assert(res == noErr);
}

BASSetDefaultRules(internalMacPortsAuthRef,
kMPHelperCommandSet,
(CFStringRef) bundleID,
NULL);

//NSLog(@"BEFORE Tool Execution request is %@ , response is %@ \n\n", request, response);
err = BASExecuteRequestInHelperTool(internalMacPortsAuthRef,
kMPHelperCommandSet,
(CFStringRef) bundleID,
(CFDictionaryRef) request,
&response);
if (err == noErr){// retrieve result here if available
if( response != NULL)
result = (NSString *) (CFStringRef) CFDictionaryGetValue(response, CFSTR(kTclStringEvaluationResult));
}
else { //Try to recover error
failCode = BASDiagnoseFailure(internalMacPortsAuthRef, (CFStringRef) bundleID);


//Need to pass in URL's to helper and install tools since I
//modified BASFixFaliure
NSBundle * mpBundle = [NSBundle bundleForClass:[self class]];

NSString * installToolPath = [mpBundle pathForResource:@"MPHelperInstallTool" ofType:nil];
assert(installToolPath != nil);
NSURL * installToolURL = [NSURL fileURLWithPath:installToolPath];
assert(installToolURL != nil);

NSString * helperToolPath = [mpBundle pathForResource:@"MPHelperTool" ofType:nil];
assert(helperToolPath != nil);
NSURL * helperToolURL = [NSURL fileURLWithPath:helperToolPath];
assert(helperToolURL != nil);

err = BASFixFailure(internalMacPortsAuthRef,
(CFStringRef) bundleID,
(CFURLRef) installToolURL,
(CFURLRef) helperToolURL,
failCode);


//Making the following assumption in error handling. If we return
//a noErr then response dictionary cannot be nil since everything went ok.
//Hence I'm only checking for errors WITHIN the following blocks ...
        //
        // NOTE: We don't automatically retry as the user wants to have a consistent cancel
        // action (i.e. terminate the process when he wants to)
if (err != noErr) {//This means FixFaliure failed ... Report that in returned error
if (mportError != NULL) {
//I'm not sure of exactly how to report this error ...
//Do we need some error codes for our domain? I'll define one
NSError * undError = [[[NSError alloc] initWithDomain:NSOSStatusErrorDomain
code:err
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
NSLocalizedString(@"Check error code for OSStatus returned",@""),
NSLocalizedDescriptionKey,
nil]] autorelease];

*mportError = [[[NSError alloc] initWithDomain:MPFrameworkErrorDomain
code:MPHELPINSTFAILED
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
NSLocalizedString(@"Unable to fix faliure for MPHelperTool execution", @""),
NSLocalizedDescriptionKey,
undError, NSUnderlyingErrorKey,
NSLocalizedString(@"BASFixFaliure routine wasn't completed successfuly", @""),
NSLocalizedFailureReasonErrorKey,
nil]] autorelease];
}
}
}

//NSLog(@"AFTER Tool Execution request is %@ , response is %@ \n\n", request, response);

return result;
}

- (NSString *) evaluateStringWithMPPortProcess:(NSString *) statement error:(NSError **)mportError {
    aTask = [[NSTask alloc] init];
    NSMutableArray *args = [NSMutableArray array];
    
    /* set arguments */
    [args addObject:PKGPath];
    [aTask setCurrentDirectoryPath:[[NSBundle bundleForClass:[self class]] resourcePath]];
    [aTask setLaunchPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"MPPortProcess" ofType:@""]];
    [aTask setArguments:args];
    [aTask launch];
    
    NSConnection *notificationsConnection = [NSConnection defaultConnection];
    // Vending MPNotifications sharedListener
    [notificationsConnection setRootObject:[MPNotifications sharedListener]];
    
    // Register the named connection
    if ( [notificationsConnection registerName:@"MPNotifications"] ) {
        NSLog( @"Successfully registered connection with port %@",
              [[notificationsConnection receivePort] description] );
    } else {
        NSLog( @"Name used by %@",
              [[[NSPortNameServer systemDefaultPortNameServer] portForName:@"MPNotifications"] description] );
    }
    
    
    id theProxy;
    do {
        theProxy = [NSConnection
                       rootProxyForConnectionWithRegisteredName:@"MPPortProcess"
                       host:nil];
    }
    while (theProxy == nil);
    
    [theProxy evaluateString:statement];
    [aTask waitUntilExit];
    
    int status = [aTask terminationStatus];
    
    if (status != TCL_OK) {
        NSLog(@"Task failed. Code: %i", status);
    }
    [[notificationsConnection receivePort] invalidate];
    
    return nil;
}

+ (NSTask*) task {
    return aTask;
}

+ (void) terminateMPHelperTool {
    NSString * bundleID;

    //In order to make the framework work normally by default ... we do a bare initialization
    //of internalMacPortsAuthRef if the delegate hasn't iniitialzed it already
    if (internalMacPortsAuthRef == NULL) {
        OSStatus res = AuthorizationCreate (NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &internalMacPortsAuthRef);
        assert(res == noErr);
    }

    NSBundle * mpBundle = [NSBundle bundleForClass:[self class]];
    NSString * installToolPath = [mpBundle pathForResource:@"MPHelperInstallTool" ofType:nil];
    bundleID = [mpBundle bundleIdentifier];

    BASSetDefaultRules(internalMacPortsAuthRef,
                        kMPHelperCommandSet,
                        (CFStringRef) bundleID,
                        NULL);
    BASTerminateCommand(internalMacPortsAuthRef,
                        [bundleID UTF8String],
                        [installToolPath UTF8String]);
    return;
}

#pragma mark -
#pragma mark Authorization Code

- (BOOL)checkIfAuthorized {
if (internalMacPortsAuthRef == NULL ) {
return NO;
}
return YES;
}

-(void)setAuthorizationRef:(AuthorizationRef)authRef {
//I can do this since Framework client responsible
//for managing memory for Authorization
internalMacPortsAuthRef = authRef;
}



#pragma mark -
#pragma mark For Internal Use

- (int) execute:(NSString *)pathToExecutable withArgs:(NSArray *)args {
NSTask * task = [[NSTask alloc] init];
[task setLaunchPath:pathToExecutable];
[task setArguments:args];
[task launch];
[task waitUntilExit];
int status = [task terminationStatus];
[task release];
return status;
}


- (Tcl_Interp *) sharedInternalTclInterpreter {
return _interpreter;
}

@end
Something went wrong with that request. Please try again.