/
GPGServices.m
854 lines (706 loc) · 30.1 KB
/
GPGServices.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//
// GPGServices.m
// GPGServices
//
// Created by Robert Goldsmith on 24/06/2006.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//
#import "GPGServices.h"
#import "RecipientWindowController.h"
#import "KeyChooserWindowController.h"
@implementation GPGServices
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[NSApp setServicesProvider:self];
// NSUpdateDynamicServices();
currentTerminateTimer=nil;
[GrowlApplicationBridge setGrowlDelegate:self];
}
#pragma mark -
#pragma mark GPG-Helper
-(void)importKey:(NSString *)inputString
{
NSDictionary *importedKeys = nil;
GPGContext *aContext = [[GPGContext alloc] init];
GPGData* inputData=[[GPGData alloc] initWithDataNoCopy:[inputString dataUsingEncoding:NSUTF8StringEncoding]];
@try {
importedKeys = [aContext importKeyData:inputData];
} @catch(NSException* localException) {
[self displayMessageWindowWithTitleText:@"Import result:"
bodyText:GPGErrorDescription([[[localException userInfo]
objectForKey:@"GPGErrorKey"]
intValue])];
return;
} @finally {
[inputData release];
[aContext release];
}
[[NSAlert alertWithMessageText:@"Import result:"
defaultButton:@"Ok"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:@"%i key(s), %i secret key(s), %i revocation(s) ",
[[importedKeys valueForKey:@"importedKeyCount"] intValue],
[[importedKeys valueForKey:@"importedSecretKeyCount"] intValue],
[[importedKeys valueForKey:@"newRevocationCount"] intValue]]
runModal];
}
+ (NSSet*)myPrivateKeys {
GPGContext* context = [[GPGContext alloc] init];
NSMutableSet* keySet = [NSMutableSet set];
for(GPGKey* k in [NSSet setWithArray:[[context keyEnumeratorForSearchPattern:@"" secretKeysOnly:YES] allObjects]]) {
[keySet addObject:[context refreshKey:k]];
}
[context release];
return keySet;
}
+ (GPGKey*)myPrivateKey {
GPGOptions *myOptions=[[GPGOptions alloc] init];
NSString *keyID=[myOptions optionValueForName:@"default-key"];
[myOptions release];
if(keyID == nil)
return nil;
GPGContext *aContext = [[GPGContext alloc] init];
@try {
GPGKey* defaultKey=[aContext keyFromFingerprint:keyID secretKey:YES];
return defaultKey;
} @catch (NSException* s) {
} @finally {
[aContext release];
}
return nil;
}
#pragma mark -
#pragma mark Validators
+ (KeyValidatorT)canEncryptValidator {
id block = ^(GPGKey* key) {
// A subkey can be expired, without the key being, thus making key useless because it has
// no other subkey...
// We don't care about ownerTrust, validity
for (GPGSubkey *aSubkey in [key subkeys]) {
if ([aSubkey canEncrypt] &&
![aSubkey hasKeyExpired] &&
![aSubkey isKeyRevoked] &&
![aSubkey isKeyInvalid] &&
![aSubkey isKeyDisabled]) {
return YES;
}
}
return NO;
};
return [[block copy] autorelease];
}
+ (KeyValidatorT)canSignValidator {
// Copied from GPGMail's GPGMailBundle.m
KeyValidatorT block = ^(GPGKey* key) {
// A subkey can be expired, without the key being, thus making key useless because it has
// no other subkey...
// We don't care about ownerTrust, validity, subkeys
// Secret keys are never marked as revoked! Use public key
key = [key publicKey];
// If primary key itself can sign, that's OK (unlike what gpgme documentation says!)
if ([key canSign] &&
![key hasKeyExpired] &&
![key isKeyRevoked] &&
![key isKeyInvalid] &&
![key isKeyDisabled]) {
return YES;
}
for (GPGSubkey *aSubkey in [key subkeys]) {
if ([aSubkey canSign] &&
![aSubkey hasKeyExpired] &&
![aSubkey isKeyRevoked] &&
![aSubkey isKeyInvalid] &&
![aSubkey isKeyDisabled]) {
return YES;
}
}
return NO;
};
return [[block copy] autorelease];
}
+ (KeyValidatorT)isActiveValidator {
// Copied from GPGMail's GPGMailBundle.m
KeyValidatorT block = ^(GPGKey* key) {
// Secret keys are never marked as revoked! Use public key
key = [key publicKey];
// If primary key itself can sign, that's OK (unlike what gpgme documentation says!)
if (![key hasKeyExpired] &&
![key isKeyRevoked] &&
![key isKeyInvalid] &&
![key isKeyDisabled]) {
return YES;
}
for (GPGSubkey *aSubkey in [key subkeys]) {
if (![aSubkey hasKeyExpired] &&
![aSubkey isKeyRevoked] &&
![aSubkey isKeyInvalid] &&
![aSubkey isKeyDisabled]) {
return YES;
}
}
return NO;
};
return [[block copy] autorelease];
}
#pragma mark -
#pragma mark Text Stuff
-(NSString *)myFingerprint {
GPGKey* chosenKey = [GPGServices myPrivateKey];
NSSet* availableKeys = [[GPGServices myPrivateKeys] filteredSetUsingPredicate:
[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [GPGServices isActiveValidator]((GPGKey*)evaluatedObject);
}]];
if(chosenKey == nil || availableKeys.count > 1) {
KeyChooserWindowController* wc = [[KeyChooserWindowController alloc] init];
[wc setKeyValidator:[GPGServices isActiveValidator]];
if([wc runModal] == 0)
chosenKey = wc.selectedKey;
else
chosenKey = nil;
[wc release];
}
if(chosenKey != nil)
return [[[chosenKey formattedFingerprint] copy] autorelease];
else
return nil;
}
-(NSString *)myKey {
GPGKey* selectedPrivateKey = [GPGServices myPrivateKey];
NSSet* availableKeys = [[GPGServices myPrivateKeys] filteredSetUsingPredicate:
[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [GPGServices isActiveValidator]((GPGKey*)evaluatedObject);
}]];
if(selectedPrivateKey == nil || availableKeys.count > 1) {
KeyChooserWindowController* wc = [[KeyChooserWindowController alloc] init];
[wc setKeyValidator:[GPGServices isActiveValidator]];
if([wc runModal] == 0)
selectedPrivateKey = wc.selectedKey;
else
selectedPrivateKey = nil;
[wc release];
}
if(selectedPrivateKey == nil)
return nil;
GPGContext* ctx = [[GPGContext alloc] init];
[ctx setUsesArmor:YES];
[ctx setUsesTextMode:YES];
NSData* keyData = nil;
@try {
keyData = [[ctx exportedKeys:[NSArray arrayWithObject:selectedPrivateKey]] data];
if(keyData == nil) {
[[NSAlert alertWithMessageText:@"Exporting key failed."
defaultButton:@"Ok"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:@"Could not export key %@", [selectedPrivateKey shortKeyID]]
runModal];
return nil;
}
} @catch(NSException* localException) {
GPGError error = [[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue];
[self displayMessageWindowWithTitleText:@"Exporting key failed."
bodyText:GPGErrorDescription(error)];
return nil;
} @finally {
[ctx release];
}
return [[[NSString alloc] initWithData:keyData
encoding:NSUTF8StringEncoding] autorelease];
}
-(NSString *)encryptTextString:(NSString *)inputString
{
GPGContext *aContext = [[GPGContext alloc] init];
[aContext setUsesArmor:YES];
BOOL trustsAllKeys = YES;
GPGData *outputData = nil;
RecipientWindowController* rcp = [[RecipientWindowController alloc] init];
int ret = [rcp runModal];
[rcp release];
if(ret != 0) {
[aContext release];
return nil;
} else {
GPGData *inputData=[[GPGData alloc] initWithDataNoCopy:[inputString dataUsingEncoding:NSUTF8StringEncoding]];
BOOL sign = rcp.sign;
NSArray* validRecipients = rcp.selectedKeys;
GPGKey* privateKey = rcp.selectedPrivateKey;
if(rcp.encryptForOwnKeyToo && privateKey) {
validRecipients = [[[NSSet setWithArray:validRecipients]
setByAddingObject:[privateKey publicKey]]
allObjects];
} else {
validRecipients = [[NSSet setWithArray:validRecipients] allObjects];
}
if(privateKey == nil) {
[self displayMessageWindowWithTitleText:@"Encryption failed."
bodyText:@"No usable private key found"];
[inputData release];
[aContext release];
return nil;
}
if(validRecipients.count == 0) {
[self displayMessageWindowWithTitleText:@"Encryption failed."
bodyText:@"No valid recipients found"];
[inputData release];
[aContext release];
return nil;
}
@try {
if(sign) {
[aContext addSignerKey:privateKey];
outputData=[aContext encryptedSignedData:inputData withKeys:validRecipients trustAllKeys:trustsAllKeys];
} else {
outputData=[aContext encryptedData:inputData withKeys:validRecipients trustAllKeys:trustsAllKeys];
}
} @catch(NSException* localException) {
outputData = nil;
switch(GPGErrorCodeFromError([[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue]))
{
case GPGErrorNoData:
[self displayMessageWindowWithTitleText:@"Encryption failed."
bodyText:@"No encryptable text was found within the selection."];
break;
case GPGErrorCancelled:
break;
default: {
GPGError error = [[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue];
[self displayMessageWindowWithTitleText:@"Encryption failed."
bodyText:GPGErrorDescription(error)];
}
}
return nil;
} @finally {
[inputData release];
[aContext release];
}
}
return [[[NSString alloc] initWithData:[outputData data] encoding:NSUTF8StringEncoding] autorelease];
}
-(NSString *)decryptTextString:(NSString *)inputString
{
GPGData *outputData = nil;
GPGContext *aContext = [[GPGContext alloc] init];
GPGData *inputData=[[GPGData alloc] initWithDataNoCopy:[inputString dataUsingEncoding:NSUTF8StringEncoding]];
@try {
[aContext setPassphraseDelegate:self];
outputData = [aContext decryptedData:inputData];
} @catch (NSException* localException) {
outputData = nil;
switch(GPGErrorCodeFromError([[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue]))
{
case GPGErrorNoData:
[self displayMessageWindowWithTitleText:@"Decryption failed."
bodyText:@"No decryptable text was found within the selection."];
break;
case GPGErrorCancelled:
break;
default: {
GPGError error = [[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue];
[self displayMessageWindowWithTitleText:@"Decryption failed."
bodyText:GPGErrorDescription(error)];
}
}
return nil;
} @finally {
[inputData release];
[aContext release];
}
return [[[NSString alloc] initWithData:[outputData data] encoding:NSUTF8StringEncoding] autorelease];
}
-(NSString *)signTextString:(NSString *)inputString
{
GPGContext *aContext = [[GPGContext alloc] init];
[aContext setPassphraseDelegate:self];
GPGData *inputData=[[GPGData alloc] initWithDataNoCopy:[inputString dataUsingEncoding:NSUTF8StringEncoding]];
GPGKey* chosenKey = [GPGServices myPrivateKey];
NSSet* availableKeys = [[GPGServices myPrivateKeys] filteredSetUsingPredicate:
[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [GPGServices canSignValidator]((GPGKey*)evaluatedObject);
}]];
if(chosenKey == nil || availableKeys.count > 1) {
KeyChooserWindowController* wc = [[KeyChooserWindowController alloc] init];
[wc setKeyValidator:[GPGServices canSignValidator]];
if([wc runModal] == 0)
chosenKey = wc.selectedKey;
else
chosenKey = nil;
[wc release];
} else if(availableKeys.count == 1) {
chosenKey = [availableKeys anyObject];
}
if(chosenKey != nil) {
[aContext clearSignerKeys];
[aContext addSignerKey:chosenKey];
} else {
[inputData release];
[aContext release];
return nil;
}
GPGData *outputData = nil;
@try {
outputData = [aContext signedData:inputData signatureMode:GPGSignatureModeClear];
} @catch(NSException* localException) {
outputData = nil;
switch(GPGErrorCodeFromError([[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue]))
{
case GPGErrorNoData:
[self displayMessageWindowWithTitleText:@"Signing failed."
bodyText:@"No signable text was found within the selection."];
break;
case GPGErrorBadPassphrase:
[self displayMessageWindowWithTitleText:@"Signing failed."
bodyText:@"The passphrase is incorrect."];
break;
case GPGErrorUnusableSecretKey:
[self displayMessageWindowWithTitleText:@"Signing failed."
bodyText:@"The default secret key is unusable."];
break;
case GPGErrorCancelled:
break;
default: {
GPGError error = [[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue];
[self displayMessageWindowWithTitleText:@"Signing failed."
bodyText:GPGErrorDescription(error)];
}
}
return nil;
} @finally {
[inputData release];
[aContext release];
}
return [[[NSString alloc] initWithData:[outputData data] encoding:NSUTF8StringEncoding] autorelease];
}
-(void)verifyTextString:(NSString *)inputString
{
GPGContext *aContext = [[GPGContext alloc] init];
GPGData* inputData=[[GPGData alloc] initWithDataNoCopy:[inputString dataUsingEncoding:NSUTF8StringEncoding]];
@try {
NSArray* sigs = [aContext verifySignedData:inputData originalData:nil];
if([sigs count]>0)
{
GPGSignature* sig=[sigs objectAtIndex:0];
if(GPGErrorCodeFromError([sig status])==GPGErrorNoError)
{
NSString* userID = [[aContext keyFromFingerprint:[sig fingerprint] secretKey:NO] userID];
NSString* validity = [sig validityDescription];
[[NSAlert alertWithMessageText:@"Verification successful."
defaultButton:@"Ok"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:@"Good signature (%@ trust):\n\"%@\"",validity,userID]
runModal];
}
else {
[self displayMessageWindowWithTitleText:@"Verification FAILED."
bodyText:GPGErrorDescription([sig status])];
}
}
else {
//Looks like sigs.count == 0 when we have encrypted text but no signature
//[self displayMessageWindowWithTitleText:@"Verification error."
// bodyText:@"Unable to verify due to an internal error"];
[self displayMessageWindowWithTitleText:@"Verification failed."
bodyText:@"No signatures found within the selection."];
}
} @catch(NSException* localException) {
if(GPGErrorCodeFromError([[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue])==GPGErrorNoData)
[self displayMessageWindowWithTitleText:@"Verification failed."
bodyText:@"No verifiable text was found within the selection"];
else {
GPGError error = [[[localException userInfo] objectForKey:@"GPGErrorKey"] intValue];
[self displayMessageWindowWithTitleText:@"Verification failed."
bodyText:GPGErrorDescription(error)];
}
return;
} @finally {
[inputData release];
[aContext release];
}
}
#pragma mark -
#pragma mark File Stuff
- (void)signFile:(NSURL*)file withKeys:(NSArray*)keys {
@try {
//Generate .sig file
GPGContext* signContext = [[[GPGContext alloc] init] autorelease];
[signContext setUsesArmor:YES];
for(GPGKey* k in keys)
[signContext addSignerKey:k];
GPGData* dataToSign = [[[GPGData alloc] initWithContentsOfFile:[file path]] autorelease];
GPGData* signData = [signContext signedData:dataToSign signatureMode:GPGSignatureModeDetach];
NSURL* sigURL = [file URLByAppendingPathExtension:@"sig"];
[[signData data] writeToURL:sigURL atomically:YES];
} @catch (NSException* e) {
[GrowlApplicationBridge notifyWithTitle:@"Signing failed"
description:[file lastPathComponent]
notificationName:@"SigningFileFailed"
iconData:[NSData data]
priority:0
isSticky:NO
clickContext:file];
}
}
- (void)encryptFiles:(NSArray*)files {
BOOL trustAllKeys = YES;
NSLog(@"encrypting files: %@...", [files componentsJoinedByString:@","]);
if(files.count == 0)
return;
else if(files.count > 1)
[self displayMessageWindowWithTitleText:@"Verification error."
bodyText:@"Only one file at a time please."];
RecipientWindowController* rcp = [[RecipientWindowController alloc] init];
int ret = [rcp runModal];
[rcp release];
if(ret != 0) {
//User pressed 'cancel'
return;
} else {
BOOL sign = rcp.sign;
NSArray* validRecipients = rcp.selectedKeys;
GPGKey* privateKey = rcp.selectedPrivateKey;
if(rcp.encryptForOwnKeyToo && privateKey) {
validRecipients = [[[NSSet setWithArray:validRecipients]
setByAddingObject:[privateKey publicKey]]
allObjects];
} else {
validRecipients = [[NSSet setWithArray:validRecipients] allObjects];
}
NSFileManager* fmgr = [[[NSFileManager alloc] init] autorelease];
for(NSString* file in files) {
BOOL isDirectory = YES;
BOOL fileExists = [fmgr fileExistsAtPath:file isDirectory:&isDirectory];
if(fileExists == NO) {
[self displayMessageWindowWithTitleText:@"File doesn't exist"
bodyText:@"Please try again"];
return;
}
if(isDirectory == YES) {
[self displayMessageWindowWithTitleText:@"File is a directory"
bodyText:@"Encryption of directories isn't supported"];
return;
}
NSError* error = nil;
NSNumber* fileSize = [[fmgr attributesOfItemAtPath:file error:&error] valueForKey:NSFileSize];
double megabytes = [fileSize doubleValue] / 1048576;
NSLog(@"fileSize: %@Mb", [NSNumberFormatter localizedStringFromNumber:[NSNumber numberWithDouble:megabytes]
numberStyle:NSNumberFormatterDecimalStyle]);
if(megabytes > 10) {
int ret = [[NSAlert alertWithMessageText:@"Large File"
defaultButton:@"Continue"
alternateButton:@"Cancel"
otherButton:nil
informativeTextWithFormat:@"Encryption will take a long time.\nPress 'Cancel' to abort."]
runModal];
if(ret == NSAlertAlternateReturn)
return;
}
//NSURL* destination = [self getFilenameForSavingWithSuggestedPath:file
// withSuggestedExtension:@".gpg"];
NSURL* destination = [[NSURL fileURLWithPath:file] URLByAppendingPathExtension:@"gpg"];
NSLog(@"destination: %@", destination);
if(destination == nil)
return;
if(megabytes > 10) {
[GrowlApplicationBridge notifyWithTitle:@"Encrypting..."
description:[file lastPathComponent]
notificationName:@"EncryptionStarted"
iconData:[NSData data]
priority:0
isSticky:NO
clickContext:file];
}
GPGContext* ctx = [[[GPGContext alloc] init] autorelease];
GPGData* gpgData = [[[GPGData alloc] initWithContentsOfFile:file] autorelease];
GPGData* encrypted = [ctx encryptedData:gpgData
withKeys:validRecipients
trustAllKeys:trustAllKeys];
[encrypted.data writeToURL:destination atomically:YES];
if(sign == YES && privateKey != nil)
[self signFile:destination withKeys:[NSArray arrayWithObject:privateKey]];
[GrowlApplicationBridge notifyWithTitle:@"Encryption finished"
description:[destination lastPathComponent]
notificationName:@"EncryptionSucceeded"
iconData:[NSData data]
priority:0
isSticky:NO
clickContext:destination];
}
}
}
#pragma mark -
#pragma mark Service handling routines
-(void)dealWithPasteboard:(NSPasteboard *)pboard
userData:(NSString *)userData
mode:(ServiceModeEnum)mode
error:(NSString **)error {
[self cancelTerminateTimer];
[NSApp activateIgnoringOtherApps:YES];
NSString *pboardString = nil;
if(mode!=MyKeyService && mode!=MyFingerprintService)
{
NSString* type = [pboard availableTypeFromArray:[NSArray arrayWithObjects:
NSStringPboardType,
NSRTFPboardType,
NSFilenamesPboardType,
nil]];
if([type isEqualToString:NSStringPboardType])
{
if(!(pboardString = [pboard stringForType:NSStringPboardType]))
{
*error=[NSString stringWithFormat:@"Error: Could not perform GPG operation. Pasteboard could not supply text string."];
[self exitServiceRequest];
return;
}
}
else if([type isEqualToString:NSRTFPboardType])
{
if(!(pboardString = [pboard stringForType:NSStringPboardType]))
{
*error=[NSString stringWithFormat:@"Error: Could not perform GPG operation. Pasteboard could not supply text string."];
[self exitServiceRequest];
return;
}
}
else
{
*error = NSLocalizedString(@"Error: Could not perform GPG operation.", @"Pasteboard could not supply the string in an acceptible format.");
[self exitServiceRequest];
return;
}
}
NSString *newString=nil;
switch(mode)
{
case SignService:
newString=[self signTextString:pboardString];
break;
case EncryptService:
newString=[self encryptTextString:pboardString];
break;
case DecryptService:
newString=[self decryptTextString:pboardString];
break;
case VerifyService:
[self verifyTextString:pboardString];
break;
case MyKeyService:
newString=[self myKey];
break;
case MyFingerprintService:
newString=[self myFingerprint];
break;
case ImportKeyService:
[self importKey:pboardString];
break;
default:
break;
}
if(newString!=nil)
{
[pboard declareTypes:[NSArray arrayWithObjects:NSStringPboardType,NSRTFPboardType,nil] owner:nil];
[pboard setString:newString forType:NSStringPboardType];
[pboard setString:newString forType:NSRTFPboardType];
}
[self exitServiceRequest];
}
-(void)exitServiceRequest
{
[NSApp hide:self];
[self goneIn60Seconds];
}
-(void)sign:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{[self dealWithPasteboard:pboard userData:userData mode:SignService error:error];}
-(void)encrypt:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{[self dealWithPasteboard:pboard userData:userData mode:EncryptService error:error];}
-(void)decrypt:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{[self dealWithPasteboard:pboard userData:userData mode:DecryptService error:error];}
-(void)verify:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{[self dealWithPasteboard:pboard userData:userData mode:VerifyService error:error];}
-(void)myKey:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{[self dealWithPasteboard:pboard userData:userData mode:MyKeyService error:error];}
-(void)myFingerprint:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{[self dealWithPasteboard:pboard userData:userData mode:MyFingerprintService error:error];}
-(void)importKey:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{[self dealWithPasteboard:pboard userData:userData mode:ImportKeyService error:error];}
-(void)encryptFile:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSData *data = [pboard dataForType:NSFilenamesPboardType];
NSString* fileErrorStr = nil;
NSArray *filenames = [NSPropertyListSerialization
propertyListFromData:data
mutabilityOption:kCFPropertyListImmutable
format:nil
errorDescription:&fileErrorStr];
if(fileErrorStr) {
NSLog(@"error while getting files form pboard: %@", fileErrorStr);
*error = fileErrorStr;
} else {
[self encryptFiles:filenames];
}
[pool release];
}
#pragma mark -
#pragma mark UI Helpher
- (NSURL*)getFilenameForSavingWithSuggestedPath:(NSString*)path
withSuggestedExtension:(NSString*)ext {
NSSavePanel* savePanel = [NSSavePanel savePanel];
savePanel.title = @"Choose Destination";
savePanel.directory = [path stringByDeletingLastPathComponent];
if(ext == nil)
ext = @".gpg";
[savePanel setNameFieldStringValue:[[path lastPathComponent]
stringByAppendingString:ext]];
if([savePanel runModal] == NSFileHandlingPanelOKButton)
return savePanel.URL;
else
return nil;
}
-(void)displayMessageWindowWithTitleText:(NSString *)title bodyText:(NSString *)body
{
/*
[messageHeadingText setStringValue:title];
[messageBodyText setStringValue:body];
[NSApp runModalForWindow:messageWindow];
[messageWindow close];
*/
[[NSAlert alertWithMessageText:title
defaultButton:@"Ok"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:[NSString stringWithFormat:@"%@", body]] runModal];
}
-(NSString *)context:(GPGContext *)context passphraseForKey:(GPGKey *)key again:(BOOL)again
{
[passphraseText setStringValue:@""];
int flag=[NSApp runModalForWindow:passphraseWindow];
NSString *passphrase=[[[passphraseText stringValue] copy] autorelease];
[passphraseWindow close];
if(flag)
return passphrase;
else
return nil;
}
-(IBAction)closeModalWindow:(id)sender{
[NSApp stopModalWithCode:[sender tag]];
[recipientWindow close];
}
//
//Timer based application termination
//
-(void)cancelTerminateTimer
{
[currentTerminateTimer invalidate];
currentTerminateTimer=nil;
}
-(void)goneIn60Seconds
{
if(currentTerminateTimer!=nil)
[self cancelTerminateTimer];
currentTerminateTimer=[NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(selfQuit:) userInfo:nil repeats:NO];
}
-(void)selfQuit:(NSTimer *)timer
{
[NSApp terminate:self];
}
@end