5 // Created by Claudio Bisegni on 10/05/07.
6 // Copyright (c) 2007 INFN - National Institute of Nuclear Physics. All rights reserved.
9 #import "AFSCommanderPref.h"
10 #import "IpConfiguratorCommander.h"
11 #import "TokenCredentialController.h"
12 #import "InfoController.h"
14 #import "PListManager.h"
15 #import "DialogUtility.h"
16 #import "NSString+search.h"
17 #include <sys/param.h>
20 #include <sys/types.h>
21 #include <sys/fcntl.h>
22 #include <sys/errno.h>
26 #import <CoreServices/CoreServices.h>
29 #define ADD_CELL_CONTROL_TAG 1
30 #define REMOVE_CELL_CONTROL_TAG 2
32 #define TABLE_TOKENS_LIST 1
33 #define TABLE_CELL_LIST 2
36 #define TAB_CELL_SERV_DB 2
41 #define CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN 0
42 #define CELLSRVDB_TABLE_DFLT_CHECK_COLUMN 1
43 #define CELLSRVDB_TABLE_NAME_COLUMN 2
44 #define CELLSRVDB_TABLE_DESCRIPTION_COLUMN 3
46 @implementation AFSCommanderPref
48 // -------------------------------------------------------------------------------
50 // -------------------------------------------------------------------------------
51 - (id)initWithBundle:(NSBundle *)bundle
53 if ( ( self = [super initWithBundle:bundle] ) != nil ) {
54 //appID = afsCommanderID;
60 // -------------------------------------------------------------------------------
62 // -------------------------------------------------------------------------------
63 - (NSView *) mainView {
64 if (prefStartUp == 1){
67 if (Gestalt(gestaltSystemVersionMajor, &osxMJVers) == noErr && Gestalt(gestaltSystemVersionMinor, &osxMnVers) == noErr) {
68 if (osxMJVers == 10 && osxMnVers>= 5) {
69 // we are working on leopard
70 NSLog(@"Leopard AFSCommander adapting");
71 [afsCommanderView setFrameSize:NSMakeSize(668, [afsCommanderView frame].size.height)];
77 return afsCommanderView;
80 // -------------------------------------------------------------------------------
82 // -------------------------------------------------------------------------------
83 - (void) mainViewDidLoad
86 [((NSTableView*)cellList) setDelegate:self];
87 [((NSTableView*)cellList) setTarget:self];
88 [((NSTableView*)cellList) setDoubleAction:@selector(tableDoubleAction:)];
93 // -------------------------------------------------------------------------------
95 // -------------------------------------------------------------------------------
99 [textFieldDevInfoLabel setStringValue:kDevelopInfo];
101 tokensLock = [[NSLock alloc] init];
103 //Initialization cellservdb and token list
104 filteredCellDB = nil;
107 [self readPreferenceFile];
109 // alloc the afs property mananger
110 afsProperty = [[AFSPropertyManager alloc] init];
112 // register preference pane to detect menuextra killed by user
113 [[NSDistributedNotificationCenter defaultCenter] addObserver:self
114 selector:@selector(mextraChangeActivation:)
116 object:kMExtraClosedNotification];
118 [[NSDistributedNotificationCenter defaultCenter] addObserver:self
119 selector:@selector(refreshGui:)
121 object:kMenuExtraEventOccured];
123 //Register for mount/unmount afs volume
124 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
125 selector:@selector(afsVolumeMountChange:)
126 name:NSWorkspaceDidMountNotification object:nil];
128 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
129 selector:@selector(afsVolumeMountChange:)
130 name:NSWorkspaceDidUnmountNotification object:nil];
132 // set self as table data source
133 [((NSTableView*)cellList) setDataSource:self];
134 [((NSTableView*)tokensTable) setDataSource:self];
136 //check the afs state
139 // check the MenuExtra state
140 [self mextraChangeActivation:nil];
142 // let show the configuration after prefpane is open
143 [self refreshConfiguration:nil];
145 // refresh the token list
146 //[self refreshTokens:nil];
148 //refresh table to reflect the NSSearchField contained text
149 [self searchCellTextEvent:nil];
152 // -------------------------------------------------------------------------------
154 // -------------------------------------------------------------------------------
157 NSLog(@"willUnselect");
158 // remove self as datasource
159 [((NSTableView*)cellList) setDataSource:nil];
160 [((NSTableView*)tokensTable) setDataSource:nil];
162 //release the afs property manager
163 if(afsProperty) [afsProperty release];
164 //release tokens list
165 if(tokenList) [tokenList release];
166 //Remove the cell temp array
167 if(filteredCellDB) [filteredCellDB release];
169 [self writePreferenceFile];
171 // unregister preference pane to detect menuextra killed by user
172 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self
174 object:kMExtraClosedNotification];
175 [[NSDistributedNotificationCenter defaultCenter] removeObserver:self
177 object:kMenuExtraEventOccured];
178 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self
179 name:NSWorkspaceDidMountNotification object:nil];
180 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self
181 name:NSWorkspaceDidUnmountNotification object:nil];
184 [tokensLock release];
188 // -------------------------------------------------------------------------------
190 // -------------------------------------------------------------------------------
192 //start the time for check tokens validity
193 if(timerForCheckTokensList) return;
194 timerForCheckTokensList = [NSTimer scheduledTimerWithTimeInterval:TOKENS_REFRESH_TIME_IN_SEC
196 selector:@selector(refreshTokens:)
199 [timerForCheckTokensList fire];
202 // -------------------------------------------------------------------------------
204 // -------------------------------------------------------------------------------
206 if(!timerForCheckTokensList) return;
207 [timerForCheckTokensList invalidate];
208 timerForCheckTokensList = nil;
212 // -------------------------------------------------------------------------------
213 // readPreferenceFile:
214 // -------------------------------------------------------------------------------
215 - (void) readPreferenceFile
218 // read the preference for afs path
219 //NSString *afsSysPath = PREFERENCE_AFS_SYS_PAT_STATIC;/*(NSString*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_AFS_SYS_PAT, (CFStringRef)afsCommanderID,
220 // kCFPreferencesAnyUser, kCFPreferencesAnyHost);*/
222 [((NSTextField*) installationPathTextField ) setStringValue:afsSysPath];
225 // read the preference for aklog use
226 NSNumber *useAklogPrefValue = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_USE_AKLOG, (CFStringRef)afsCommanderID,
227 kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
228 if(useAklogPrefValue){
229 [useAklogCheck setState:[useAklogPrefValue intValue]];
230 [aklogCredentialAtLoginTime setEnabled:[useAklogPrefValue intValue]];
232 [useAklogCheck setState:NSOffState];
233 [aklogCredentialAtLoginTime setEnabled:NSOffState];
234 [aklogCredentialAtLoginTime setState:NSOffState];
235 [PListManager installLaunchdFile:NO
239 //check if krb5 at startup is enable at system level
240 [installKRB5AuthAtLoginButton setState:[PListManager checkKrb5AtLoginTimeLaunchdEnable]];
242 //check if the user has installed and enabled the afs agent
243 [aklogCredentialAtLoginTime setState:[PListManager checkAklogAtLoginTimeLaunchdEnable]];
245 //check for AFS enable at startup
246 NSNumber *afsEnableStartupTime = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_START_AFS_AT_STARTUP,
247 (CFStringRef)afsCommanderID, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
248 if(afsEnableStartupTime)
249 startAFSAtLogin = [afsEnableStartupTime boolValue];
251 startAFSAtLogin = false;
252 //set the check button state
253 [checkButtonAfsAtBootTime setState:startAFSAtLogin];
256 // -------------------------------------------------------------------------------
258 // -------------------------------------------------------------------------------
259 - (void) writePreferenceFile
261 //Set the preference for afs path
262 /*CFPreferencesSetValue((CFStringRef)PREFERENCE_AFS_SYS_PAT,
263 (CFStringRef)[((NSTextField*) installationPathTextField ) stringValue],
264 (CFStringRef)afsCommanderID, kCFPreferencesAnyUser, kCFPreferencesAnyHost);*/
266 //Set the preference for aklog use
267 CFPreferencesSetValue((CFStringRef)PREFERENCE_USE_AKLOG,
268 (CFNumberRef)[NSNumber numberWithInt:[useAklogCheck state]],
269 (CFStringRef)afsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
273 if ([self isAFSMenuExtraLoaded]) [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kPrefChangeNotification];
275 //set AFS enable state at startup
276 CFPreferencesSetValue((CFStringRef)PREFERENCE_START_AFS_AT_STARTUP,
277 (CFNumberRef)[NSNumber numberWithBool:startAFSAtLogin],
278 (CFStringRef)afsCommanderID, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
280 CFPreferencesSynchronize((CFStringRef)afsCommanderID, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
281 CFPreferencesSynchronize((CFStringRef)afsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
284 // -------------------------------------------------------------------------------
285 // saveConfiguration:
286 // -------------------------------------------------------------------------------
287 - (IBAction) saveConfiguration:(id) sender
291 //[afsProperty setCellName:[cellNameTextEdit stringValue]];
292 [afsProperty setCellName:[afsProperty getDefaultCellName]];
294 //save configurations
295 [afsProperty saveConfigurationFiles:YES];
298 //Reload all configuration
299 [self refreshConfiguration:nil];
301 //refresh table to reflect the NSSearchField contained text
302 [self searchCellTextEvent:nil];
304 //Show dialog for notifity al saving process ar gone ell
305 [self showMessage:kConfigurationSaved];
306 }@catch(NSException *e){
307 [self showMessage:[e reason]];
309 [((NSTableView*)cellList) reloadData];
314 // -------------------------------------------------------------------------------
315 // saveCacheManagerParam:
316 // -------------------------------------------------------------------------------
317 - (IBAction) saveCacheManagerParam:(id) sender
320 NSLog(@"Backing up the cache configuration file");
321 //Update the value form view to afs property manager class
322 [self updateCacheParamFromView];
323 [afsProperty saveCacheConfigurationFiles:YES];
324 NSLog(@"Cache configuration file backuped");
325 [self showMessage:kSavedCacheConfiguration];
326 }@catch(NSException *e){
327 [self showMessage:[e reason]];
329 [((NSTableView*)cellList) reloadData];
333 // -------------------------------------------------------------------------------
334 // refreshConfiguration:
335 // -------------------------------------------------------------------------------
336 - (IBAction) refreshConfiguration:(id) sender
338 NSLog(@"refreshConfiguration");
339 NSString *afsBasePath = PREFERENCE_AFS_SYS_PAT_STATIC;
343 [afsProperty setPath:afsBasePath];
345 // load configuration
346 [afsProperty loadConfiguration];
348 //set the afs version label
349 [afsVersionLabel setStringValue:[afsProperty getAfsVersion]];
351 //set the current default cell
352 [afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
355 [self fillCacheParamView];
357 //Filter the cellServDb and allocate filtered array
358 [self filterCellServDB:nil];
360 }@catch(NSException *e){
361 [self showMessage:[e reason]];
363 [((NSTableView*)cellList) reloadData];
367 // -------------------------------------------------------------------------------
368 // fillCacheParamView:
369 // -------------------------------------------------------------------------------
370 -(void) fillCacheParamView
372 [dynRoot setState:[afsProperty dynRoot]?NSOnState:NSOffState];
373 [afsDB setState:[afsProperty afsDB]?NSOnState:NSOffState];
374 [statCacheEntry setIntValue:[afsProperty statCacheEntry]];
375 [dCacheDim setIntValue:[afsProperty dCacheDim]];
376 [cacheDimension setIntValue:[afsProperty cacheDimension]];
377 [daemonNumber setIntValue:[afsProperty daemonNumber]];
378 [afsRootMountPoint setStringValue:[afsProperty afsRootMountPoint]];
379 [nVolEntry setIntValue:[afsProperty nVolEntry]];
381 //new version property
382 //[verbose setEnabled:[afsProperty useAfsdConfConfigFile]];
383 [verbose setState:[afsProperty verbose]?NSOnState:NSOffState];
387 // -------------------------------------------------------------------------------
388 // updateCacheParamFromView:
389 // -------------------------------------------------------------------------------
390 -(void) updateCacheParamFromView
392 NSString *tmpAfsPath = [afsRootMountPoint stringValue];
393 if(!tmpAfsPath || ([tmpAfsPath length] == 0) || ([tmpAfsPath characterAtIndex:0] != '/'))
394 @throw [NSException exceptionWithName:@"updateCacheParamFromView"
395 reason:kBadAfsRootMountPoint
399 [afsProperty setDynRoot:[dynRoot state]==NSOnState];
400 [afsProperty setAfsDB:[afsDB state]==NSOnState];
401 [afsProperty setStatCacheEntry:[statCacheEntry intValue]];
402 [afsProperty setDCacheDim:[dCacheDim intValue]];
403 [afsProperty setCacheDimension:[cacheDimension intValue]];
404 [afsProperty setDaemonNumber:[daemonNumber intValue]];
405 [afsProperty setAfsRootMountPoint:tmpAfsPath];
406 [afsProperty setNVolEntry:[nVolEntry intValue]];
407 [afsProperty setVerbose:[verbose state]==NSOnState];
411 // -------------------------------------------------------------------------------
413 // -------------------------------------------------------------------------------
414 - (IBAction) showCellIP:(id) sender
416 int rowSelected = [((NSTableView *) cellList) selectedRow];
417 [self modifyCellByIDX:rowSelected];
420 // -------------------------------------------------------------------------------
422 // -------------------------------------------------------------------------------
423 -(void) modifyCellByIDX:(int) idx
425 [self modifyCell:[self getCellByIDX:idx]];
428 // -------------------------------------------------------------------------------
430 // -------------------------------------------------------------------------------
431 -(void) modifyCell:(DBCellElement*) cellElement
433 [NSBundle loadNibNamed:@"IpPanel" owner:self];
434 [((IpConfiguratorCommander*) ipConfControllerCommander) setWorkCell:cellElement];
435 [NSApp beginSheet: ipConfigurationSheet
436 modalForWindow: [[self mainView] window]
438 didEndSelector: @selector(didEndSheet:returnCode:contextInfo:)
442 // -------------------------------------------------------------------------------
444 // -------------------------------------------------------------------------------
445 - (IBAction) addRemoveCell:(id) sender
447 switch([((NSControl*) sender) tag]){
448 case ADD_CELL_CONTROL_TAG:
450 DBCellElement *newCell = [[DBCellElement alloc] init];
453 [newCell setCellName:kNewCellName];
454 [newCell setCellComment:kNewCellComment];
456 [[afsProperty getCellList] addObject:newCell];
460 [self modifyCell:newCell];
464 case REMOVE_CELL_CONTROL_TAG:
467 NSIndexSet *selectedIndex = [(NSTableView*)cellList selectedRowIndexes];
468 if( [selectedIndex count] > 0) {
469 index = [selectedIndex firstIndex];
471 DBCellElement *cellElement = (DBCellElement*)[filteredCellDB objectAtIndex:index];
472 [[afsProperty getCellList] removeObject:cellElement];
473 } while ((index = [selectedIndex indexGreaterThanIndex: index]) != NSNotFound);
478 //Filter the cellServDb and allocate filtered array
479 [self searchCellTextEvent:nil];
480 [(NSTableView*)cellList deselectAll:nil];
481 [(NSTableView*)cellList reloadData];
484 // -------------------------------------------------------------------------------
486 // -------------------------------------------------------------------------------
487 - (void) repairHelperTool
492 NSLog(@"repairHelperTool");
493 NSString *afshlpPath = [[self bundle] pathForResource:@"afshlp" ofType:nil];
497 // Open tool exclusively, so nobody can change it while we bless it.
498 fdTool = open([afshlpPath UTF8String], O_NONBLOCK | O_RDONLY | O_EXLOCK, 0);
502 NSLog(@"Exclusive open while repairing tool failed: %d.", errno);
506 if(fstat(fdTool, &st))
508 NSLog(@"fstat failed.");
514 status = [[AuthUtil shared] autorize];
516 fchown(fdTool, 0, st.st_gid);
518 // Disable group and world writability and make setuid root.
519 fchmod(fdTool, (st.st_mode & (~(S_IWGRP | S_IWOTH)))/* | S_ISUID*/);
520 const char *args[] = {"root", [afshlpPath UTF8String],0L};
521 [[AuthUtil shared] execUnixCommand:"/usr/sbin/chown"
524 [[AuthUtil shared] deautorize];
526 } else NSLog(@"st_uid = 0");
532 NSLog(@"Self-repair done.");
537 // -------------------------------------------------------------------------------
539 // -------------------------------------------------------------------------------
540 - (IBAction) startStopAfs:(id) sender
542 OSStatus status = noErr;
543 NSString *afsdPath = [TaskUtil searchExecutablePath:@"afsd"];
544 //NSString *startStopScript = nil;
545 NSString *rootHelperApp = nil;
546 BOOL currentAfsState = NO;
549 if(afsdPath == nil) return;
550 currentAfsState = [afsProperty checkAfsStatus];
551 rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
553 //[startStopScript setString: resourcePath];
554 NSLog(@"Launch repair HelperTool");
556 [self repairHelperTool];
558 // make the parameter to call the root helper app
559 status = [[AuthUtil shared] autorize];
563 NSLog(@"Shutting down afs");
564 NSMutableString *afsKextPath = [[NSMutableString alloc] initWithCapacity:256];
565 [afsKextPath setString:[afsProperty path]];
566 [afsKextPath appendString:@"/etc/afs.kext"];
568 //Make the array for arguments
569 NSLog(@"executeTaskWithAuth");
570 const char *stopAfsArgs[] = {"stop_afs", [afsKextPath UTF8String], [afsdPath UTF8String], 0L};
571 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
576 NSLog(@"Starting up afs");
577 const char *startAfsArgs[] = {[[[self bundle] pathForResource:@"start_afs" ofType:@"sh"] UTF8String], [[afsProperty path] UTF8String], [afsdPath UTF8String], 0L};
578 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
583 [self refreshGui:nil];
585 @catch (NSException * e) {
586 [self showMessage:[e reason]];
589 [[AuthUtil shared] deautorize];
593 // -------------------------------------------------------------------------------
595 // -------------------------------------------------------------------------------
596 - (void) refreshGui:(NSNotification *)notification{
597 BOOL afsIsUp = [afsProperty checkAfsStatus];
599 //[self refreshTokens:nil];
600 [tokensButton setEnabled:afsIsUp];
601 [unlogButton setEnabled:afsIsUp];
604 // -------------------------------------------------------------------------------
605 // afsVolumeMountChange: Track the afs volume state change
606 // -------------------------------------------------------------------------------
607 - (void) afsVolumeMountChange:(NSNotification *)notification{
608 // Cehck if is mounted or unmounted afs
609 if([[[notification userInfo] objectForKey:@"NSDevicePath"] isEqualToString:@"/afs"]){
611 [self refreshTokens:nil];
615 // -------------------------------------------------------------------------------
617 // -------------------------------------------------------------------------------
618 - (IBAction) info:(id) sender
620 //NSLog(kDevelopInfo);
621 //[self showMessage:kDevelopInfo];
622 [((InfoController*) infoController) showHtmlResource:[[self bundle] pathForResource:@"licenza" ofType:@"rtf"]];
624 [NSApp beginSheet: infoSheet
625 modalForWindow: [[self mainView] window]
627 didEndSelector: @selector(didEndInfoSheet:returnCode:contextInfo:)
631 // -------------------------------------------------------------------------------
632 // tableDoubleAction:
633 // -------------------------------------------------------------------------------
634 - (IBAction) tableDoubleAction:(id) sender
636 [self showCellIP:nil];
639 // -------------------------------------------------------------------------------
641 // -------------------------------------------------------------------------------
642 - (IBAction) getNewToken:(id) sender
644 BOOL useAklog = [useAklogCheck state] == NSOnState;
646 //[AFSPropertyManager aklog];
647 [afsProperty getTokens:false
650 [self refreshTokens:nil];
651 //Inform afs menuextra to updata afs status
652 if ([self isAFSMenuExtraLoaded]) [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
655 [NSBundle loadNibNamed:@"CredentialPanel" owner:self];
656 [NSApp beginSheet: credentialSheet
657 modalForWindow: [[self mainView] window]
659 didEndSelector: @selector(didEndCredentialSheet:returnCode:contextInfo:)
665 // -------------------------------------------------------------------------------
666 // getCurrentCellInDB:
667 // -------------------------------------------------------------------------------
668 - (IBAction) unlog:(id) sender
671 NSIndexSet *selectedIndex = [(NSTableView*)tokensTable selectedRowIndexes];
672 if( [selectedIndex count] > 0) {
673 index = [selectedIndex firstIndex];
675 NSString *tokenDesc = [tokenList objectAtIndex:index];
676 NSString *cellToUnlog = [tokenDesc estractTokenByDelimiter:@"afs@"
678 [afsProperty unlog:cellToUnlog];
679 } while ((index = [selectedIndex indexGreaterThanIndex: index]) != NSNotFound);
681 [afsProperty unlog:nil];
683 [self refreshTokens:nil];
684 //Inform afs menuextra to updata afs status
685 if ([self isAFSMenuExtraLoaded]) [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
690 // -------------------------------------------------------------------------------
692 // -------------------------------------------------------------------------------
693 - (IBAction) aklogSwitchEvent:(id) sender
695 //afs menu extra is loaded inform it to read preference
697 if(![useAklogCheck state]) {
698 //Remove launchd ctrl file
699 [PListManager installLaunchdFile:NO resourcePath:[[self bundle] resourcePath]];
701 //deselect the checkbox
702 [aklogCredentialAtLoginTime setState:NO];
705 [self writePreferenceFile];
707 //Enable disable aklog at login time checkbox according the useAklog checkbox
708 [aklogCredentialAtLoginTime setEnabled:[useAklogCheck state]];
711 @catch (NSException * e) {
712 [self showMessage:[e reason]];
719 // -------------------------------------------------------------------------------
720 // credentialAtLoginTimeEvent:
721 // -------------------------------------------------------------------------------
722 - (IBAction) credentialAtLoginTimeEvent:(id) sender {
724 [PListManager installLaunchdFile:[aklogCredentialAtLoginTime state]
725 resourcePath:[[self bundle] resourcePath]];
730 @catch (NSException * e) {
731 if([e userInfo] != nil && [[e userInfo] isKindOfClass:[NSNumber class]]) {
732 if([((NSNumber*)[e userInfo]) intValue] == 1) {
733 // the dir HOME_LAUNCHD_AGENT_FOLDER (PListManager.h) must be created
734 NSBeginAlertSheet([[NSString stringWithString:kDoYouWantCreateTheDirectory] stringByAppendingString:HOME_LAUNCHD_AGENT_FOLDER],
735 @"Create", @"Cancel", nil,
736 [[self mainView] window], self, @selector(credentialAtLoginTimeEventCreationLaunchAgentDir:returnCode:contextInfo:), NULL,
740 [self showMessage:[e reason]];
744 [aklogCredentialAtLoginTime setState:[PListManager checkAklogAtLoginTimeLaunchdEnable]];
749 // -------------------------------------------------------------------------------
750 // afsStartupSwitchEvent:
751 // -------------------------------------------------------------------------------
752 - (IBAction) afsStartupSwitchEvent:(id) sender {
753 NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
755 NSString *afsdPath = [TaskUtil searchExecutablePath:@"afsd"];
756 NSString *afsStartupScriptPath = [[self bundle] pathForResource:@"start_afs" ofType:@"sh"];
757 startAFSAtLogin = [checkButtonAfsAtBootTime state];
758 const char *startAfsArgs[] = {"load", "-w", [AFS_STARTUP_CONTROL_FILE UTF8String], 0L};
759 const char *stopAfsArgs[] = {"unload", "-w", [AFS_STARTUP_CONTROL_FILE UTF8String], 0L};
760 const char *launchctlExecutable = "/bin/launchctl";
761 /* [PListManager manageAfsStartupLaunchdFile:startAFSAtLogin
762 afsStartupScript:afsStartupScriptPath
763 afsBasePath:[afsProperty path] afsdPath:afsdPath];
765 const char *startupConfigureOption[] = {"start_afs_at_startup", [afsStartupScriptPath UTF8String], [afsdPath UTF8String], [[afsProperty path] UTF8String], 0L};
766 if([[AuthUtil shared] autorize] == noErr) {
767 if(startAFSAtLogin) {
768 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
769 args:startupConfigureOption
772 [[AuthUtil shared] execUnixCommand:launchctlExecutable
776 //now disable the launchd configuration
777 [[AuthUtil shared] execUnixCommand:launchctlExecutable
784 // -------------------------------------------------------------------------------
785 // credentialAtLoginTimeEventCreationLaunchAgentDir:
786 // -------------------------------------------------------------------------------
787 - (void) credentialAtLoginTimeEventCreationLaunchAgentDir:(NSWindow*)alert returnCode:(int)returnCode contextInfo:(void *)contextInfo {
789 switch (returnCode) {
792 if([[NSFileManager defaultManager] createDirectoryAtPath:[HOME_LAUNCHD_AGENT_FOLDER stringByExpandingTildeInPath]
796 [PListManager installLaunchdFile:YES
797 resourcePath:[[self bundle] resourcePath]];
799 //refresh the check box
800 [aklogCredentialAtLoginTime setState:[PListManager checkAklogAtLoginTimeLaunchdEnable]];
801 [self showMessage:kDirectoryCreated];
803 [self showMessage:kErrorCreatingDirectory];
813 // -------------------------------------------------------------------------------
814 // afsMenuActivationEvent:
815 // -------------------------------------------------------------------------------
816 - (IBAction) krb5KredentialAtLoginTimeEvent:(id) sender {
818 NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
819 const char *args[] = {"enable_krb5_startup", [[installKRB5AuthAtLoginButton stringValue] UTF8String], "", 0L};
822 [self repairHelperTool];
823 if([[AuthUtil shared] autorize] == noErr) {
824 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
828 //check if all is gone well
829 [installKRB5AuthAtLoginButton setState:[PListManager checkKrb5AtLoginTimeLaunchdEnable]];
833 // -------------------------------------------------------------------------------
834 // afsMenuActivationEvent:
835 // -------------------------------------------------------------------------------
836 -(IBAction) afsMenuActivationEvent:(id) sender
838 if([(NSButton*)afsMenucheckBox state] == NSOffState){
839 // must remove the menu
840 [self removeAFSMenuExtra];
843 [self addAFSMenuExtra];
847 // -------------------------------------------------------------------------------
848 // searchCellTextEvent:
849 // Fileter the CellServDB list according to NSSearch content
850 // -------------------------------------------------------------------------------
851 - (IBAction) searchCellTextEvent:(id) sender
854 NSString *searchText = [[textSearchField stringValue] lowercaseString]; //filter string
855 [self filterCellServDB:searchText];
856 [((NSTableView*)cellList) reloadData];
859 // -------------------------------------------------------------------------------
860 // clearCellServDBFiltering:
861 // clear the NSSearchField and showw all CellServDB table
862 // -------------------------------------------------------------------------------
863 - (void) clearCellServDBFiltering {
864 //Clear the text search
865 [textSearchField setStringValue:@""];
866 //load the temp array with all cell servdb
867 [self searchCellTextEvent:nil];
869 // --------------------------------------o-----------------------------------------
871 // make the NSMutableArray with all cellservdb or filtered element
872 // -------------------------------------------------------------------------------
873 - (void) filterCellServDB:(NSString*)textToFilter {
874 DBCellElement *cellElement; //Filtered element
875 BOOL doFilter = !(textToFilter == nil || ([textToFilter length] == 0));
877 // We can do filtering and make the temp array
879 [filteredCellDB release];
881 filteredCellDB = [[NSMutableArray alloc] init];
882 NSEnumerator *e = [[afsProperty getCellList] objectEnumerator];
883 while(cellElement = (DBCellElement*)[e nextObject]) {
884 // check if the element can be get
886 //Get the CellServDB array enumerator
887 //NSLog(@"String for filtering: %s", [textToFilter UTF8String]);
888 NSRange rsltRng = [[[cellElement getCellName] lowercaseString] rangeOfString:textToFilter];
889 if(rsltRng.location != NSNotFound) {
890 //we can add this cell to filtered
891 //NSLog(@"Element found during filter: %s", [[cellElement getCellName] UTF8String]);
892 [filteredCellDB addObject:[cellElement retain]];
895 [filteredCellDB addObject:[cellElement retain]];
901 // -------------------------------------------------------------------------------
902 // getCurrentCellInDB:
903 // -------------------------------------------------------------------------------
904 - (DBCellElement*) getCurrentCellInDB
906 int rowSelected = [((NSTableView *) cellList) selectedRow];
907 return [self getCellByIDX:rowSelected];
910 // -------------------------------------------------------------------------------
911 // getCurrentCellInDB:
912 // -------------------------------------------------------------------------------
913 - (DBCellElement*) getCellByIDX:(int) idx
915 //NSMutableArray *cellArray = [afsProperty getCellList];
916 DBCellElement *cellElement = (DBCellElement*)[filteredCellDB objectAtIndex:idx];
920 // -------------------------------------------------------------------------------
922 // -------------------------------------------------------------------------------
923 -(void) showMessage:(NSString*) message{
924 NSAlert *alert = [[NSAlert alloc] init];
926 [alert setMessageText:message];
927 [alert beginSheetModalForWindow:[[self mainView] window]
934 // -------------------------------------------------------------------------------
935 // manageButtonState:
936 // -------------------------------------------------------------------------------
937 -(void) manageButtonState:(int) rowSelected {
938 [((NSControl*) cellIpButton) setEnabled:rowSelected >= 0];
939 [((NSControl*) removeCellButton) setEnabled:rowSelected >= 0];
942 // -------------------------------------------------------------------------------
944 // -------------------------------------------------------------------------------
947 BOOL afsIsUp = [afsProperty checkAfsStatus];
948 NSLog(@"Afs is: %s", afsIsUp?"Up":"Down");
949 [((NSButton *)startStopButton) setTitle: (afsIsUp?kAfsButtonShutdown:kAfsButtonStartup)];
951 NSMutableAttributedString *colorTitle =[[NSMutableAttributedString alloc] initWithAttributedString:[((NSButton *)startStopButton) attributedTitle]];
952 NSRange titleRange = NSMakeRange(0, [colorTitle length]);
954 [colorTitle addAttribute:NSForegroundColorAttributeName
955 value:(afsIsUp?[NSColor redColor]:[NSColor blackColor])
958 [((NSButton *)startStopButton) setAttributedTitle:colorTitle];
967 // -------------------------------------------------------------------------------
969 // -------------------------------------------------------------------------------
970 - (void) refreshTokens:(NSTimer*)theTimer;
972 if(![tokensLock tryLock]) return;
977 tokenList = [afsProperty getTokenList];
978 [((NSTableView*)tokensTable) reloadData];
983 // -------------------------------------------------------------------------------
984 // isExtraMenuLoaded:
985 // -------------------------------------------------------------------------------
986 - (BOOL) isAFSMenuExtraLoaded
989 if ((CoreMenuExtraGetMenuExtra((CFStringRef)kAFSMenuExtraID, &menu) == 0) && menu) {
997 // -------------------------------------------------------------------------------
998 // isExtraMenuLoaded:
999 // -------------------------------------------------------------------------------
1000 - (void)addAFSMenuExtra {
1002 void *menuCracker = 0L;
1004 //Check for MenuCracker
1005 if ((CoreMenuExtraGetMenuExtra((CFStringRef)kMenuCrakerMenuExtraID, &menuCracker) != 0) || !menuCracker) {
1006 NSLog(@"MenuCracker not present");
1008 // load the MenuCracker.menu menu extra
1009 CoreMenuExtraAddMenuExtra((CFURLRef)kMenuCrakerMenuExtra, 0, 0, 0, 0, 0);
1010 } else NSLog(@"MenuCracker alredy loaded");
1013 //Load the AFSCommander menu extra
1014 CoreMenuExtraAddMenuExtra((CFURLRef)kAFSMenuExtra, 0, 0, 0, 0, 0);
1017 // -------------------------------------------------------------------------------
1019 // -------------------------------------------------------------------------------
1020 - (IBAction) addLink:(id) sender {
1021 [NSBundle loadNibNamed:@"SymLinkEdit" owner:self];
1023 [NSApp beginSheet: lyncCreationSheet
1024 modalForWindow: [[self mainView] window]
1026 didEndSelector: @selector(didEndSymlinkSheet:returnCode:contextInfo:)
1031 // -------------------------------------------------------------------------------
1033 // -------------------------------------------------------------------------------
1034 - (IBAction) removeLink:(id) sender {
1038 // -------------------------------------------------------------------------------
1040 // -------------------------------------------------------------------------------
1041 - (IBAction) enableLink:(id) sender {
1046 // -------------------------------------------------------------------------------
1048 // -------------------------------------------------------------------------------
1049 - (void)removeAFSMenuExtra{
1051 if ((CoreMenuExtraGetMenuExtra((CFStringRef)kAFSMenuExtraID, &menu) == 0) && menu) {
1052 CoreMenuExtraRemoveMenuExtra(menu, 0);
1057 // -------------------------------------------------------------------------------
1058 // mextraChangeActivation:
1059 // -------------------------------------------------------------------------------
1060 - (void)mextraChangeActivation:(NSNotification *)notification
1062 // set the afsmenu check state
1063 [(NSButton*)afsMenucheckBox setState: [self isAFSMenuExtraLoaded]?NSOnState:NSOffState];
1067 @implementation AFSCommanderPref (NSTableDataSource)
1070 // -------------------------------------------------------------------------------
1072 // Manage the checkbox of CellServDB Table
1074 // -------------------------------------------------------------------------------
1075 - (void)tableView:(NSTableView *)table
1076 setObjectValue:(id)data
1077 forTableColumn:(NSTableColumn *)col
1080 NSString *identifier = (NSString*)[col identifier];
1081 switch([table tag]){
1082 case TABLE_TOKENS_LIST:
1085 case TABLE_CELL_LIST:
1086 // we are editing checkbox for cellservdb table
1087 if([identifier intValue] == CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN) {
1088 // set the user default cell
1089 DBCellElement *cellElement = (DBCellElement*)[filteredCellDB objectAtIndex:row];
1090 [afsProperty setDefaultCellByName:[cellElement getCellName]];
1091 //[afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
1092 [((NSTableView*)cellList) reloadData];
1093 } else if([identifier intValue] == CELLSRVDB_TABLE_DFLT_CHECK_COLUMN) {
1094 // set the cell for wich the user want to get token
1095 DBCellElement *cellElement = (DBCellElement*)[filteredCellDB objectAtIndex:row];
1096 [cellElement setUserDefaultForToken:![cellElement userDefaultForToken]];
1104 // -------------------------------------------------------------------------------
1106 // refresh delegate method for two AFSCommander table
1107 // -------------------------------------------------------------------------------
1108 - (id) tableView:(NSTableView *) aTableView
1109 objectValueForTableColumn:(NSTableColumn *) aTableColumn
1114 NSString *identifier = (NSString*)[aTableColumn identifier];
1115 switch([aTableView tag]){
1116 case TABLE_TOKENS_LIST:
1117 //We are refreshing tokens table
1118 result = [self getTableTokensListValue:[identifier intValue] row:rowIndex];
1121 case TABLE_CELL_LIST:
1122 //We are refreshing cell db table
1123 result = [self getTableCelListValue:[identifier intValue] row:rowIndex];
1131 // -------------------------------------------------------------------------------
1132 // getTableCelListValue:
1133 // -------------------------------------------------------------------------------
1134 - (id)getTableTokensListValue:(int) colId row:(int)row
1137 if(!tokenList) return nil;
1140 result = (NSString*)[tokenList objectAtIndex:row];
1147 // -------------------------------------------------------------------------------
1148 // getTableCelListValue:
1149 // -------------------------------------------------------------------------------
1150 - (id)getTableCelListValue:(int) colId row:(int)row
1153 //NSMutableArray *cellArray = [afsProperty getCellList];
1154 DBCellElement *cellElement = (DBCellElement*)[filteredCellDB objectAtIndex:row];
1156 case CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN:
1157 result = [NSNumber numberWithInt:[cellElement userDefaultForCell]];
1160 case CELLSRVDB_TABLE_DFLT_CHECK_COLUMN:
1161 result = [NSNumber numberWithInt:[cellElement userDefaultForToken]];
1163 case CELLSRVDB_TABLE_NAME_COLUMN:
1164 result = [cellElement getCellName];
1167 case CELLSRVDB_TABLE_DESCRIPTION_COLUMN:
1168 result = [cellElement getCellComment];
1174 // -------------------------------------------------------------------------------
1175 // numberOfRowsInTableView:
1176 // -------------------------------------------------------------------------------
1177 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
1180 //NSMutableArray *cellArray = nil;
1181 switch([aTableView tag]){
1182 case TABLE_TOKENS_LIST:
1183 if(tokenList) rowCount = [tokenList count];
1186 case TABLE_CELL_LIST:
1187 //cellArray = [afsProperty getCellList];
1188 if(filteredCellDB) rowCount = [filteredCellDB count];
1199 @implementation AFSCommanderPref (TableDelegate)
1200 // -------------------------------------------------------------------------------
1201 // selectionShouldChangeInTableView:
1202 // -------------------------------------------------------------------------------
1203 - (BOOL)selectionShouldChangeInTableView:(NSTableView *)aTable
1205 [self manageButtonState:[aTable selectedRow]];
1209 // -------------------------------------------------------------------------------
1211 // -------------------------------------------------------------------------------
1212 - (BOOL)tableView:(NSTableView *)aTable shouldSelectRow:(int)aRow
1214 [self manageButtonState:aRow];
1221 @implementation AFSCommanderPref (ModalDelegate)
1222 // -------------------------------------------------------------------------------
1224 // -------------------------------------------------------------------------------
1225 - (void)didEndSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1227 NSLog(@"didEndSheet");
1228 [sheet orderOut:self];
1229 //Filter the cellServDb and allocate filtered array
1230 [self searchCellTextEvent:nil];
1231 [((NSTableView*)cellList) reloadData];
1232 NSLog(@"Has saved %s:", ([((IpConfiguratorCommander*) ipConfControllerCommander) saved])?"YES":"NO");
1235 // -------------------------------------------------------------------------------
1236 // Klog credential request
1237 // -------------------------------------------------------------------------------
1238 - (void)didEndCredentialSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1240 NSLog(@"didEndCredentialSheet");
1241 if([((TokenCredentialController*)credentialCommander) takenToken] == YES){
1242 /*[AFSPropertyManager klog:[((TokenCredentialController*)credentialCommander) uName]
1243 uPwd:[((TokenCredentialController*)credentialCommander) uPwd] ];*/
1244 [afsProperty getTokens:true
1245 usr:[((TokenCredentialController*)credentialCommander) uName]
1246 pwd:[((TokenCredentialController*)credentialCommander) uPwd]];
1248 [sheet orderOut:self];
1249 [self refreshTokens:nil];
1250 //Inform afs menuextra to updata afs status
1251 if ([self isAFSMenuExtraLoaded]) [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
1255 // -------------------------------------------------------------------------------
1256 // Klog credential request
1257 // -------------------------------------------------------------------------------
1258 - (void)didEndInfoSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1260 NSLog(@"didEndInfoSheet");
1261 [sheet orderOut:self];
1264 // -------------------------------------------------------------------------------
1266 // -------------------------------------------------------------------------------
1267 - (void)didEndSymlinkSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1269 NSLog(@"didEndSymlinkSheet");
1270 [lyncCreationSheet orderOut:self];
1274 // -------------------------------------------------------------------------------
1275 // AFSCommanderPref(NSTabViewDelegator) - delegate for nstabview in
1276 // main preference view
1277 // -------------------------------------------------------------------------------
1278 @implementation AFSCommanderPref(NSTabViewDelegator)
1279 - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem
1281 //check to see if the cache param tab is the tab that will be selected
1282 if([((NSString*)[tabViewItem identifier]) intValue] == TAB_GROUP)
1285 NSLog(@"cache param tab");
1286 // [groupsBox setHidden:YES];
1287 NSLog([groupsBox title]);
1288 [ViewUtility enbleDisableControlView:[groupsBox contentView]