OSDN Git Service

Add MS7619SE
[uclinux-h8/uClinux-dist.git] / openswan / osxApp / MainMenuController.m
1 //
2 //  MainMenuController.m
3 //  Openswan
4 //
5 //  Created by Jose Quaresma on 11/6/09.
6 //  Copyright 2009 __MyCompanyName__. All rights reserved.
7 //
8
9 #import "MainMenuController.h"
10 #import "AdvMenuController.h"
11 #import "PreferenceController.h"
12 #import "ConnectionsDB.h"
13 #import "Connection.h"
14 #import <AppKit/NSCell.h>
15
16 //Stuff from Openswan
17 #define OPENSWAN_COCOA_APP 1
18 #import <sys/queue.h>
19 #import "ipsecconf/confread.h"
20 #import "openswan/passert.h"
21 #import "oswlog.h"
22 #import "programs/pluto/log.h"
23 void exit_tool(int x)
24 {
25         exit(x);
26 }
27 char* progname = "openswan \0";
28 int verbose=0;
29 int warningsarefatal = 0;
30 #import "ipsecconf/confwrite.h"
31
32
33 @implementation MainMenuController
34 @synthesize db, connTime, connDuration, timer, connDurationPrint, selConn;
35
36 - (IBAction)showAdvMenu: (id)sender
37 {
38         //Is advMenuController nil?
39         if(!advMenuController){
40                 advMenuController = [[AdvMenuController alloc] init];
41                 [advMenuController setSelItemIndex:[[self selConn] indexOfSelectedItem]];
42         }
43         else{
44                 [[advMenuController selConn] selectItemAtIndex:[[self selConn] indexOfSelectedItem]];
45         }
46         
47         NSLog(@"Showing %@", advMenuController);
48         [advMenuController showWindow: self];
49 }
50
51 - (IBAction)connDisc: (id) sender
52 {
53         if([sender state] == NSOnState){
54                 [connView setHidden:YES];
55                 [discView setHidden:NO];
56         }
57         else{
58                 [connView setHidden:NO];
59                 [discView setHidden:YES];
60         }
61 }
62
63 - (void)awakeFromNib
64 {
65         [NSApp setDelegate: self];
66         
67         [GrowlApplicationBridge setGrowlDelegate:self];
68         
69         [self loadDataFromDisk];
70         
71         [connView setHidden:NO];
72         [discView setHidden:YES];
73         [self setConnDurationPrint:[NSString stringWithString:@"0:0:0"]];
74 }
75
76 - (void) applicationWillTerminate: (NSNotification *)note
77 {
78         [self saveDataToDisk];
79 }
80
81 - (IBAction)showPreferencePanel: (id)sender
82 {
83         //Is preferenceController nil?
84         if(!preferenceController){
85                 preferenceController = [[PreferenceController alloc] init];
86         }
87         NSLog(@"Showing %@", preferenceController);
88         [preferenceController showWindow: self];
89 }
90
91 #pragma mark archiving
92 - (NSString *) pathForDataFile
93 {
94         NSFileManager *fileManager = [NSFileManager defaultManager];
95     
96         NSString *folder = @"~/Library/Application Support/Openswan/";
97         folder = [folder stringByExpandingTildeInPath];
98         
99         if ([fileManager fileExistsAtPath: folder] == NO)
100         {
101                 [fileManager createDirectoryAtPath: folder attributes: nil];
102         }
103     
104         NSString *fileName = @"Openswan.data";
105         return [folder stringByAppendingPathComponent:fileName];
106 }
107
108 - (void) saveDataToDisk
109 {
110         NSLog(@"Saving data to disk");
111         NSString* path = [self pathForDataFile];
112         
113         NSMutableDictionary* rootObject;
114         rootObject = [NSMutableDictionary dictionary];
115     
116         [rootObject setValue:[self db] forKey:@"db"];
117         [NSKeyedArchiver archiveRootObject:rootObject toFile:path];
118 }
119
120 - (void) loadDataFromDisk
121 {
122         NSLog(@"Loading data from disk");
123         NSString* path        = [self pathForDataFile];
124         NSDictionary* rootObject;
125     
126         rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
127         [self setDb:[rootObject valueForKey:@"db"]];
128         
129         //If there is no previously saved data
130         if(db==NULL)
131         {
132                 [self setDb:[ConnectionsDB sharedInstance]];    
133         }       
134 }
135
136 - (IBAction)saveData: (id)sender
137 {
138         [self saveDataToDisk];
139 }
140 - (IBAction)loadData: (id)sender
141 {
142         [self loadDataFromDisk];
143 }
144
145 //Helper Tool
146
147 static OSStatus DoConnect(CFStringRef reqConnName)
148 // This code shows how to do a typical BetterAuthorizationSample privileged operation 
149 // in straight C.  In this case, it does the low-numbered ports operation, which 
150 // returns three file descriptors that are bound to low-numbered TCP ports.
151 {
152     OSStatus        err;
153     CFBundleRef     bundle;
154     CFStringRef     bundleID;
155     CFIndex         keyCount;
156     CFStringRef     keys[2];
157     CFTypeRef       values[2];
158     CFDictionaryRef request;
159     CFDictionaryRef response;
160     BASFailCode     failCode;
161     
162     // Pre-conditions
163
164         
165     // Get our bundle information.
166     
167     bundle = CFBundleGetMainBundle();
168     assert(bundle != NULL);
169     
170     bundleID = CFBundleGetIdentifier(bundle);
171     assert(bundleID != NULL);
172     
173     // Create the request.  The request always contains the kBASCommandKey that 
174     // describes the command to do.  It also, optionally, contains the 
175         // kSampleLowNumberedPortsForceFailure key that tells the tool to always return 
176         // an error.  The purpose of this is to test our error handling path (do we leak 
177         // descriptors, for example). 
178     
179     keyCount = 0;
180     keys[keyCount]   = CFSTR(kBASCommandKey);
181     values[keyCount] = CFSTR(kConnectCommand);
182     keyCount += 1;
183         
184         keys[keyCount]   = CFSTR("connName");
185     values[keyCount] = CFStringCreateCopy(NULL, reqConnName);
186     keyCount += 1;
187         
188     request = CFDictionaryCreate(
189                                                                  NULL, 
190                                                                  (const void **) keys, 
191                                                                  (const void **) values, 
192                                                                  keyCount, 
193                                                                  &kCFTypeDictionaryKeyCallBacks, 
194                                                                  &kCFTypeDictionaryValueCallBacks
195                                                                  );
196     assert(request != NULL);
197     
198     response = NULL;
199     
200     // Execute it.
201         
202         err = BASExecuteRequestInHelperTool(
203                                                                                 gAuth, 
204                                                                                 kCommandSet, 
205                                                                                 bundleID, 
206                                                                                 request, 
207                                                                                 &response
208                                                                                 );
209         
210     // If it failed, try to recover.
211         
212     if ( (err != noErr) && (err != userCanceledErr) ) {
213         int alertResult;
214         
215         failCode = BASDiagnoseFailure(gAuth, bundleID);
216         
217         // At this point we tell the user that something has gone wrong and that we need 
218         // to authorize in order to fix it.  Ideally we'd use failCode to describe the type of 
219         // error to the user.
220                 
221         alertResult = NSRunAlertPanel(@"Needs Install", @"BAS needs to install", @"Install", @"Cancel", NULL);
222         
223         if ( alertResult == NSAlertDefaultReturn ) {
224             // Try to fix things.
225             
226             err = BASFixFailure(gAuth, (CFStringRef) bundleID, CFSTR("InstallTool"), CFSTR("HelperTool"), failCode);
227                         
228             // If the fix went OK, retry the request.
229             
230             if (err == noErr) {
231                 err = BASExecuteRequestInHelperTool(
232                                                                                                         gAuth, 
233                                                                                                         kCommandSet, 
234                                                                                                         bundleID, 
235                                                                                                         request, 
236                                                                                                         &response
237                                                                                                         );
238             }
239         } else {
240             err = userCanceledErr;
241         }
242     }
243         
244     // If all of the above went OK, it means that the IPC to the helper tool worked.  We 
245     // now have to check the response dictionary to see if the command's execution within 
246     // the helper tool was successful.
247     
248     if (err == noErr) {
249         err = BASGetErrorFromResponse(response);
250     }
251     
252     // Extract the descriptors from the response and copy them out to our caller.
253     
254     if (err == noErr) {
255                 CFStringRef returnString;
256                 
257                 returnString = (CFStringRef) CFDictionaryGetValue(response, CFSTR(kBASTestString));
258                 NSLog(@"Command ran: %@", returnString);
259     }
260                  
261     
262     if (response != NULL) {
263         CFRelease(response);
264     }
265
266     return err;
267 }
268
269 - (IBAction)connect: (id)sender
270 {       
271         if([self timer] == nil) {
272                 [self setConnTime:[NSDate date]];
273                 
274                 NSTimer *tmpTimer = [NSTimer scheduledTimerWithTimeInterval:1
275                                                                                                                          target:self 
276                                                                                                                    selector:@selector(updateConnDuration:)
277                                                                                                                    userInfo:nil 
278                                                                                                                         repeats:YES];
279                 [self setTimer:tmpTimer];
280         }
281         else {
282                 [[self timer] invalidate];
283                 //[[self timer] release];
284                 [self setTimer:nil];
285                 [self setConnDuration:0];
286                 [self setConnDurationPrint:[NSString stringWithString:@"0:0:0"]];
287         }
288         if([sender state] == NSOnState){
289                 [connView setHidden:YES];
290                 [discView setHidden:NO];
291                 
292                 [self saveConnToFile];
293                 
294                 ///////////////
295                 OSStatus    err;
296                 
297                 // Call the C code to do the real work.
298                 
299                 Connection *conn = [[[ConnectionsDB sharedInstance] connDB] objectAtIndex:[selConn indexOfSelectedItem]];
300                 
301                 char connName[100];
302                 [[conn connName] getCString:connName maxLength:100 encoding:NSMacOSRomanStringEncoding];
303                 
304                 CFStringRef reqConnName = CFStringCreateWithCString(NULL, connName, CFStringGetSystemEncoding());
305                 
306                 err = DoConnect(reqConnName);
307                 
308                 // Log our results.
309
310                 
311                 
312                 //////////////
313                 
314                 [GrowlApplicationBridge
315                  notifyWithTitle:@"Connected" 
316                  description:@"Connection was established" 
317                  notificationName:@"Openswan Growl Notification" 
318                  iconData:nil 
319                  priority:0 
320                  isSticky:NO 
321                  clickContext:nil];
322         }
323         else{
324                 [connView setHidden:NO];
325                 [discView setHidden:YES];
326                 
327                 //Delete conn file?
328                 /*
329                 Connection *conn = [[[ConnectionsDB sharedInstance] connDB] objectAtIndex:[selConn indexOfSelectedItem]];
330                 NSString *origFileName = [conn connName];
331                 NSString *fileName = [origFileName stringByAppendingFormat:@".conf"];
332                 NSString *origPath = @"~/Library/Application Support/Openswan";
333                 NSString *filePath = [origPath stringByAppendingPathComponent:fileName];
334                 NSString *path = [filePath stringByStandardizingPath];
335                 
336                 NSFileManager *fileManager = [NSFileManager defaultManager];
337                 if ([fileManager fileExistsAtPath: path] == YES)
338                 {
339                         [fileManager removeFileAtPath:path handler:nil];
340                 }
341                 */
342                 
343                 [GrowlApplicationBridge
344                  notifyWithTitle:@"Disconnected" 
345                  description:@"Connection was closed" 
346                  notificationName:@"Openswan Growl Notification" 
347                  iconData:nil 
348                  priority:0 
349                  isSticky:NO 
350                  clickContext:nil];
351         }
352 }
353
354 - (void)updateConnDuration: (NSTimer*)aTimer
355 {
356         NSDate* now = [NSDate date];
357         [self setConnDuration:[now timeIntervalSinceDate: connTime]];
358         int hours = (NSInteger)connDuration / 3600;
359         [self setConnDuration:(NSInteger)connDuration % 3600];
360         int mins = (NSInteger)connDuration / 60;
361         [self setConnDuration:(NSInteger)connDuration % 60];
362         int secs = (NSInteger)connDuration;
363         [self setConnDurationPrint:[NSString stringWithFormat:@"%d:%d:%d", hours, mins, secs]];
364 }
365
366 //Growl
367 - (NSDictionary*)registrationDictionaryForGrowl
368 {
369         NSArray *notifications;
370         notifications = [NSArray arrayWithObject:@"Openswan Growl Notification"];
371         
372         NSDictionary *dict;
373         dict = [NSDictionary dictionaryWithObjectsAndKeys:
374                         notifications, GROWL_NOTIFICATIONS_ALL,
375                         notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
376         
377         return dict;
378 }
379
380 int main(int argc, char *argv[])
381 {
382     OSStatus    junk;
383     
384     // Create the AuthorizationRef that we'll use through this application.  We ignore 
385     // any error from this.  A failure from AuthorizationCreate is very unusual, and if it 
386     // happens there's no way to recover; Authorization Services just won't work.
387         
388     junk = AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &gAuth);
389     assert(junk == noErr);
390     assert( (junk == noErr) == (gAuth != NULL) );
391         
392         // For each of our commands, check to see if a right specification exists and, if not,
393     // create it.
394     //
395     // The last parameter is the name of a ".strings" file that contains the localised prompts 
396     // for any custom rights that we use.
397     
398         BASSetDefaultRules(
399                                            gAuth, 
400                                            kCommandSet, 
401                                            CFBundleGetIdentifier(CFBundleGetMainBundle()), 
402                                            CFSTR("AuthorizationPrompts")
403                                            );
404
405     return NSApplicationMain(argc,  (const char **) argv);
406 }
407
408 #pragma mark writeFile
409 - (void) saveConnToFile {
410         struct starter_config *cfg = NULL;
411         struct starter_conn *new_conn = NULL;
412         err_t perr = NULL;
413         FILE *file = NULL;
414         
415         char *cPath = "../../test/testGUI.cfg";
416         
417         //Connection *conn = [[[ConnectionsDB sharedInstance] connDB] objectAtIndex:[selConn indexOfSelectedItem]];
418         
419         //file pathname
420         /*
421          NSString *origFileName = [conn connName];
422          NSString *fileName = [origFileName stringByAppendingFormat:@".conf"];
423          NSString *origPath = @"~/Library/Application Support/Openswan";
424          NSString *filePath = [origPath stringByAppendingPathComponent:fileName];
425          NSString *path = [filePath stringByStandardizingPath];
426          char cPath[100];
427          [path getCString:cPath maxLength:100 encoding:NSMacOSRomanStringEncoding];
428          */
429         
430         cfg = (struct starter_config *) malloc(sizeof(struct starter_config));
431         if (!cfg) printf("can't allocate memory");
432         
433         memset(cfg, 0, sizeof(struct starter_config));
434         
435         ipsecconf_default_values(cfg);
436         
437         //NSString to char*
438         //char cConnName[20];
439         //[[conn connName] getCString:cConnName maxLength:20 encoding:NSMacOSRomanStringEncoding];
440         
441         new_conn = alloc_add_conn(cfg, "test", &perr);
442         if(new_conn == NULL) printf("%s", perr);
443         
444         cfg->setup.options_set[KBF_NATTRAVERSAL] = 1;
445         cfg->setup.options[KBF_NATTRAVERSAL] = 0;
446         
447         cfg->setup.strings_set[KSF_PROTOSTACK] = 1;
448         cfg->setup.strings[KSF_PROTOSTACK] = strdup("netkey");
449         
450         new_conn->connalias = strdup("anotheralias");
451         
452         new_conn->left.rsakey2 = (unsigned char *)"0s23489234ba28934243";
453     new_conn->left.rsakey1 = (unsigned char *)"0sabcdabcdabcd";
454         
455         new_conn->desired_state = STARTUP_START;
456         
457         new_conn->options_set[KBF_AUTO] = 1;
458         new_conn->options[KBF_AUTO] = STARTUP_START;
459         
460         new_conn->left.cert = "/my/cert/file";
461         
462         file = fopen(cPath,"w");
463         confwrite(cfg, file);
464         fclose(file);    
465 }
466
467
468 @end