OSX prefspane use Kerberos Preferences for defaults
[openafs.git] / src / platform / DARWIN / AFSPreference / AFSCommanderPref.m
1 //
2 //  AFSCommanderPref.m
3 //  AFSCommander
4 //
5 //  Created by Claudio Bisegni on 10/05/07.
6 //  Copyright (c) 2007 INFN - National Institute of Nuclear Physics. All rights reserved.
7 //
8
9 #import "AFSCommanderPref.h"
10 #import "IpConfiguratorCommander.h"
11 #import "TokenCredentialController.h"
12 #import "InfoController.h"
13 #import "TaskUtil.h"
14 #import "PListManager.h"
15 #import "DialogUtility.h"
16 #import "NSString+search.h"
17 #include <sys/param.h>
18 #include <sys/stat.h>
19 #include <sys/wait.h>
20 #include <sys/types.h>
21 #include <sys/fcntl.h>
22 #include <sys/errno.h>
23 #include <unistd.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #import <CoreServices/CoreServices.h>
27
28
29 #define ADD_CELL_CONTROL_TAG 1
30 #define REMOVE_CELL_CONTROL_TAG 2
31
32 #define TABLE_TOKENS_LIST 1
33 #define TABLE_CELL_LIST 2
34 #define TABLE_LINK_LIST 3
35
36 #define TAB_TOKENS 1
37 #define TAB_CELL_SERV_DB 2
38 #define TAB_CACHE 3
39 #define TAB_LINK 4
40
41 //CellServDB table id
42 #define CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN   0
43 #define CELLSRVDB_TABLE_DFLT_CHECK_COLUMN               1
44 #define CELLSRVDB_TABLE_NAME_COLUMN                             2
45 #define CELLSRVDB_TABLE_DESCRIPTION_COLUMN              3
46
47 //Link Table
48 #define TABLE_COLUMN_LINK_NAME  0
49 #define TABLE_COLUMN_LINK_PATH  1
50
51
52 @implementation AFSCommanderPref
53
54 // -------------------------------------------------------------------------------
55 //  initWithBundle:
56 // -------------------------------------------------------------------------------
57 - (id)initWithBundle:(NSBundle *)bundle
58 {
59     if ( ( self = [super initWithBundle:bundle] ) != nil ) {
60         //appID = kAfsCommanderID;
61                 prefStartUp = 1;
62     }
63     return self;
64 }
65
66 // -------------------------------------------------------------------------------
67 //  mainView:
68 // -------------------------------------------------------------------------------
69 - (NSView *) mainView {
70         if (prefStartUp == 1){
71                 SInt32 osxMJVers = 0;
72                 SInt32 osxMnVers = 0;
73                 if (Gestalt(gestaltSystemVersionMajor, &osxMJVers) == noErr && Gestalt(gestaltSystemVersionMinor, &osxMnVers) == noErr) {
74                         if (osxMJVers == 10 && osxMnVers>= 5) {
75                                 [afsCommanderView  setFrameSize:NSMakeSize(668, [afsCommanderView frame].size.height)];
76                 prefStartUp = 0;
77                         }
78                 }
79         }
80         
81     return afsCommanderView;
82 }
83
84 // -------------------------------------------------------------------------------
85 //  mainViewDidLoad:
86 // -------------------------------------------------------------------------------
87 - (void) mainViewDidLoad
88 {
89         //CellServDB Table
90         [((NSTableView*)cellList) setDelegate:self];
91         [((NSTableView*)cellList) setTarget:self];
92         [((NSTableView*)cellList) setDoubleAction:@selector(tableDoubleAction:)];
93         
94         
95 }
96
97 // -------------------------------------------------------------------------------
98 //  didSelect:
99 // -------------------------------------------------------------------------------
100 - (void) didSelect
101 {
102         //try to install the launchd file for backgrounder
103         //Remove launchd ctrl file
104         @try {
105                 [PListManager installBackgrounderLaunchdFile:YES 
106                                                                                 resourcePath:[[self bundle] resourcePath]];
107         }
108         @catch (NSException * e) {
109                 NSDictionary *excecptDic = [e userInfo];
110                 NSNumber *keyNum = [excecptDic objectForKey:@"agent_folder_error"];
111                 if(keyNum && [keyNum boolValue]) {
112                         // the dir HOME_LAUNCHD_AGENT_FOLDER (PListManager.h) must be created
113                         NSBeginAlertSheet([[NSString stringWithString:kDoYouWantCreateTheDirectory] stringByAppendingString:HOME_LAUNCHD_AGENT_FOLDER],
114                                                           @"Create", @"Cancel", nil,                                                                            
115                                                           [[self mainView] window],     self, @selector(credentialAtLoginTimeEventCreationLaunchAgentDir:returnCode:contextInfo:), NULL, 
116                                                           nil, @"", nil);
117                 }
118         }
119         @finally {
120                 
121         }
122         
123         
124         // Set Developer info
125         [textFieldDevInfoLabel setStringValue:kDevelopInfo];
126         // creating the lock
127         tokensLock = [[NSLock alloc] init];
128         
129         //Initialization cellservdb and token list
130         filteredCellDB = nil;
131         tokenList = nil;
132         
133         [self readPreferenceFile];
134                         
135         // alloc the afs property mananger
136         afsProperty = [[AFSPropertyManager alloc] init];
137         
138         // register preference pane to detect menuextra killed by user
139         [[NSDistributedNotificationCenter defaultCenter] addObserver:self
140                                                                                                                 selector:@selector(refreshTokensNotify:)
141                                                                                                                         name:kAfsCommanderID
142                                                                                                                   object:kMExtraTokenOperation];
143          
144         [[NSDistributedNotificationCenter defaultCenter] addObserver:self 
145                                                                                                                 selector:@selector(refreshGui:) 
146                                                                                                                         name:kAfsCommanderID 
147                                                                                                                   object:kMenuExtraEventOccured];
148         
149         //Register for mount/unmount afs volume
150         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self 
151                                                                                                                    selector:@selector(afsVolumeMountChange:) 
152                                                                                                                            name:NSWorkspaceDidMountNotification object:nil];
153         
154         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self 
155                                                                                                                    selector:@selector(afsVolumeMountChange:) 
156                                                                                                                            name:NSWorkspaceDidUnmountNotification object:nil];
157         
158         // set self as table data source
159         [cellList setDataSource:self];
160         [tokensTable setDataSource:self];
161         //[tableViewLink setDataSource:self];
162         //check the afs state
163         [self setAfsStatus];
164         
165         // let show the configuration after prefpane is open
166         [self refreshConfiguration:nil];
167         
168         // refresh the token list
169         //[self refreshTokens:nil];
170         
171         //refresh table to reflect the NSSearchField contained text
172         [self searchCellTextEvent:nil];
173 }
174
175 // -------------------------------------------------------------------------------
176 //  credentialAtLoginTimeEventCreationLaunchAgentDir:
177 // -------------------------------------------------------------------------------
178 - (void) credentialAtLoginTimeEventCreationLaunchAgentDir:(NSWindow*)alert returnCode:(int)returnCode contextInfo:(void *)contextInfo {
179         [alert close];
180         switch (returnCode) {
181                 case  1:
182                         if([[NSFileManager defaultManager] createDirectoryAtPath:[HOME_LAUNCHD_AGENT_FOLDER stringByExpandingTildeInPath] 
183                                                                                  withIntermediateDirectories:NO
184                                                                                                                   attributes:nil
185                                                                                                                            error:nil]) {
186                                 
187                                 //Create the file
188                                 [PListManager installBackgrounderLaunchdFile:YES
189                                                                                                 resourcePath:[[self bundle] resourcePath]];
190                                 [self showMessage:kDirectoryCreated];
191                         } else {
192                                 [self showMessage:kErrorCreatingDirectory];
193                         }
194                         break;
195                 case 0:
196                         break;
197         }
198 }
199
200
201 // -------------------------------------------------------------------------------
202 //  willUnselect:
203 // -------------------------------------------------------------------------------
204 - (void)willUnselect
205 {
206         // remove self as datasource
207         [((NSTableView*)cellList) setDataSource:nil];
208         [((NSTableView*)tokensTable) setDataSource:nil];
209
210         //release the afs property manager
211         if(afsProperty) [afsProperty release];
212         //release tokens list
213         if(tokenList) [tokenList release];      
214         //Remove the cell temp array
215         if(filteredCellDB) [filteredCellDB release];
216         
217         [self writePreferenceFile];
218         
219         // unregister preference pane to detect menuextra killed by user
220         [[NSDistributedNotificationCenter defaultCenter] removeObserver:self
221                                                                                                                            name:kAfsCommanderID
222                                                                                                                          object:kMExtraClosedNotification];
223         [[NSDistributedNotificationCenter defaultCenter] removeObserver:self
224                                                                                                                            name:kAfsCommanderID
225                                                                                                                          object:kMExtraTokenOperation];
226         [[NSDistributedNotificationCenter defaultCenter] removeObserver:self
227                                                                                                                            name:kAfsCommanderID
228                                                                                                                          object:kMenuExtraEventOccured];
229         [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self 
230                                                                                                                                   name:NSWorkspaceDidMountNotification object:nil];
231         [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self 
232                                                                                                                                   name:NSWorkspaceDidUnmountNotification object:nil];
233         
234         [self stopTimer];
235         [tokensLock release];
236 }
237
238
239 // -------------------------------------------------------------------------------
240 //  startTimer:
241 // -------------------------------------------------------------------------------
242 - (void)startTimer{
243         //start the time for check tokens validity
244         if(timerForCheckTokensList) return;
245         timerForCheckTokensList = [NSTimer scheduledTimerWithTimeInterval:TOKENS_REFRESH_TIME_IN_SEC 
246                                                                                                                            target:self 
247                                                                                                                          selector:@selector(refreshTokens:) 
248                                                                                                                          userInfo:nil 
249                                                                                                                           repeats:YES];
250         [timerForCheckTokensList fire]; 
251 }
252
253 // -------------------------------------------------------------------------------
254 //  stopTimer:
255 // -------------------------------------------------------------------------------
256 - (void)stopTimer{
257         if(!timerForCheckTokensList) return;
258         [timerForCheckTokensList invalidate];   
259         timerForCheckTokensList = nil;
260 }
261
262
263 // -------------------------------------------------------------------------------
264 //  readPreferenceFile:
265 // -------------------------------------------------------------------------------
266 - (void) readPreferenceFile
267 {
268         // read the preference for aklog use
269         NSNumber *useAklogPrefValue = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_USE_AKLOG, (CFStringRef)kAfsCommanderID,  
270                                                                                                                                         kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
271         NSNumber *aklogTokenAtLogin = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_AKLOG_TOKEN_AT_LOGIN, (CFStringRef)kAfsCommanderID,  
272                                                                                                                                         kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
273         [useAklogCheck setState:[useAklogPrefValue intValue]];
274         [aklogCredentialAtLoginTime setEnabled:useAklogPrefValue && [useAklogPrefValue boolValue]];
275         [aklogCredentialAtLoginTime setState:aklogTokenAtLogin && [aklogTokenAtLogin boolValue]];
276
277         //check krb5 at login time
278         [installKRB5AuthAtLoginButton setState:[PListManager checkKrb5AtLoginTimeLaunchdEnable]];
279
280         //check for AFS enable at startup
281         NSNumber *afsEnableStartupTime = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_START_AFS_AT_STARTUP,
282                                                                                                                                            (CFStringRef)kAfsCommanderID,  kCFPreferencesAnyUser, kCFPreferencesAnyHost);
283         if(afsEnableStartupTime)
284                 startAFSAtLogin = [afsEnableStartupTime boolValue];
285         else 
286                 startAFSAtLogin = false;
287         //set the check button state
288         [checkButtonAfsAtBootTime setState:startAFSAtLogin];
289         
290         NSNumber *showStatusMenu =  (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_SHOW_STATUS_MENU,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
291         [(NSButton*)afsMenucheckBox setState: [showStatusMenu boolValue]];
292         
293         //backgrounder state
294         [backgrounderActivationCheck setState:[PListManager launchdJobState:BACKGROUNDER_P_FILE]];
295         
296         //link enabled status
297         NSNumber *linkEnabledStatus =  (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_USE_LINK,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
298         [checkEnableLink setState:[linkEnabledStatus boolValue]];
299         
300         //check the user preference for manage the renew
301         NSNumber *checkRenew =  (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_KRB5_CHECK_ENABLE,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
302         if(checkRenew)[nsButtonEnableDisableKrb5RenewCheck setState:[checkRenew intValue]];
303
304         NSNumber *renewTime = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_KRB5_RENEW_TIME,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
305         if(!renewTime) renewTime = [NSNumber numberWithInt:PREFERENCE_KRB5_RENEW_TIME_DEFAULT_VALUE];
306
307                 //update gui
308         NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
309         NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) 
310                                                                                                            fromDate:[NSDate dateWithTimeIntervalSince1970:[renewTime intValue]]];
311         [nsTextFieldKrb5RenewTimeD setIntValue:[weekdayComponents day]-1];
312         [nsTextFieldKrb5RenewTimeH setIntValue:[weekdayComponents hour]-1];
313         [nsTextFieldKrb5RenewTimeM setIntValue:[weekdayComponents minute]];
314         [nsTextFieldKrb5RenewTimeS setIntValue:[weekdayComponents second]];
315         [nsStepperKrb5RenewTimeD setIntValue:[weekdayComponents day]-1];
316         [nsStepperKrb5RenewTimeH setIntValue:[weekdayComponents hour]-1];
317         [nsStepperKrb5RenewTimeM setIntValue:[weekdayComponents minute]];
318         [nsStepperKrb5RenewTimeS setIntValue:[weekdayComponents second]];
319
320         NSNumber *renewCheckTimeInterval = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_KRB5_RENEW_CHECK_TIME_INTERVALL,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
321         if(renewCheckTimeInterval && [renewCheckTimeInterval intValue])[nsTextFieldKrb5RenewCheckIntervall setIntValue:[renewCheckTimeInterval intValue]];
322         else [nsTextFieldKrb5RenewCheckIntervall setIntValue:PREFERENCE_KRB5_RENEW_CHECK_TIME_INTERVALL_DEFAULT_VALUE];
323
324         NSNumber *expireTimeForRenew = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_KRB5_SEC_TO_EXPIRE_TIME_FOR_RENEW,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
325         if(expireTimeForRenew && [expireTimeForRenew intValue])[nsTextFieldKrb5SecToExpireDateForRenew setIntValue:[expireTimeForRenew intValue]];
326         else [nsTextFieldKrb5SecToExpireDateForRenew setIntValue:PREFERENCE_KRB5_SEC_TO_EXPIRE_TIME_FOR_RENEW_DEFAULT_VALUE];
327
328         //link configuration
329         NSData *prefData = (NSData*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_LINK_CONFIGURATION,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
330         linkConfiguration = (NSMutableDictionary*)[NSPropertyListSerialization propertyListFromData:prefData
331                                                                                                                                                            mutabilityOption:NSPropertyListMutableContainers
332                                                                                                                                                                                  format:nil
333                                                                                                                                                            errorDescription:nil];
334         
335 }
336
337 // -------------------------------------------------------------------------------
338 //  willUnselect:
339 // -------------------------------------------------------------------------------
340 - (void) writePreferenceFile
341 {
342         //Set the preference for afs path
343         //Set the preference for aklog use
344         CFPreferencesSetValue((CFStringRef)PREFERENCE_USE_AKLOG, 
345                                                   (CFNumberRef)[NSNumber numberWithInt:[useAklogCheck state]], 
346                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
347
348         //set AFS enable state at startup
349         CFPreferencesSetValue((CFStringRef)PREFERENCE_START_AFS_AT_STARTUP, 
350                                                   (CFNumberRef)[NSNumber numberWithBool:startAFSAtLogin], 
351                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
352         
353         //set aklog at login
354         CFPreferencesSetValue((CFStringRef)PREFERENCE_AKLOG_TOKEN_AT_LOGIN, 
355                                                   (CFNumberRef)[NSNumber numberWithBool:[aklogCredentialAtLoginTime state]], 
356                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
357         
358         //set aklog at login
359         CFPreferencesSetValue((CFStringRef)PREFERENCE_SHOW_STATUS_MENU, 
360                                                   (CFNumberRef)[NSNumber numberWithBool:[(NSButton*)afsMenucheckBox state]],
361                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
362         
363         //preference for link
364         CFPreferencesSetValue((CFStringRef)PREFERENCE_USE_LINK,
365                                                   (CFNumberRef)[NSNumber numberWithBool:[checkEnableLink state]], 
366                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
367         
368                 //preference for renew time
369         NSLog(@"%d %d %d %d", [nsTextFieldKrb5RenewTimeD intValue],[nsTextFieldKrb5RenewTimeH intValue],[nsTextFieldKrb5RenewTimeM intValue],[nsTextFieldKrb5RenewTimeS intValue]);
370         NSInteger totalSeconds =        ([nsTextFieldKrb5RenewTimeD intValue]*24*60*60)+
371                                                                 ([nsTextFieldKrb5RenewTimeH intValue]*60*60)+
372                                                                 ([nsTextFieldKrb5RenewTimeM intValue]*60)+
373                                                                 [nsTextFieldKrb5RenewTimeS intValue];
374
375         CFPreferencesSetValue((CFStringRef)PREFERENCE_KRB5_RENEW_TIME,
376                                                   (CFNumberRef)[NSNumber numberWithInt:totalSeconds],
377                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
378
379                 //expire time for renew
380         CFPreferencesSetValue((CFStringRef)PREFERENCE_KRB5_SEC_TO_EXPIRE_TIME_FOR_RENEW,
381                                                   (CFNumberRef)[NSNumber numberWithInt:[nsTextFieldKrb5SecToExpireDateForRenew intValue]],
382                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
383
384                 //sec to expiretime for renew job
385         CFPreferencesSetValue((CFStringRef)PREFERENCE_KRB5_RENEW_CHECK_TIME_INTERVALL,
386                                                   (CFNumberRef)[NSNumber numberWithInt:[nsTextFieldKrb5RenewCheckIntervall intValue]],
387                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
388
389         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesAnyUser, kCFPreferencesAnyHost);
390         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
391         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kPrefChangeNotification];
392 }
393
394 // -------------------------------------------------------------------------------
395 //  saveConfiguration:
396 // -------------------------------------------------------------------------------
397 - (IBAction) saveConfiguration:(id) sender
398 {
399         @try{
400                 
401                 //[afsProperty setCellName:[cellNameTextEdit stringValue]];
402                 [afsProperty setCellName:[afsProperty getDefaultCellName]];
403                 
404                 //save configurations
405                 [afsProperty saveConfigurationFiles:YES];
406                 
407                 
408                 //Reload all configuration
409                 [self refreshConfiguration:nil];
410                 
411                 //refresh table to reflect the NSSearchField contained text
412                 [self searchCellTextEvent:nil];
413                 
414                 //Show dialog for notifity al saving process ar gone ell
415                 [self showMessage:kConfigurationSaved];
416         }@catch(NSException *e){
417                 [self showMessage:[e reason]];
418         } @finally {
419                 [((NSTableView*)cellList) reloadData];
420         }
421         
422 }
423
424 // -------------------------------------------------------------------------------
425 //  saveCacheManagerParam:
426 // -------------------------------------------------------------------------------
427 - (IBAction) saveCacheManagerParam:(id) sender
428 {
429         @try{
430                 //Update the value form view to afs property manager class
431                 [self updateCacheParamFromView];
432                 [afsProperty saveCacheConfigurationFiles:YES];
433                 [self showMessage:kSavedCacheConfiguration];
434         }@catch(NSException *e){
435                 [self showMessage:[e reason]];
436         } @finally {
437                 [((NSTableView*)cellList) reloadData];
438         }
439 }
440
441 // -------------------------------------------------------------------------------
442 //  refreshConfiguration:
443 // -------------------------------------------------------------------------------
444 - (IBAction) refreshConfiguration:(id) sender
445 {
446         NSString *afsBasePath = PREFERENCE_AFS_SYS_PAT_STATIC;
447         @try{
448                 // set the afs path
449                 [afsProperty setPath:afsBasePath];
450                 
451                 // load configuration
452                 [afsProperty loadConfiguration];
453                 
454                 //set the afs version label
455                 [afsVersionLabel setStringValue:[afsProperty getAfsVersion]];
456                 
457                 //set the current default cell
458                 [afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
459                 
460                 // Update cache view
461                 [self fillCacheParamView];
462                 
463                 //Filter the cellServDb and allocate filtered array
464                 [self filterCellServDB:nil];
465                 
466         }@catch(NSException *e){
467                 [self showMessage:[e reason]];
468         } @finally {
469                 [((NSTableView*)cellList) reloadData];
470         }
471 }
472
473 // -------------------------------------------------------------------------------
474 //  fillCacheParamView:
475 // -------------------------------------------------------------------------------
476 -(void) fillCacheParamView
477 {
478         [dynRoot setState:[afsProperty dynRoot]?NSOnState:NSOffState];
479         [afsDB setState:[afsProperty afsDB]?NSOnState:NSOffState];
480         [statCacheEntry setIntValue:[afsProperty statCacheEntry]];
481         [dCacheDim setIntValue:[afsProperty dCacheDim]];
482         [cacheDimension setIntValue:[afsProperty cacheDimension]];
483         [daemonNumber setIntValue:[afsProperty daemonNumber]];
484         [afsRootMountPoint setStringValue:[afsProperty afsRootMountPoint]];
485         [nVolEntry setIntValue:[afsProperty nVolEntry]];
486         
487         //new version property
488         //[verbose setEnabled:[afsProperty useAfsdConfConfigFile]];
489         [verbose setState:[afsProperty verbose]?NSOnState:NSOffState];
490         
491 }
492
493 // -------------------------------------------------------------------------------
494 //  updateCacheParamFromView:
495 // -------------------------------------------------------------------------------
496 -(void) updateCacheParamFromView
497 {
498         NSString *tmpAfsPath = [afsRootMountPoint stringValue];
499         if(!tmpAfsPath || ([tmpAfsPath length] == 0) || ([tmpAfsPath characterAtIndex:0] != '/')) 
500                 @throw [NSException exceptionWithName:@"updateCacheParamFromView" 
501                                                                            reason:kBadAfsRootMountPoint
502                                                                          userInfo:nil];
503
504         
505         [afsProperty setDynRoot:[dynRoot state]==NSOnState];
506         [afsProperty setAfsDB:[afsDB state]==NSOnState];
507         [afsProperty setStatCacheEntry:[statCacheEntry intValue]];
508         [afsProperty setDCacheDim:[dCacheDim intValue]]; 
509         [afsProperty setCacheDimension:[cacheDimension intValue]]; 
510         [afsProperty setDaemonNumber:[daemonNumber intValue]];
511         [afsProperty setAfsRootMountPoint:tmpAfsPath];
512         [afsProperty setNVolEntry:[nVolEntry intValue]];
513         [afsProperty setVerbose:[verbose state]==NSOnState];
514 }
515
516
517 // -------------------------------------------------------------------------------
518 //  showCellIP:
519 // -------------------------------------------------------------------------------
520 - (IBAction) showCellIP:(id) sender
521 {
522         int rowSelected = [((NSTableView *) cellList) selectedRow];
523         [self modifyCellByIDX:rowSelected];
524 }
525
526 // -------------------------------------------------------------------------------
527 //  modifyCellByIDX:
528 // -------------------------------------------------------------------------------
529 -(void) modifyCellByIDX:(int) idx
530 {
531         [self modifyCell:[self getCellByIDX:idx]];
532 }
533
534 // -------------------------------------------------------------------------------
535 //  modifyCellByIDX:
536 // -------------------------------------------------------------------------------
537 -(void) modifyCell:(DBCellElement*) cellElement
538 {
539         [NSBundle loadNibNamed:@"IpPanel" owner:self];
540         [((IpConfiguratorCommander*) ipConfControllerCommander) setWorkCell:cellElement];
541         [NSApp beginSheet: ipConfigurationSheet
542            modalForWindow: [[self mainView] window]
543                 modalDelegate: self
544            didEndSelector: @selector(didEndSheet:returnCode:contextInfo:)
545                   contextInfo: nil];
546 }
547
548 // -------------------------------------------------------------------------------
549 //  addMoifyCell:
550 // -------------------------------------------------------------------------------
551 - (IBAction) addRemoveCell:(id) sender
552 {
553         switch([((NSControl*) sender) tag]){
554                 case ADD_CELL_CONTROL_TAG:
555                 {
556                         DBCellElement *newCell = [[DBCellElement alloc] init];
557                         if(!newCell) break;
558                         
559                         [newCell setCellName:kNewCellName];
560                         [newCell setCellComment:kNewCellComment];
561                         //cellArray = ;
562                         [[afsProperty getCellList] addObject:newCell];
563                         [newCell release];
564                         
565                         //Modify new cell
566                         [self modifyCell:newCell];
567                 }
568                 break;
569                         
570                 case REMOVE_CELL_CONTROL_TAG:
571                 {
572                         int index = 0;
573                         NSIndexSet *selectedIndex = [(NSTableView*)cellList selectedRowIndexes];
574                         if( [selectedIndex count] > 0) {
575                                 index = [selectedIndex firstIndex]; 
576                                 do {
577                                         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:index];
578                                         [[afsProperty getCellList] removeObject:cellElement];
579                                 } while ((index = [selectedIndex indexGreaterThanIndex:index]) != NSNotFound);
580                         }
581                 }
582                 break;
583         }
584         //Filter the cellServDb and allocate filtered array
585         [self searchCellTextEvent:nil];
586         [(NSTableView*)cellList deselectAll:nil];
587         [(NSTableView*)cellList reloadData];
588 }
589
590 // -------------------------------------------------------------------------------
591 //  repairHelperTool:
592 // -------------------------------------------------------------------------------
593 - (void) repairHelperTool
594 {
595         struct stat st;
596     int fdTool;
597         int status = 0;
598         NSLog(@"repairHelperTool"); 
599         NSString *afshlpPath = [[self bundle] pathForResource:@"afshlp" ofType:nil];
600         
601         
602     
603     // Open tool exclusively, so nobody can change it while we bless it.
604     fdTool = open([afshlpPath UTF8String], O_NONBLOCK | O_RDONLY | O_EXLOCK, 0);
605     
606     if(fdTool == -1)
607     {
608         NSLog(@"Exclusive open while repairing tool failed: %d.", errno);
609         exit(-1);
610     }
611     
612     if(fstat(fdTool, &st))
613     {
614         NSLog(@"fstat failed.");
615         exit(-1);
616     }
617     
618     if(st.st_uid != 0)
619     {
620                 status = [[AuthUtil shared] autorize];
621                 if(status == noErr){
622                         fchown(fdTool, 0, st.st_gid);
623                         
624                         // Disable group and world writability and make setuid root.
625                         fchmod(fdTool, (st.st_mode & (~(S_IWGRP | S_IWOTH)))/* | S_ISUID*/);
626                         const char *args[] = {"root", [afshlpPath UTF8String],0L};
627                         [[AuthUtil shared] execUnixCommand:"/usr/sbin/chown" 
628                                                                                   args:args
629                                                                                 output:nil];
630                         [[AuthUtil shared] deautorize];
631                 }
632     } else  NSLog(@"st_uid = 0");
633     
634         
635     
636     close(fdTool);
637     
638     NSLog(@"Self-repair done.");
639         
640 }
641
642
643 // -------------------------------------------------------------------------------
644 //  startStopAfs:
645 // -------------------------------------------------------------------------------
646 - (IBAction) startStopAfs:(id) sender
647 {
648         BOOL currentAfsState = NO;
649         @try {
650                 currentAfsState = [afsProperty checkAfsStatus];
651                 // make the parameter to call the root helper app
652                 if(currentAfsState){
653                         //shutdown afs
654                         NSLog(@"Shutting down afs");
655                         [afsProperty shutdown];
656                 } else {
657                         //Start afs
658                         NSLog(@"Starting up afs");
659                         [afsProperty startup];
660                 }
661                 [self refreshGui:nil];
662         }
663         @catch (NSException * e) {
664                 [self showMessage:[e reason]];
665         }
666         @finally {
667                 [[AuthUtil shared] deautorize];
668         }
669 }
670
671 // -------------------------------------------------------------------------------
672 //  info:
673 // -------------------------------------------------------------------------------
674 - (void) refreshGui:(NSNotification *)notification{
675         BOOL afsIsUp = [afsProperty checkAfsStatus];
676         [self setAfsStatus];
677         [tokensButton setEnabled:afsIsUp];
678         [unlogButton setEnabled:afsIsUp];
679
680 }
681
682 // -------------------------------------------------------------------------------
683 //  -(void) refreshTokensNotify:(NSNotification*)notification
684 // -------------------------------------------------------------------------------
685 -(void) refreshTokensNotify:(NSNotification*)notification {
686         [self refreshTokens:nil];
687 }
688
689 // -------------------------------------------------------------------------------
690 //  afsVolumeMountChange: Track the afs volume state change
691 // -------------------------------------------------------------------------------
692 - (void) afsVolumeMountChange:(NSNotification *)notification{
693         // Cehck if is mounted or unmounted afs
694         if([[[notification userInfo] objectForKey:@"NSDevicePath"] isEqualToString:@"/afs"]){
695                 [self setAfsStatus];
696                 [self refreshTokens:nil];
697         }
698 }
699
700 // -------------------------------------------------------------------------------
701 //  info:
702 // -------------------------------------------------------------------------------
703 - (IBAction) info:(id) sender
704 {
705         [((InfoController*) infoController) showHtmlResource:[[self bundle] pathForResource:@"license" ofType:@"rtf"]];
706
707         [NSApp beginSheet: infoSheet
708            modalForWindow: [[self mainView] window]
709                 modalDelegate: self
710            didEndSelector:  @selector(didEndInfoSheet:returnCode:contextInfo:)
711                   contextInfo: nil];
712 }
713
714 // -------------------------------------------------------------------------------
715 //  tableDoubleAction:
716 // -------------------------------------------------------------------------------
717 - (IBAction) tableDoubleAction:(id) sender
718 {
719         [self showCellIP:nil];
720 }
721
722 // -------------------------------------------------------------------------------
723 //  getNewToken:
724 // -------------------------------------------------------------------------------
725 - (IBAction) getNewToken:(id) sender
726 {
727         BOOL useAklog = [useAklogCheck state] == NSOnState;
728         if(useAklog){
729                 //[AFSPropertyManager aklog];
730                 [afsProperty getTokens:false 
731                                                    usr:nil 
732                                                    pwd:nil];
733                 [self refreshTokens:nil];
734                 //Inform afs menuextra to updata afs status
735                 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
736
737         } else {
738                 [NSBundle loadNibNamed:@"CredentialPanel" owner:self];
739                 [NSApp beginSheet: credentialSheet
740                    modalForWindow: [[self mainView] window]
741                         modalDelegate: self
742                    didEndSelector: @selector(didEndCredentialSheet:returnCode:contextInfo:)
743                           contextInfo: nil];
744         }
745 }
746
747
748 // -------------------------------------------------------------------------------
749 //  getCurrentCellInDB:
750 // -------------------------------------------------------------------------------
751 - (IBAction) unlog:(id) sender
752 {
753         int index = -1;
754         NSIndexSet *selectedIndex = [(NSTableView*)tokensTable selectedRowIndexes];
755         if( [selectedIndex count] > 0) {
756                 index = [selectedIndex firstIndex]; 
757                 do {
758                         NSString *tokenDesc = [tokenList objectAtIndex:index];
759                         NSString *cellToUnlog = [tokenDesc estractTokenByDelimiter:@"afs@" 
760                                                                                                                           endToken:@" "];
761                         [afsProperty unlog:cellToUnlog];
762                 } while ((index = [selectedIndex indexGreaterThanIndex: index]) != NSNotFound);
763         } else {
764                 [afsProperty unlog:nil];
765         }
766         [self refreshTokens:nil];
767         //Inform afs menuextra to updata afs status
768         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
769
770 }
771
772
773 // -------------------------------------------------------------------------------
774 //  aklogSwitchEvent:
775 // -------------------------------------------------------------------------------
776 - (IBAction) aklogSwitchEvent:(id) sender
777 {
778         //afs menu extra is loaded inform it to read preference
779         @try {
780                 if(![useAklogCheck state]) {
781                         //deselect the checkbox
782                         [aklogCredentialAtLoginTime setState:NO];
783                 }
784                 
785                 [self writePreferenceFile];
786                 
787                 //Enable disable aklog at login time checkbox according the useAklog checkbox
788                 [aklogCredentialAtLoginTime setEnabled:[useAklogCheck state]];
789                 
790         }
791         @catch (NSException * e) {
792                 [self showMessage:[e reason]];
793         }
794         
795                 
796 }
797
798 // -------------------------------------------------------------------------------
799 //  credentialAtLoginTimeEvent:
800 // -------------------------------------------------------------------------------
801 - (IBAction) credentialAtLoginTimeEvent:(id) sender {
802         [self writePreferenceFile];
803 }
804
805 // -------------------------------------------------------------------------------
806 //  afsStartupSwitchEvent:
807 // -------------------------------------------------------------------------------
808 - (IBAction) afsStartupSwitchEvent:(id) sender {
809         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
810         //get the new state
811         startAFSAtLogin = [checkButtonAfsAtBootTime state];
812         const char *startupConfigureOption[] = {"start_afs_at_startup", startAFSAtLogin?"enable":"disable", 0L};
813         if([[AuthUtil shared] autorize] == noErr) {
814                         //now disable the launchd configuration
815                         [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
816                                                                                   args:startupConfigureOption
817                                                                                 output:nil];
818         }
819 }
820
821
822 // -------------------------------------------------------------------------------
823 //  afsMenuActivationEvent:
824 // -------------------------------------------------------------------------------
825 - (IBAction) krb5KredentialAtLoginTimeEvent:(id) sender {
826         //
827         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
828         const char *args[] = {"enable_krb5_startup", [[installKRB5AuthAtLoginButton stringValue] UTF8String], "", 0L};
829         
830         //Check helper app
831         [self repairHelperTool];
832         if([[AuthUtil shared] autorize] == noErr) {
833                 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String] 
834                                                                           args:args
835                                                                         output:nil];
836                 
837                 //check if all is gone well
838                 [installKRB5AuthAtLoginButton setState:[PListManager checkKrb5AtLoginTimeLaunchdEnable]];
839         }
840 }
841
842 // -------------------------------------------------------------------------------
843 //  afsMenuActivationEvent:
844 // -------------------------------------------------------------------------------
845 -(IBAction) afsMenuActivationEvent:(id) sender
846 {
847         CFPreferencesSetValue((CFStringRef)PREFERENCE_SHOW_STATUS_MENU, 
848                                                   (CFNumberRef)[NSNumber numberWithBool:[(NSButton*)afsMenucheckBox state]],
849                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
850         
851         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesAnyUser, kCFPreferencesAnyHost);
852         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
853         
854         //notify the backgrounder
855         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSMenuChangeState];
856 }
857
858 // -------------------------------------------------------------------------------
859 //  searchCellTextEvent:
860 //              Fileter the CellServDB list according to NSSearch content
861 // -------------------------------------------------------------------------------
862 - (IBAction) searchCellTextEvent:(id) sender
863 {
864         
865         NSString *searchText = [[textSearchField stringValue] lowercaseString]; //filter string
866         [self filterCellServDB:searchText];
867         [((NSTableView*)cellList) reloadData];
868 }
869
870 // -------------------------------------------------------------------------------
871 //  clearCellServDBFiltering:
872 //              clear the NSSearchField and showw all CellServDB table
873 // -------------------------------------------------------------------------------
874 - (void) clearCellServDBFiltering {
875         //Clear the text search
876         [textSearchField setStringValue:@""];
877         //load the temp array with all cell servdb
878         [self searchCellTextEvent:nil];
879 }
880 // --------------------------------------o-----------------------------------------
881 //  filterCellServDB:
882 //  make the NSMutableArray with all cellservdb or filtered element
883 // -------------------------------------------------------------------------------
884 - (void) filterCellServDB:(NSString*)textToFilter {
885         DBCellElement *cellElement; //Filtered element
886         BOOL doFilter = !(textToFilter == nil || ([textToFilter length] == 0));
887         
888         // We can do filtering and make the temp array
889         if(filteredCellDB){
890                 [filteredCellDB release];
891         }
892         filteredCellDB = [[NSMutableArray alloc] init];
893         NSEnumerator *e = [[afsProperty getCellList] objectEnumerator];
894         while(cellElement = (DBCellElement*)[e nextObject]) {
895                 // check if the element can be get
896                 if(doFilter) {
897                         //Get the CellServDB array enumerator
898                         NSRange rsltRng = [[[cellElement getCellName] lowercaseString] rangeOfString:textToFilter];
899                    if(rsltRng.location != NSNotFound) {
900                         //we can add this cell to filtered
901                         [filteredCellDB addObject:[cellElement retain]];
902                    }
903                 } else {
904                         [filteredCellDB addObject:[cellElement retain]];
905
906                 }
907         }
908 }
909                    
910 // -------------------------------------------------------------------------------
911 //  getCurrentCellInDB:
912 // -------------------------------------------------------------------------------
913 - (DBCellElement*) getCurrentCellInDB
914 {
915         int rowSelected = [((NSTableView *) cellList) selectedRow];
916         return [self getCellByIDX:rowSelected];
917 }
918
919 // -------------------------------------------------------------------------------
920 //  getCurrentCellInDB:
921 // -------------------------------------------------------------------------------
922 - (DBCellElement*) getCellByIDX:(int) idx
923 {
924         //NSMutableArray *cellArray = [afsProperty getCellList];
925         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:idx];
926         return cellElement;
927 }
928
929 // -------------------------------------------------------------------------------
930 //  showMessage:
931 // -------------------------------------------------------------------------------
932 -(void) showMessage:(NSString*) message{
933         NSAlert *alert = [[NSAlert alloc] init];
934         
935         [alert setMessageText:message];
936         [alert beginSheetModalForWindow:[[self mainView] window]
937                                           modalDelegate:nil 
938                                          didEndSelector:nil
939                                                 contextInfo:nil];
940         [alert release];
941 }
942
943 // -------------------------------------------------------------------------------
944 //  setAfsStatus:
945 // -------------------------------------------------------------------------------
946 -(void) setAfsStatus
947 {
948         
949         BOOL afsIsUp = [afsProperty checkAfsStatus];
950         BOOL afsEnabledAtStartup = NO;
951         
952         NSMutableString *commandOutput = [NSMutableString stringWithCapacity:20];
953         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
954                 
955 #if 0
956                         // make the parameter to call the root helper app
957         const char *checkAFSDaemonParam[] = {"check_afs_daemon",  0L};
958         if([[AuthUtil shared] autorize] == noErr) {
959                                 //now disable the launchd configuration
960                 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
961                                                                           args:checkAFSDaemonParam
962                                                                         output:commandOutput];
963                 afsEnabledAtStartup = [commandOutput rangeOfString:@"afshlp:afs daemon registration result:1"].location!=NSNotFound;
964         }
965 #else
966         afsEnabledAtStartup = 1;
967 #endif
968         
969         
970
971
972         [((NSButton *)startStopButton) setTitle: (afsIsUp?kAfsButtonShutdown:kAfsButtonStartup)];
973         
974         NSMutableAttributedString *colorTitle =[[NSMutableAttributedString alloc] initWithAttributedString:[((NSButton *)startStopButton) attributedTitle]];
975     NSRange titleRange = NSMakeRange(0, [colorTitle length]);
976         
977     [colorTitle addAttribute:NSForegroundColorAttributeName
978                        value:(afsIsUp?[NSColor redColor]:[NSColor blackColor])
979                        range:titleRange];
980         
981     [((NSButton *)startStopButton) setAttributedTitle:colorTitle];
982         [checkButtonAfsAtBootTime setState:afsEnabledAtStartup];
983         if(afsIsUp) {
984                 [self startTimer];
985         } else {
986                 [self stopTimer];
987         }
988 }
989
990 // -------------------------------------------------------------------------------
991 //  refreshToken:
992 // -------------------------------------------------------------------------------
993 - (void) refreshTokens:(NSTimer*)theTimer;
994 {
995         if(![tokensLock tryLock]) return;
996         if(tokenList){
997                 [tokenList release];
998         }
999         
1000         tokenList = [afsProperty getTokenList];
1001         [((NSTableView*)tokensTable) reloadData];
1002         [tokensLock unlock];
1003 }
1004
1005 // -------------------------------------------------------------------------------
1006 //  removeExtra:
1007 // -------------------------------------------------------------------------------
1008 - (IBAction) addLink:(id) sender {
1009         [NSBundle loadNibNamed:@"SymLinkEdit" owner:self];
1010         
1011         [NSApp beginSheet: lyncCreationSheet
1012            modalForWindow: [[self mainView] window]
1013                 modalDelegate: self
1014            didEndSelector: @selector(didEndSymlinkSheet:returnCode:contextInfo:)
1015                   contextInfo: nil];
1016         
1017 }
1018
1019 // -------------------------------------------------------------------------------
1020 //  removeExtra:
1021 // -------------------------------------------------------------------------------
1022 - (IBAction) removeLink:(id) sender {
1023         if(!linkConfiguration) return;
1024         int index = 0;
1025         NSArray *keys = [linkConfiguration allKeys];
1026         NSIndexSet *linkToRemove = [tableViewLink selectedRowIndexes];
1027         if( [linkToRemove count] > 0) {
1028                 index = [linkToRemove firstIndex];
1029                 do {
1030                         [linkConfiguration removeObjectForKey:[keys objectAtIndex:index]];
1031                 } while ((index = [linkToRemove indexGreaterThanIndex:index]) != -1);
1032         }
1033         
1034         //write the new configuration
1035         NSData *prefData = nil;
1036         if([linkConfiguration count] > 0) {
1037                 prefData = [NSPropertyListSerialization dataWithPropertyList:linkConfiguration
1038                                                                                                                           format:NSPropertyListXMLFormat_v1_0
1039                                                                                                                          options:0
1040                                                                                                                            error:nil];
1041         }
1042         CFPreferencesSetValue((CFStringRef)PREFERENCE_LINK_CONFIGURATION,
1043                                                   (CFDataRef)prefData,
1044                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1045         
1046         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1047         
1048         //reload the new data
1049         [tableViewLink reloadData];
1050 }
1051
1052 // -------------------------------------------------------------------------------
1053 //  removeExtra:
1054 // -------------------------------------------------------------------------------
1055 - (IBAction) enableLink:(id) sender {
1056         [self writePreferenceFile];
1057 }
1058
1059 // -------------------------------------------------------------------------------
1060 //  removeExtra:
1061 // -------------------------------------------------------------------------------
1062 - (IBAction) manageBackgrounderActivation:(id)sender {
1063         [PListManager launchctlCommand:[(NSButton*)sender state] 
1064                                                 userDomain:YES 
1065                                                         option:[NSArray arrayWithObjects:@"-S", @"Aqua", nil] 
1066                                                  plistName:[NSString stringWithFormat:@"%@.plist", BACKGROUNDER_P_FILE]];
1067         //re ad the status to check taht all is gone well
1068         [backgrounderActivationCheck setState:[PListManager launchdJobState:BACKGROUNDER_P_FILE]];
1069 }
1070
1071 // -------------------------------------------------------------------------------
1072 //  tableViewLinkPerformClick:
1073 // -------------------------------------------------------------------------------
1074 - (IBAction) tableViewLinkPerformClick:(id) sender {
1075         NSLog(@"tableViewLinkPerformClick");
1076 }
1077
1078 // -------------------------------------------------------------------------------
1079 //  - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem
1080 // -------------------------------------------------------------------------------
1081 - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem 
1082 {
1083         //check to see if the cache param tab is the tab that will be selected
1084         if([((NSString*)[tabViewItem identifier]) intValue] == TAB_LINK)
1085         {
1086                 [tableViewLink reloadData];
1087         }
1088 }
1089 // -------------------------------------------------------------------------------
1090 //  tableViewLinkPerformClick:
1091 // -------------------------------------------------------------------------------
1092 - (IBAction) enableDisableKrb5RenewCheck:(id) sender {
1093         //NSLog(@"enableDisableKrb5RenewCheck");
1094         CFPreferencesSetValue((CFStringRef)PREFERENCE_KRB5_CHECK_ENABLE,
1095                                                   (CFNumberRef) [NSNumber numberWithInt:[(NSButton*)sender intValue]],
1096                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1097         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1098                 //notify the backgrounder
1099         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kPrefChangeNotification];
1100 }
1101 // -------------------------------------------------------------------------------
1102 //  tableViewLinkPerformClick:
1103 // -------------------------------------------------------------------------------
1104 - (IBAction) krb5RenewParamChange:(id) sender {
1105 }
1106 @end
1107
1108 @implementation AFSCommanderPref (NSTableDataSource)
1109
1110
1111 // -------------------------------------------------------------------------------
1112 //  tableView:
1113 //              Manage the checkbox of CellServDB Table
1114
1115 // -------------------------------------------------------------------------------
1116 - (void)tableView:(NSTableView *)table 
1117    setObjectValue:(id)data 
1118    forTableColumn:(NSTableColumn *)col 
1119                           row:(int)row
1120 {
1121         NSString *identifier = (NSString*)[col identifier];
1122         switch([table tag]){
1123                 case TABLE_TOKENS_LIST:
1124                         break;
1125                         
1126                 case TABLE_CELL_LIST:
1127                         // we are editing checkbox for cellservdb table
1128                         if([identifier intValue] == CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN) {
1129                                 // set the user default cell
1130                                 DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1131                                 [afsProperty setDefaultCellByName:[cellElement getCellName]];
1132                                 //[afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
1133                                 [((NSTableView*)cellList) reloadData];
1134                         } else if([identifier intValue] == CELLSRVDB_TABLE_DFLT_CHECK_COLUMN) {
1135                                 // set the cell for wich the user want to get token
1136                                 DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1137                                 [cellElement setUserDefaultForToken:![cellElement userDefaultForToken]];
1138                         }  
1139                         break;
1140         }
1141         
1142 }
1143
1144
1145 // -------------------------------------------------------------------------------
1146 //  tableView:
1147 //              refresh delegate method for two AFSCommander table
1148 // -------------------------------------------------------------------------------
1149 - (id)  tableView:(NSTableView *) aTableView
1150         objectValueForTableColumn:(NSTableColumn *) aTableColumn
1151                                                   row:(int) rowIndex
1152 {  
1153         
1154         id result = nil;
1155         NSString *identifier = (NSString*)[aTableColumn identifier];
1156         switch([aTableView tag]){
1157                 case TABLE_TOKENS_LIST:
1158                         //We are refreshing tokens table
1159                         result = [self getTableTokensListValue:[identifier intValue] row:rowIndex];
1160                         break;
1161                         
1162                 case TABLE_CELL_LIST:
1163                         //We are refreshing cell db table
1164                         result = [self getTableCelListValue:[identifier intValue] row:rowIndex];
1165                         break;
1166                         
1167                 case TABLE_LINK_LIST:
1168                         result = [self getTableLinkValue:[identifier intValue] row:rowIndex];
1169                         break;
1170
1171                 
1172         }
1173         return result;  
1174 }
1175
1176
1177 // -------------------------------------------------------------------------------
1178 //  getTableCelListValue:
1179 // -------------------------------------------------------------------------------
1180 - (id)getTableTokensListValue:(int) colId row:(int)row
1181 {
1182         id result = nil;
1183         if(!tokenList) return nil;
1184         switch(colId){
1185                 case 0:
1186                         result = (NSString*)[tokenList objectAtIndex:row];
1187                         break;
1188         }
1189         return result;
1190 }
1191
1192
1193 // -------------------------------------------------------------------------------
1194 //  getTableCelListValue:
1195 // -------------------------------------------------------------------------------
1196 - (id)getTableCelListValue:(int) colId row:(int)row
1197 {
1198         id result = nil;
1199         //NSMutableArray *cellArray = [afsProperty getCellList];
1200         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1201         switch(colId){
1202                 case CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN:
1203                         result = [NSNumber numberWithInt:[cellElement userDefaultForCell]];
1204                         break;
1205                         
1206                 case CELLSRVDB_TABLE_DFLT_CHECK_COLUMN:
1207                         result = [NSNumber numberWithInt:[cellElement userDefaultForToken]];
1208                         break;
1209                 case CELLSRVDB_TABLE_NAME_COLUMN:
1210                         result = [cellElement getCellName];
1211                         break;
1212                         
1213                 case CELLSRVDB_TABLE_DESCRIPTION_COLUMN:
1214                         result = [cellElement getCellComment];
1215                         break;
1216         }
1217         return result;
1218 }
1219
1220 // -------------------------------------------------------------------------------
1221 //  getTableCelListValue:
1222 // -------------------------------------------------------------------------------
1223 - (id)getTableLinkValue:(int) colId row:(int)row
1224 {
1225         id result = nil;
1226         NSArray *allKey = [linkConfiguration allKeys];
1227         switch(colId){
1228                 case TABLE_COLUMN_LINK_NAME:
1229                         result = [allKey objectAtIndex:row];
1230                         break;
1231                         
1232                 case TABLE_COLUMN_LINK_PATH:
1233                         result = [linkConfiguration objectForKey:[allKey objectAtIndex:row]];
1234                         break;
1235         }
1236         return result;
1237 }
1238
1239
1240 // -------------------------------------------------------------------------------
1241 //  numberOfRowsInTableView:
1242 // -------------------------------------------------------------------------------
1243 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
1244 {
1245         int rowCount = 0;
1246         //NSMutableArray *cellArray = nil;
1247         switch([aTableView tag]){
1248                 case TABLE_TOKENS_LIST:
1249                         if(tokenList)  rowCount = [tokenList count];
1250                         break;
1251                         
1252                 case TABLE_CELL_LIST:
1253                         //cellArray = [afsProperty getCellList];
1254                         if(filteredCellDB)  rowCount = [filteredCellDB count];
1255                         break;
1256                         
1257                 case TABLE_LINK_LIST:
1258                         if(linkConfiguration)  rowCount = [linkConfiguration count];
1259                         break;
1260
1261                         
1262         }       
1263         return rowCount;  
1264 }
1265 @end
1266
1267
1268 @implementation AFSCommanderPref (TableDelegate)
1269 // -------------------------------------------------------------------------------
1270 //  selectionShouldChangeInTableView:
1271 // -------------------------------------------------------------------------------
1272 - (BOOL)selectionShouldChangeInTableView:(NSTableView *)aTable
1273 {
1274         switch([aTable tag]){
1275                 case TABLE_TOKENS_LIST:
1276                         
1277                         break;
1278                         
1279                 case TABLE_CELL_LIST:
1280                         [self tableViewCellmanageButtonState:[aTable selectedRow]];
1281                         break;
1282                         
1283                 case TABLE_LINK_LIST:
1284                         break;
1285                         
1286                         
1287         }       
1288         
1289         return YES;
1290 }
1291
1292 // -------------------------------------------------------------------------------
1293 //  tableView:
1294 // -------------------------------------------------------------------------------
1295 - (BOOL)tableView:(NSTableView *)aTable shouldSelectRow:(int)aRow
1296 {
1297         switch([aTable tag]){
1298                 case TABLE_TOKENS_LIST:
1299                         
1300                         break;
1301                         
1302                 case TABLE_CELL_LIST:
1303                         [self tableViewCellmanageButtonState:aRow];
1304                         break;
1305                         
1306                 case TABLE_LINK_LIST:
1307                         break;
1308                         
1309                         
1310         }
1311         
1312         return YES;
1313 }
1314
1315 // -------------------------------------------------------------------------------
1316 //  tableView:
1317 // -------------------------------------------------------------------------------
1318 - (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
1319         NSTableView *aTable = [aNotification object];
1320         switch([aTable tag]){
1321                 case TABLE_TOKENS_LIST:
1322                         break;
1323                         
1324                 case TABLE_CELL_LIST:
1325                         break;
1326                         
1327                 case TABLE_LINK_LIST:
1328                         [self tableViewLinkmanageButtonState:[aTable selectedRowIndexes]];
1329                         break;
1330                         
1331                         
1332         }
1333 }
1334 // -------------------------------------------------------------------------------
1335 //  manageButtonState:
1336 // -------------------------------------------------------------------------------
1337 -(void) tableViewCellmanageButtonState:(int) rowSelected  {
1338         [((NSControl*) cellIpButton) setEnabled:rowSelected >= 0];
1339         [((NSControl*) removeCellButton) setEnabled:rowSelected >= 0];
1340 }
1341
1342 // -------------------------------------------------------------------------------
1343 //  manageButtonState:
1344 // -------------------------------------------------------------------------------
1345 -(void) tableViewLinkmanageButtonState:(NSIndexSet *) rowsSelectedIndex {
1346         [buttonRemoveLink setEnabled:[rowsSelectedIndex count]>0];
1347 }
1348 @end
1349
1350
1351 @implementation AFSCommanderPref (ModalDelegate)
1352 // -------------------------------------------------------------------------------
1353 //  didEndSheet:
1354 // -------------------------------------------------------------------------------
1355 - (void)didEndSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1356 {
1357     [sheet orderOut:self];
1358         //Filter the cellServDb and allocate filtered array
1359         [self searchCellTextEvent:nil];
1360         [((NSTableView*)cellList) reloadData];
1361 }
1362
1363 // -------------------------------------------------------------------------------
1364 //  Klog credential request
1365 // -------------------------------------------------------------------------------
1366 - (void)didEndCredentialSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1367 {
1368         if([((TokenCredentialController*)credentialCommander) takenToken] == YES){
1369                 /*[AFSPropertyManager klog:[((TokenCredentialController*)credentialCommander) uName] 
1370                                                         uPwd:[((TokenCredentialController*)credentialCommander) uPwd] ];*/
1371                 [afsProperty getTokens:true 
1372                                                    usr:[((TokenCredentialController*)credentialCommander) uName] 
1373                                                    pwd:[((TokenCredentialController*)credentialCommander) uPwd]];
1374         }
1375     [sheet orderOut:self];
1376         [self refreshTokens:nil];
1377         //Inform afs menuextra to updata afs status
1378         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
1379
1380 }
1381
1382 // -------------------------------------------------------------------------------
1383 //  Klog credential request
1384 // -------------------------------------------------------------------------------
1385 - (void)didEndInfoSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1386 {
1387         [sheet orderOut:self];
1388 }
1389
1390 // -------------------------------------------------------------------------------
1391 //  symlink edite
1392 // -------------------------------------------------------------------------------
1393 - (void)didEndSymlinkSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1394 {
1395         [lyncCreationSheet orderOut:self];
1396         [self readPreferenceFile];
1397         [tableViewLink reloadData];
1398         
1399 }
1400 @end