Develop Kerberos renew system for ticket
[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 intValue])[nsTextFieldKrb5RenewTime setIntValue:[renewTime intValue]];
306         else [nsTextFieldKrb5RenewTime setIntValue:PREFERENCE_KRB5_RENEW_TIME_DEFAULT_VALUE];
307
308         NSNumber *renewCheckTimeInterval = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_KRB5_RENEW_CHECK_TIME_INTERVALL,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
309         if(renewCheckTimeInterval && [renewCheckTimeInterval intValue])[nsTextFieldKrb5RenewCheckIntervall setIntValue:[renewCheckTimeInterval intValue]];
310         else [nsTextFieldKrb5RenewCheckIntervall setIntValue:PREFERENCE_KRB5_RENEW_CHECK_TIME_INTERVALL_DEFAULT_VALUE];
311
312         NSNumber *expireTimeForRenew = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_KRB5_SEC_TO_EXPIRE_TIME_FOR_RENEW,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
313         if(expireTimeForRenew && [expireTimeForRenew intValue])[nsTextFieldKrb5SecToExpireDateForRenew setIntValue:[expireTimeForRenew intValue]];
314         else [nsTextFieldKrb5SecToExpireDateForRenew setIntValue:PREFERENCE_KRB5_SEC_TO_EXPIRE_TIME_FOR_RENEW_DEFAULT_VALUE];
315
316         //link configuration
317         NSData *prefData = (NSData*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_LINK_CONFIGURATION,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
318         linkConfiguration = (NSMutableDictionary*)[NSPropertyListSerialization propertyListFromData:prefData
319                                                                                                                                                            mutabilityOption:NSPropertyListMutableContainers
320                                                                                                                                                                                  format:nil
321                                                                                                                                                            errorDescription:nil];
322         
323 }
324
325 // -------------------------------------------------------------------------------
326 //  willUnselect:
327 // -------------------------------------------------------------------------------
328 - (void) writePreferenceFile
329 {
330         //Set the preference for afs path
331         //Set the preference for aklog use
332         CFPreferencesSetValue((CFStringRef)PREFERENCE_USE_AKLOG, 
333                                                   (CFNumberRef)[NSNumber numberWithInt:[useAklogCheck state]], 
334                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
335
336         //set AFS enable state at startup
337         CFPreferencesSetValue((CFStringRef)PREFERENCE_START_AFS_AT_STARTUP, 
338                                                   (CFNumberRef)[NSNumber numberWithBool:startAFSAtLogin], 
339                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
340         
341         //set aklog at login
342         CFPreferencesSetValue((CFStringRef)PREFERENCE_AKLOG_TOKEN_AT_LOGIN, 
343                                                   (CFNumberRef)[NSNumber numberWithBool:[aklogCredentialAtLoginTime state]], 
344                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
345         
346         //set aklog at login
347         CFPreferencesSetValue((CFStringRef)PREFERENCE_SHOW_STATUS_MENU, 
348                                                   (CFNumberRef)[NSNumber numberWithBool:[(NSButton*)afsMenucheckBox state]],
349                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
350         
351         //preference for link
352         CFPreferencesSetValue((CFStringRef)PREFERENCE_USE_LINK,
353                                                   (CFNumberRef)[NSNumber numberWithBool:[checkEnableLink state]], 
354                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
355         
356                 //preference for renew time
357         CFPreferencesSetValue((CFStringRef)PREFERENCE_KRB5_RENEW_TIME,
358                                                   (CFNumberRef)[NSNumber numberWithInt:[nsTextFieldKrb5RenewTime intValue]],
359                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
360
361                 //expire time for renew
362         CFPreferencesSetValue((CFStringRef)PREFERENCE_KRB5_SEC_TO_EXPIRE_TIME_FOR_RENEW,
363                                                   (CFNumberRef)[NSNumber numberWithInt:[nsTextFieldKrb5SecToExpireDateForRenew intValue]],
364                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
365
366                 //sec to expiretime for renew job
367         CFPreferencesSetValue((CFStringRef)PREFERENCE_KRB5_RENEW_CHECK_TIME_INTERVALL,
368                                                   (CFNumberRef)[NSNumber numberWithInt:[nsTextFieldKrb5RenewCheckIntervall intValue]],
369                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
370
371         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesAnyUser, kCFPreferencesAnyHost);
372         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
373         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kPrefChangeNotification];
374 }
375
376 // -------------------------------------------------------------------------------
377 //  saveConfiguration:
378 // -------------------------------------------------------------------------------
379 - (IBAction) saveConfiguration:(id) sender
380 {
381         @try{
382                 
383                 //[afsProperty setCellName:[cellNameTextEdit stringValue]];
384                 [afsProperty setCellName:[afsProperty getDefaultCellName]];
385                 
386                 //save configurations
387                 [afsProperty saveConfigurationFiles:YES];
388                 
389                 
390                 //Reload all configuration
391                 [self refreshConfiguration:nil];
392                 
393                 //refresh table to reflect the NSSearchField contained text
394                 [self searchCellTextEvent:nil];
395                 
396                 //Show dialog for notifity al saving process ar gone ell
397                 [self showMessage:kConfigurationSaved];
398         }@catch(NSException *e){
399                 [self showMessage:[e reason]];
400         } @finally {
401                 [((NSTableView*)cellList) reloadData];
402         }
403         
404 }
405
406 // -------------------------------------------------------------------------------
407 //  saveCacheManagerParam:
408 // -------------------------------------------------------------------------------
409 - (IBAction) saveCacheManagerParam:(id) sender
410 {
411         @try{
412                 //Update the value form view to afs property manager class
413                 [self updateCacheParamFromView];
414                 [afsProperty saveCacheConfigurationFiles:YES];
415                 [self showMessage:kSavedCacheConfiguration];
416         }@catch(NSException *e){
417                 [self showMessage:[e reason]];
418         } @finally {
419                 [((NSTableView*)cellList) reloadData];
420         }
421 }
422
423 // -------------------------------------------------------------------------------
424 //  refreshConfiguration:
425 // -------------------------------------------------------------------------------
426 - (IBAction) refreshConfiguration:(id) sender
427 {
428         NSString *afsBasePath = PREFERENCE_AFS_SYS_PAT_STATIC;
429         @try{
430                 // set the afs path
431                 [afsProperty setPath:afsBasePath];
432                 
433                 // load configuration
434                 [afsProperty loadConfiguration];
435                 
436                 //set the afs version label
437                 [afsVersionLabel setStringValue:[afsProperty getAfsVersion]];
438                 
439                 //set the current default cell
440                 [afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
441                 
442                 // Update cache view
443                 [self fillCacheParamView];
444                 
445                 //Filter the cellServDb and allocate filtered array
446                 [self filterCellServDB:nil];
447                 
448         }@catch(NSException *e){
449                 [self showMessage:[e reason]];
450         } @finally {
451                 [((NSTableView*)cellList) reloadData];
452         }
453 }
454
455 // -------------------------------------------------------------------------------
456 //  fillCacheParamView:
457 // -------------------------------------------------------------------------------
458 -(void) fillCacheParamView
459 {
460         [dynRoot setState:[afsProperty dynRoot]?NSOnState:NSOffState];
461         [afsDB setState:[afsProperty afsDB]?NSOnState:NSOffState];
462         [statCacheEntry setIntValue:[afsProperty statCacheEntry]];
463         [dCacheDim setIntValue:[afsProperty dCacheDim]];
464         [cacheDimension setIntValue:[afsProperty cacheDimension]];
465         [daemonNumber setIntValue:[afsProperty daemonNumber]];
466         [afsRootMountPoint setStringValue:[afsProperty afsRootMountPoint]];
467         [nVolEntry setIntValue:[afsProperty nVolEntry]];
468         
469         //new version property
470         //[verbose setEnabled:[afsProperty useAfsdConfConfigFile]];
471         [verbose setState:[afsProperty verbose]?NSOnState:NSOffState];
472         
473 }
474
475 // -------------------------------------------------------------------------------
476 //  updateCacheParamFromView:
477 // -------------------------------------------------------------------------------
478 -(void) updateCacheParamFromView
479 {
480         NSString *tmpAfsPath = [afsRootMountPoint stringValue];
481         if(!tmpAfsPath || ([tmpAfsPath length] == 0) || ([tmpAfsPath characterAtIndex:0] != '/')) 
482                 @throw [NSException exceptionWithName:@"updateCacheParamFromView" 
483                                                                            reason:kBadAfsRootMountPoint
484                                                                          userInfo:nil];
485
486         
487         [afsProperty setDynRoot:[dynRoot state]==NSOnState];
488         [afsProperty setAfsDB:[afsDB state]==NSOnState];
489         [afsProperty setStatCacheEntry:[statCacheEntry intValue]];
490         [afsProperty setDCacheDim:[dCacheDim intValue]]; 
491         [afsProperty setCacheDimension:[cacheDimension intValue]]; 
492         [afsProperty setDaemonNumber:[daemonNumber intValue]];
493         [afsProperty setAfsRootMountPoint:tmpAfsPath];
494         [afsProperty setNVolEntry:[nVolEntry intValue]];
495         [afsProperty setVerbose:[verbose state]==NSOnState];
496 }
497
498
499 // -------------------------------------------------------------------------------
500 //  showCellIP:
501 // -------------------------------------------------------------------------------
502 - (IBAction) showCellIP:(id) sender
503 {
504         int rowSelected = [((NSTableView *) cellList) selectedRow];
505         [self modifyCellByIDX:rowSelected];
506 }
507
508 // -------------------------------------------------------------------------------
509 //  modifyCellByIDX:
510 // -------------------------------------------------------------------------------
511 -(void) modifyCellByIDX:(int) idx
512 {
513         [self modifyCell:[self getCellByIDX:idx]];
514 }
515
516 // -------------------------------------------------------------------------------
517 //  modifyCellByIDX:
518 // -------------------------------------------------------------------------------
519 -(void) modifyCell:(DBCellElement*) cellElement
520 {
521         [NSBundle loadNibNamed:@"IpPanel" owner:self];
522         [((IpConfiguratorCommander*) ipConfControllerCommander) setWorkCell:cellElement];
523         [NSApp beginSheet: ipConfigurationSheet
524            modalForWindow: [[self mainView] window]
525                 modalDelegate: self
526            didEndSelector: @selector(didEndSheet:returnCode:contextInfo:)
527                   contextInfo: nil];
528 }
529
530 // -------------------------------------------------------------------------------
531 //  addMoifyCell:
532 // -------------------------------------------------------------------------------
533 - (IBAction) addRemoveCell:(id) sender
534 {
535         switch([((NSControl*) sender) tag]){
536                 case ADD_CELL_CONTROL_TAG:
537                 {
538                         DBCellElement *newCell = [[DBCellElement alloc] init];
539                         if(!newCell) break;
540                         
541                         [newCell setCellName:kNewCellName];
542                         [newCell setCellComment:kNewCellComment];
543                         //cellArray = ;
544                         [[afsProperty getCellList] addObject:newCell];
545                         [newCell release];
546                         
547                         //Modify new cell
548                         [self modifyCell:newCell];
549                 }
550                 break;
551                         
552                 case REMOVE_CELL_CONTROL_TAG:
553                 {
554                         int index = 0;
555                         NSIndexSet *selectedIndex = [(NSTableView*)cellList selectedRowIndexes];
556                         if( [selectedIndex count] > 0) {
557                                 index = [selectedIndex firstIndex]; 
558                                 do {
559                                         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:index];
560                                         [[afsProperty getCellList] removeObject:cellElement];
561                                 } while ((index = [selectedIndex indexGreaterThanIndex:index]) != NSNotFound);
562                         }
563                 }
564                 break;
565         }
566         //Filter the cellServDb and allocate filtered array
567         [self searchCellTextEvent:nil];
568         [(NSTableView*)cellList deselectAll:nil];
569         [(NSTableView*)cellList reloadData];
570 }
571
572 // -------------------------------------------------------------------------------
573 //  repairHelperTool:
574 // -------------------------------------------------------------------------------
575 - (void) repairHelperTool
576 {
577         struct stat st;
578     int fdTool;
579         int status = 0;
580         NSLog(@"repairHelperTool"); 
581         NSString *afshlpPath = [[self bundle] pathForResource:@"afshlp" ofType:nil];
582         
583         
584     
585     // Open tool exclusively, so nobody can change it while we bless it.
586     fdTool = open([afshlpPath UTF8String], O_NONBLOCK | O_RDONLY | O_EXLOCK, 0);
587     
588     if(fdTool == -1)
589     {
590         NSLog(@"Exclusive open while repairing tool failed: %d.", errno);
591         exit(-1);
592     }
593     
594     if(fstat(fdTool, &st))
595     {
596         NSLog(@"fstat failed.");
597         exit(-1);
598     }
599     
600     if(st.st_uid != 0)
601     {
602                 status = [[AuthUtil shared] autorize];
603                 if(status == noErr){
604                         fchown(fdTool, 0, st.st_gid);
605                         
606                         // Disable group and world writability and make setuid root.
607                         fchmod(fdTool, (st.st_mode & (~(S_IWGRP | S_IWOTH)))/* | S_ISUID*/);
608                         const char *args[] = {"root", [afshlpPath UTF8String],0L};
609                         [[AuthUtil shared] execUnixCommand:"/usr/sbin/chown" 
610                                                                                   args:args
611                                                                                 output:nil];
612                         [[AuthUtil shared] deautorize];
613                 }
614     } else  NSLog(@"st_uid = 0");
615     
616         
617     
618     close(fdTool);
619     
620     NSLog(@"Self-repair done.");
621         
622 }
623
624
625 // -------------------------------------------------------------------------------
626 //  startStopAfs:
627 // -------------------------------------------------------------------------------
628 - (IBAction) startStopAfs:(id) sender
629 {
630         BOOL currentAfsState = NO;
631         @try {
632                 currentAfsState = [afsProperty checkAfsStatus];
633                 // make the parameter to call the root helper app
634                 if(currentAfsState){
635                         //shutdown afs
636                         NSLog(@"Shutting down afs");
637                         [afsProperty shutdown];
638                 } else {
639                         //Start afs
640                         NSLog(@"Starting up afs");
641                         [afsProperty startup];
642                 }
643                 [self refreshGui:nil];
644         }
645         @catch (NSException * e) {
646                 [self showMessage:[e reason]];
647         }
648         @finally {
649                 [[AuthUtil shared] deautorize];
650         }
651 }
652
653 // -------------------------------------------------------------------------------
654 //  info:
655 // -------------------------------------------------------------------------------
656 - (void) refreshGui:(NSNotification *)notification{
657         BOOL afsIsUp = [afsProperty checkAfsStatus];
658         [self setAfsStatus];
659         [tokensButton setEnabled:afsIsUp];
660         [unlogButton setEnabled:afsIsUp];
661
662 }
663
664 // -------------------------------------------------------------------------------
665 //  -(void) refreshTokensNotify:(NSNotification*)notification
666 // -------------------------------------------------------------------------------
667 -(void) refreshTokensNotify:(NSNotification*)notification {
668         [self refreshTokens:nil];
669 }
670
671 // -------------------------------------------------------------------------------
672 //  afsVolumeMountChange: Track the afs volume state change
673 // -------------------------------------------------------------------------------
674 - (void) afsVolumeMountChange:(NSNotification *)notification{
675         // Cehck if is mounted or unmounted afs
676         if([[[notification userInfo] objectForKey:@"NSDevicePath"] isEqualToString:@"/afs"]){
677                 [self setAfsStatus];
678                 [self refreshTokens:nil];
679         }
680 }
681
682 // -------------------------------------------------------------------------------
683 //  info:
684 // -------------------------------------------------------------------------------
685 - (IBAction) info:(id) sender
686 {
687         [((InfoController*) infoController) showHtmlResource:[[self bundle] pathForResource:@"license" ofType:@"rtf"]];
688
689         [NSApp beginSheet: infoSheet
690            modalForWindow: [[self mainView] window]
691                 modalDelegate: self
692            didEndSelector:  @selector(didEndInfoSheet:returnCode:contextInfo:)
693                   contextInfo: nil];
694 }
695
696 // -------------------------------------------------------------------------------
697 //  tableDoubleAction:
698 // -------------------------------------------------------------------------------
699 - (IBAction) tableDoubleAction:(id) sender
700 {
701         [self showCellIP:nil];
702 }
703
704 // -------------------------------------------------------------------------------
705 //  getNewToken:
706 // -------------------------------------------------------------------------------
707 - (IBAction) getNewToken:(id) sender
708 {
709         BOOL useAklog = [useAklogCheck state] == NSOnState;
710         if(useAklog){
711                 //[AFSPropertyManager aklog];
712                 [afsProperty getTokens:false 
713                                                    usr:nil 
714                                                    pwd:nil];
715                 [self refreshTokens:nil];
716                 //Inform afs menuextra to updata afs status
717                 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
718
719         } else {
720                 [NSBundle loadNibNamed:@"CredentialPanel" owner:self];
721                 [NSApp beginSheet: credentialSheet
722                    modalForWindow: [[self mainView] window]
723                         modalDelegate: self
724                    didEndSelector: @selector(didEndCredentialSheet:returnCode:contextInfo:)
725                           contextInfo: nil];
726         }
727 }
728
729
730 // -------------------------------------------------------------------------------
731 //  getCurrentCellInDB:
732 // -------------------------------------------------------------------------------
733 - (IBAction) unlog:(id) sender
734 {
735         int index = -1;
736         NSIndexSet *selectedIndex = [(NSTableView*)tokensTable selectedRowIndexes];
737         if( [selectedIndex count] > 0) {
738                 index = [selectedIndex firstIndex]; 
739                 do {
740                         NSString *tokenDesc = [tokenList objectAtIndex:index];
741                         NSString *cellToUnlog = [tokenDesc estractTokenByDelimiter:@"afs@" 
742                                                                                                                           endToken:@" "];
743                         [afsProperty unlog:cellToUnlog];
744                 } while ((index = [selectedIndex indexGreaterThanIndex: index]) != NSNotFound);
745         } else {
746                 [afsProperty unlog:nil];
747         }
748         [self refreshTokens:nil];
749         //Inform afs menuextra to updata afs status
750         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
751
752 }
753
754
755 // -------------------------------------------------------------------------------
756 //  aklogSwitchEvent:
757 // -------------------------------------------------------------------------------
758 - (IBAction) aklogSwitchEvent:(id) sender
759 {
760         //afs menu extra is loaded inform it to read preference
761         @try {
762                 if(![useAklogCheck state]) {
763                         //deselect the checkbox
764                         [aklogCredentialAtLoginTime setState:NO];
765                 }
766                 
767                 [self writePreferenceFile];
768                 
769                 //Enable disable aklog at login time checkbox according the useAklog checkbox
770                 [aklogCredentialAtLoginTime setEnabled:[useAklogCheck state]];
771                 
772         }
773         @catch (NSException * e) {
774                 [self showMessage:[e reason]];
775         }
776         
777                 
778 }
779
780 // -------------------------------------------------------------------------------
781 //  credentialAtLoginTimeEvent:
782 // -------------------------------------------------------------------------------
783 - (IBAction) credentialAtLoginTimeEvent:(id) sender {
784         [self writePreferenceFile];
785 }
786
787 // -------------------------------------------------------------------------------
788 //  afsStartupSwitchEvent:
789 // -------------------------------------------------------------------------------
790 - (IBAction) afsStartupSwitchEvent:(id) sender {
791         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
792         //get the new state
793         startAFSAtLogin = [checkButtonAfsAtBootTime state];
794         const char *startupConfigureOption[] = {"start_afs_at_startup", startAFSAtLogin?"enable":"disable", 0L};
795         if([[AuthUtil shared] autorize] == noErr) {
796                         //now disable the launchd configuration
797                         [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
798                                                                                   args:startupConfigureOption
799                                                                                 output:nil];
800         }
801 }
802
803
804 // -------------------------------------------------------------------------------
805 //  afsMenuActivationEvent:
806 // -------------------------------------------------------------------------------
807 - (IBAction) krb5KredentialAtLoginTimeEvent:(id) sender {
808         //
809         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
810         const char *args[] = {"enable_krb5_startup", [[installKRB5AuthAtLoginButton stringValue] UTF8String], "", 0L};
811         
812         //Check helper app
813         [self repairHelperTool];
814         if([[AuthUtil shared] autorize] == noErr) {
815                 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String] 
816                                                                           args:args
817                                                                         output:nil];
818                 
819                 //check if all is gone well
820                 [installKRB5AuthAtLoginButton setState:[PListManager checkKrb5AtLoginTimeLaunchdEnable]];
821         }
822 }
823
824 // -------------------------------------------------------------------------------
825 //  afsMenuActivationEvent:
826 // -------------------------------------------------------------------------------
827 -(IBAction) afsMenuActivationEvent:(id) sender
828 {
829         CFPreferencesSetValue((CFStringRef)PREFERENCE_SHOW_STATUS_MENU, 
830                                                   (CFNumberRef)[NSNumber numberWithBool:[(NSButton*)afsMenucheckBox state]],
831                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
832         
833         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesAnyUser, kCFPreferencesAnyHost);
834         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
835         
836         //notify the backgrounder
837         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSMenuChangeState];
838 }
839
840 // -------------------------------------------------------------------------------
841 //  searchCellTextEvent:
842 //              Fileter the CellServDB list according to NSSearch content
843 // -------------------------------------------------------------------------------
844 - (IBAction) searchCellTextEvent:(id) sender
845 {
846         
847         NSString *searchText = [[textSearchField stringValue] lowercaseString]; //filter string
848         [self filterCellServDB:searchText];
849         [((NSTableView*)cellList) reloadData];
850 }
851
852 // -------------------------------------------------------------------------------
853 //  clearCellServDBFiltering:
854 //              clear the NSSearchField and showw all CellServDB table
855 // -------------------------------------------------------------------------------
856 - (void) clearCellServDBFiltering {
857         //Clear the text search
858         [textSearchField setStringValue:@""];
859         //load the temp array with all cell servdb
860         [self searchCellTextEvent:nil];
861 }
862 // --------------------------------------o-----------------------------------------
863 //  filterCellServDB:
864 //  make the NSMutableArray with all cellservdb or filtered element
865 // -------------------------------------------------------------------------------
866 - (void) filterCellServDB:(NSString*)textToFilter {
867         DBCellElement *cellElement; //Filtered element
868         BOOL doFilter = !(textToFilter == nil || ([textToFilter length] == 0));
869         
870         // We can do filtering and make the temp array
871         if(filteredCellDB){
872                 [filteredCellDB release];
873         }
874         filteredCellDB = [[NSMutableArray alloc] init];
875         NSEnumerator *e = [[afsProperty getCellList] objectEnumerator];
876         while(cellElement = (DBCellElement*)[e nextObject]) {
877                 // check if the element can be get
878                 if(doFilter) {
879                         //Get the CellServDB array enumerator
880                         NSRange rsltRng = [[[cellElement getCellName] lowercaseString] rangeOfString:textToFilter];
881                    if(rsltRng.location != NSNotFound) {
882                         //we can add this cell to filtered
883                         [filteredCellDB addObject:[cellElement retain]];
884                    }
885                 } else {
886                         [filteredCellDB addObject:[cellElement retain]];
887
888                 }
889         }
890 }
891                    
892 // -------------------------------------------------------------------------------
893 //  getCurrentCellInDB:
894 // -------------------------------------------------------------------------------
895 - (DBCellElement*) getCurrentCellInDB
896 {
897         int rowSelected = [((NSTableView *) cellList) selectedRow];
898         return [self getCellByIDX:rowSelected];
899 }
900
901 // -------------------------------------------------------------------------------
902 //  getCurrentCellInDB:
903 // -------------------------------------------------------------------------------
904 - (DBCellElement*) getCellByIDX:(int) idx
905 {
906         //NSMutableArray *cellArray = [afsProperty getCellList];
907         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:idx];
908         return cellElement;
909 }
910
911 // -------------------------------------------------------------------------------
912 //  showMessage:
913 // -------------------------------------------------------------------------------
914 -(void) showMessage:(NSString*) message{
915         NSAlert *alert = [[NSAlert alloc] init];
916         
917         [alert setMessageText:message];
918         [alert beginSheetModalForWindow:[[self mainView] window]
919                                           modalDelegate:nil 
920                                          didEndSelector:nil
921                                                 contextInfo:nil];
922         [alert release];
923 }
924
925 // -------------------------------------------------------------------------------
926 //  setAfsStatus:
927 // -------------------------------------------------------------------------------
928 -(void) setAfsStatus
929 {
930         
931         BOOL afsIsUp = [afsProperty checkAfsStatus];
932         BOOL afsEnabledAtStartup = NO;
933         
934         NSMutableString *commandOutput = [NSMutableString stringWithCapacity:20];
935         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
936                 
937 #if 0
938                         // make the parameter to call the root helper app
939         const char *checkAFSDaemonParam[] = {"check_afs_daemon",  0L};
940         if([[AuthUtil shared] autorize] == noErr) {
941                                 //now disable the launchd configuration
942                 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
943                                                                           args:checkAFSDaemonParam
944                                                                         output:commandOutput];
945                 afsEnabledAtStartup = [commandOutput rangeOfString:@"afshlp:afs daemon registration result:1"].location!=NSNotFound;
946         }
947 #else
948         afsEnabledAtStartup = 1;
949 #endif
950         
951         
952
953
954         [((NSButton *)startStopButton) setTitle: (afsIsUp?kAfsButtonShutdown:kAfsButtonStartup)];
955         
956         NSMutableAttributedString *colorTitle =[[NSMutableAttributedString alloc] initWithAttributedString:[((NSButton *)startStopButton) attributedTitle]];
957     NSRange titleRange = NSMakeRange(0, [colorTitle length]);
958         
959     [colorTitle addAttribute:NSForegroundColorAttributeName
960                        value:(afsIsUp?[NSColor redColor]:[NSColor blackColor])
961                        range:titleRange];
962         
963     [((NSButton *)startStopButton) setAttributedTitle:colorTitle];
964         [checkButtonAfsAtBootTime setState:afsEnabledAtStartup];
965         if(afsIsUp) {
966                 [self startTimer];
967         } else {
968                 [self stopTimer];
969         }
970 }
971
972 // -------------------------------------------------------------------------------
973 //  refreshToken:
974 // -------------------------------------------------------------------------------
975 - (void) refreshTokens:(NSTimer*)theTimer;
976 {
977         if(![tokensLock tryLock]) return;
978         if(tokenList){
979                 [tokenList release];
980         }
981         
982         tokenList = [afsProperty getTokenList];
983         [((NSTableView*)tokensTable) reloadData];
984         [tokensLock unlock];
985 }
986
987 // -------------------------------------------------------------------------------
988 //  removeExtra:
989 // -------------------------------------------------------------------------------
990 - (IBAction) addLink:(id) sender {
991         [NSBundle loadNibNamed:@"SymLinkEdit" owner:self];
992         
993         [NSApp beginSheet: lyncCreationSheet
994            modalForWindow: [[self mainView] window]
995                 modalDelegate: self
996            didEndSelector: @selector(didEndSymlinkSheet:returnCode:contextInfo:)
997                   contextInfo: nil];
998         
999 }
1000
1001 // -------------------------------------------------------------------------------
1002 //  removeExtra:
1003 // -------------------------------------------------------------------------------
1004 - (IBAction) removeLink:(id) sender {
1005         if(!linkConfiguration) return;
1006         int index = 0;
1007         NSArray *keys = [linkConfiguration allKeys];
1008         NSIndexSet *linkToRemove = [tableViewLink selectedRowIndexes];
1009         if( [linkToRemove count] > 0) {
1010                 index = [linkToRemove firstIndex];
1011                 do {
1012                         [linkConfiguration removeObjectForKey:[keys objectAtIndex:index]];
1013                 } while ((index = [linkToRemove indexGreaterThanIndex:index]) != -1);
1014         }
1015         
1016         //write the new configuration
1017         NSData *prefData = nil;
1018         if([linkConfiguration count] > 0) {
1019                 prefData = [NSPropertyListSerialization dataWithPropertyList:linkConfiguration
1020                                                                                                                           format:NSPropertyListXMLFormat_v1_0
1021                                                                                                                          options:0
1022                                                                                                                            error:nil];
1023         }
1024         CFPreferencesSetValue((CFStringRef)PREFERENCE_LINK_CONFIGURATION,
1025                                                   (CFDataRef)prefData,
1026                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1027         
1028         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1029         
1030         //reload the new data
1031         [tableViewLink reloadData];
1032 }
1033
1034 // -------------------------------------------------------------------------------
1035 //  removeExtra:
1036 // -------------------------------------------------------------------------------
1037 - (IBAction) enableLink:(id) sender {
1038         [self writePreferenceFile];
1039 }
1040
1041 // -------------------------------------------------------------------------------
1042 //  removeExtra:
1043 // -------------------------------------------------------------------------------
1044 - (IBAction) manageBackgrounderActivation:(id)sender {
1045         [PListManager launchctlCommand:[(NSButton*)sender state] 
1046                                                 userDomain:YES 
1047                                                         option:[NSArray arrayWithObjects:@"-S", @"Aqua", nil] 
1048                                                  plistName:[NSString stringWithFormat:@"%@.plist", BACKGROUNDER_P_FILE]];
1049         //re ad the status to check taht all is gone well
1050         [backgrounderActivationCheck setState:[PListManager launchdJobState:BACKGROUNDER_P_FILE]];
1051 }
1052
1053 // -------------------------------------------------------------------------------
1054 //  tableViewLinkPerformClick:
1055 // -------------------------------------------------------------------------------
1056 - (IBAction) tableViewLinkPerformClick:(id) sender {
1057         NSLog(@"tableViewLinkPerformClick");
1058 }
1059
1060 // -------------------------------------------------------------------------------
1061 //  - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem
1062 // -------------------------------------------------------------------------------
1063 - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem 
1064 {
1065         //check to see if the cache param tab is the tab that will be selected
1066         if([((NSString*)[tabViewItem identifier]) intValue] == TAB_LINK)
1067         {
1068                 [tableViewLink reloadData];
1069         }
1070 }
1071 // -------------------------------------------------------------------------------
1072 //  tableViewLinkPerformClick:
1073 // -------------------------------------------------------------------------------
1074 - (IBAction) enableDisableKrb5RenewCheck:(id) sender {
1075         //NSLog(@"enableDisableKrb5RenewCheck");
1076         CFPreferencesSetValue((CFStringRef)PREFERENCE_KRB5_CHECK_ENABLE,
1077                                                   (CFNumberRef) [NSNumber numberWithInt:[(NSButton*)sender intValue]],
1078                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1079         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1080                 //notify the backgrounder
1081         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kPrefChangeNotification];
1082 }
1083 // -------------------------------------------------------------------------------
1084 //  tableViewLinkPerformClick:
1085 // -------------------------------------------------------------------------------
1086 - (IBAction) krb5RenewParamChange:(id) sender {
1087         //NSLog(@"krb5RenewParamChange %@", [sender description]);
1088         CFStringRef prefStr = 0L;
1089         NSNumber *newNumberValue = [NSNumber numberWithInt:[(NSButton*)sender intValue]];
1090
1091         switch([(NSControl*)sender tag]){
1092                 case 1:{
1093                         prefStr = (CFStringRef)PREFERENCE_KRB5_RENEW_TIME;
1094                 }
1095                 break;
1096
1097                 case 2:{
1098                         prefStr = (CFStringRef)PREFERENCE_KRB5_SEC_TO_EXPIRE_TIME_FOR_RENEW;
1099                 }
1100                 break;
1101
1102                 case 3:{
1103                         prefStr = (CFStringRef)PREFERENCE_KRB5_RENEW_CHECK_TIME_INTERVALL;
1104                 }
1105                 break;
1106         }
1107
1108                 /*CFPreferencesSetValue(prefStr,
1109                                                   (CFNumberRef)newNumberValue,
1110                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1111         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);*/
1112 }
1113 @end
1114
1115 @implementation AFSCommanderPref (NSTableDataSource)
1116
1117
1118 // -------------------------------------------------------------------------------
1119 //  tableView:
1120 //              Manage the checkbox of CellServDB Table
1121
1122 // -------------------------------------------------------------------------------
1123 - (void)tableView:(NSTableView *)table 
1124    setObjectValue:(id)data 
1125    forTableColumn:(NSTableColumn *)col 
1126                           row:(int)row
1127 {
1128         NSString *identifier = (NSString*)[col identifier];
1129         switch([table tag]){
1130                 case TABLE_TOKENS_LIST:
1131                         break;
1132                         
1133                 case TABLE_CELL_LIST:
1134                         // we are editing checkbox for cellservdb table
1135                         if([identifier intValue] == CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN) {
1136                                 // set the user default cell
1137                                 DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1138                                 [afsProperty setDefaultCellByName:[cellElement getCellName]];
1139                                 //[afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
1140                                 [((NSTableView*)cellList) reloadData];
1141                         } else if([identifier intValue] == CELLSRVDB_TABLE_DFLT_CHECK_COLUMN) {
1142                                 // set the cell for wich the user want to get token
1143                                 DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1144                                 [cellElement setUserDefaultForToken:![cellElement userDefaultForToken]];
1145                         }  
1146                         break;
1147         }
1148         
1149 }
1150
1151
1152 // -------------------------------------------------------------------------------
1153 //  tableView:
1154 //              refresh delegate method for two AFSCommander table
1155 // -------------------------------------------------------------------------------
1156 - (id)  tableView:(NSTableView *) aTableView
1157         objectValueForTableColumn:(NSTableColumn *) aTableColumn
1158                                                   row:(int) rowIndex
1159 {  
1160         
1161         id result = nil;
1162         NSString *identifier = (NSString*)[aTableColumn identifier];
1163         switch([aTableView tag]){
1164                 case TABLE_TOKENS_LIST:
1165                         //We are refreshing tokens table
1166                         result = [self getTableTokensListValue:[identifier intValue] row:rowIndex];
1167                         break;
1168                         
1169                 case TABLE_CELL_LIST:
1170                         //We are refreshing cell db table
1171                         result = [self getTableCelListValue:[identifier intValue] row:rowIndex];
1172                         break;
1173                         
1174                 case TABLE_LINK_LIST:
1175                         result = [self getTableLinkValue:[identifier intValue] row:rowIndex];
1176                         break;
1177
1178                 
1179         }
1180         return result;  
1181 }
1182
1183
1184 // -------------------------------------------------------------------------------
1185 //  getTableCelListValue:
1186 // -------------------------------------------------------------------------------
1187 - (id)getTableTokensListValue:(int) colId row:(int)row
1188 {
1189         id result = nil;
1190         if(!tokenList) return nil;
1191         switch(colId){
1192                 case 0:
1193                         result = (NSString*)[tokenList objectAtIndex:row];
1194                         break;
1195         }
1196         return result;
1197 }
1198
1199
1200 // -------------------------------------------------------------------------------
1201 //  getTableCelListValue:
1202 // -------------------------------------------------------------------------------
1203 - (id)getTableCelListValue:(int) colId row:(int)row
1204 {
1205         id result = nil;
1206         //NSMutableArray *cellArray = [afsProperty getCellList];
1207         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1208         switch(colId){
1209                 case CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN:
1210                         result = [NSNumber numberWithInt:[cellElement userDefaultForCell]];
1211                         break;
1212                         
1213                 case CELLSRVDB_TABLE_DFLT_CHECK_COLUMN:
1214                         result = [NSNumber numberWithInt:[cellElement userDefaultForToken]];
1215                         break;
1216                 case CELLSRVDB_TABLE_NAME_COLUMN:
1217                         result = [cellElement getCellName];
1218                         break;
1219                         
1220                 case CELLSRVDB_TABLE_DESCRIPTION_COLUMN:
1221                         result = [cellElement getCellComment];
1222                         break;
1223         }
1224         return result;
1225 }
1226
1227 // -------------------------------------------------------------------------------
1228 //  getTableCelListValue:
1229 // -------------------------------------------------------------------------------
1230 - (id)getTableLinkValue:(int) colId row:(int)row
1231 {
1232         id result = nil;
1233         NSArray *allKey = [linkConfiguration allKeys];
1234         switch(colId){
1235                 case TABLE_COLUMN_LINK_NAME:
1236                         result = [allKey objectAtIndex:row];
1237                         break;
1238                         
1239                 case TABLE_COLUMN_LINK_PATH:
1240                         result = [linkConfiguration objectForKey:[allKey objectAtIndex:row]];
1241                         break;
1242         }
1243         return result;
1244 }
1245
1246
1247 // -------------------------------------------------------------------------------
1248 //  numberOfRowsInTableView:
1249 // -------------------------------------------------------------------------------
1250 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
1251 {
1252         int rowCount = 0;
1253         //NSMutableArray *cellArray = nil;
1254         switch([aTableView tag]){
1255                 case TABLE_TOKENS_LIST:
1256                         if(tokenList)  rowCount = [tokenList count];
1257                         break;
1258                         
1259                 case TABLE_CELL_LIST:
1260                         //cellArray = [afsProperty getCellList];
1261                         if(filteredCellDB)  rowCount = [filteredCellDB count];
1262                         break;
1263                         
1264                 case TABLE_LINK_LIST:
1265                         if(linkConfiguration)  rowCount = [linkConfiguration count];
1266                         break;
1267
1268                         
1269         }       
1270         return rowCount;  
1271 }
1272 @end
1273
1274
1275 @implementation AFSCommanderPref (TableDelegate)
1276 // -------------------------------------------------------------------------------
1277 //  selectionShouldChangeInTableView:
1278 // -------------------------------------------------------------------------------
1279 - (BOOL)selectionShouldChangeInTableView:(NSTableView *)aTable
1280 {
1281         switch([aTable tag]){
1282                 case TABLE_TOKENS_LIST:
1283                         
1284                         break;
1285                         
1286                 case TABLE_CELL_LIST:
1287                         [self tableViewCellmanageButtonState:[aTable selectedRow]];
1288                         break;
1289                         
1290                 case TABLE_LINK_LIST:
1291                         break;
1292                         
1293                         
1294         }       
1295         
1296         return YES;
1297 }
1298
1299 // -------------------------------------------------------------------------------
1300 //  tableView:
1301 // -------------------------------------------------------------------------------
1302 - (BOOL)tableView:(NSTableView *)aTable shouldSelectRow:(int)aRow
1303 {
1304         switch([aTable tag]){
1305                 case TABLE_TOKENS_LIST:
1306                         
1307                         break;
1308                         
1309                 case TABLE_CELL_LIST:
1310                         [self tableViewCellmanageButtonState:aRow];
1311                         break;
1312                         
1313                 case TABLE_LINK_LIST:
1314                         break;
1315                         
1316                         
1317         }
1318         
1319         return YES;
1320 }
1321
1322 // -------------------------------------------------------------------------------
1323 //  tableView:
1324 // -------------------------------------------------------------------------------
1325 - (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
1326         NSTableView *aTable = [aNotification object];
1327         switch([aTable tag]){
1328                 case TABLE_TOKENS_LIST:
1329                         break;
1330                         
1331                 case TABLE_CELL_LIST:
1332                         break;
1333                         
1334                 case TABLE_LINK_LIST:
1335                         [self tableViewLinkmanageButtonState:[aTable selectedRowIndexes]];
1336                         break;
1337                         
1338                         
1339         }
1340 }
1341 // -------------------------------------------------------------------------------
1342 //  manageButtonState:
1343 // -------------------------------------------------------------------------------
1344 -(void) tableViewCellmanageButtonState:(int) rowSelected  {
1345         [((NSControl*) cellIpButton) setEnabled:rowSelected >= 0];
1346         [((NSControl*) removeCellButton) setEnabled:rowSelected >= 0];
1347 }
1348
1349 // -------------------------------------------------------------------------------
1350 //  manageButtonState:
1351 // -------------------------------------------------------------------------------
1352 -(void) tableViewLinkmanageButtonState:(NSIndexSet *) rowsSelectedIndex {
1353         [buttonRemoveLink setEnabled:[rowsSelectedIndex count]>0];
1354 }
1355 @end
1356
1357
1358 @implementation AFSCommanderPref (ModalDelegate)
1359 // -------------------------------------------------------------------------------
1360 //  didEndSheet:
1361 // -------------------------------------------------------------------------------
1362 - (void)didEndSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1363 {
1364     [sheet orderOut:self];
1365         //Filter the cellServDb and allocate filtered array
1366         [self searchCellTextEvent:nil];
1367         [((NSTableView*)cellList) reloadData];
1368 }
1369
1370 // -------------------------------------------------------------------------------
1371 //  Klog credential request
1372 // -------------------------------------------------------------------------------
1373 - (void)didEndCredentialSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1374 {
1375         if([((TokenCredentialController*)credentialCommander) takenToken] == YES){
1376                 /*[AFSPropertyManager klog:[((TokenCredentialController*)credentialCommander) uName] 
1377                                                         uPwd:[((TokenCredentialController*)credentialCommander) uPwd] ];*/
1378                 [afsProperty getTokens:true 
1379                                                    usr:[((TokenCredentialController*)credentialCommander) uName] 
1380                                                    pwd:[((TokenCredentialController*)credentialCommander) uPwd]];
1381         }
1382     [sheet orderOut:self];
1383         [self refreshTokens:nil];
1384         //Inform afs menuextra to updata afs status
1385         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
1386
1387 }
1388
1389 // -------------------------------------------------------------------------------
1390 //  Klog credential request
1391 // -------------------------------------------------------------------------------
1392 - (void)didEndInfoSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1393 {
1394         [sheet orderOut:self];
1395 }
1396
1397 // -------------------------------------------------------------------------------
1398 //  symlink edite
1399 // -------------------------------------------------------------------------------
1400 - (void)didEndSymlinkSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1401 {
1402         [lyncCreationSheet orderOut:self];
1403         [self readPreferenceFile];
1404         [tableViewLink reloadData];
1405         
1406 }
1407 @end