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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
use std::ffi::CString;
use std::fmt;
use std::io;
use std::mem;
use std::ptr;
use libc;
use ffi;
use {Protocol, Token, Wrapper};
use error::{self, Error, Result};
use engine::{EngineInfo, EngineInfoIter};
use data::Data;
use keys::Key;
use trust::TrustItem;
use notation::{self, SignatureNotationIter};
use edit;
use ops;
use utils::{self, FdWriter, StrResult};
pub struct Context {
raw: ffi::gpgme_ctx_t,
}
impl Context {
pub fn new(_: Token) -> Result<Self> {
unsafe {
let mut ctx = ptr::null_mut();
return_err!(ffi::gpgme_new(&mut ctx));
Ok(Context::from_raw(ctx))
}
}
pub fn has_armor(&self) -> bool {
unsafe { ffi::gpgme_get_armor(self.raw) != 0 }
}
pub fn set_armor(&mut self, enabled: bool) {
unsafe {
ffi::gpgme_set_armor(self.raw, enabled as libc::c_int);
}
}
pub fn text_mode(&self) -> bool {
unsafe { ffi::gpgme_get_textmode(self.raw) != 0 }
}
pub fn set_text_mode(&mut self, enabled: bool) {
unsafe {
ffi::gpgme_set_textmode(self.raw, enabled as libc::c_int);
}
}
pub fn protocol(&self) -> Protocol {
unsafe { Protocol::from_raw(ffi::gpgme_get_protocol(self.raw)) }
}
pub fn set_protocol(&mut self, proto: Protocol) -> Result<()> {
unsafe {
return_err!(ffi::gpgme_set_protocol(self.raw, proto.raw()));
}
Ok(())
}
pub fn with_passphrase_handler<H, F, R>(&mut self, mut handler: H, f: F) -> R
where H: PassphraseHandler, F: FnOnce(&mut Context) -> R {
unsafe {
let mut old = (None, ptr::null_mut());
ffi::gpgme_get_passphrase_cb(self.raw, &mut old.0, &mut old.1);
ffi::gpgme_set_passphrase_cb(self.raw,
Some(passphrase_callback::<H>),
(&mut handler as *mut _) as *mut _);
let _guard = PassphraseHandlerGuard {
ctx: self.raw,
old: old,
};
f(self)
}
}
pub fn with_progress_handler<H, F, R>(&mut self, mut handler: H, f: F) -> R
where H: ProgressHandler, F: FnOnce(&mut Context) -> R {
unsafe {
let mut old = (None, ptr::null_mut());
ffi::gpgme_get_progress_cb(self.raw, &mut old.0, &mut old.1);
ffi::gpgme_set_progress_cb(self.raw,
Some(progress_callback::<H>),
(&mut handler as *mut _) as *mut _);
let _guard = ProgressHandlerGuard {
ctx: self.raw,
old: old,
};
f(self)
}
}
pub fn with_status_handler<H, F, R>(&mut self, mut handler: H, f: F) -> R
where H: StatusHandler, F: FnOnce(&mut Context) -> R {
unsafe {
let mut old = (None, ptr::null_mut());
ffi::gpgme_get_status_cb(self.raw, &mut old.0, &mut old.1);
ffi::gpgme_set_status_cb(self.raw,
Some(status_callback::<H>),
(&mut handler as *mut _) as *mut _);
let _guard = StatusHandlerGuard {
ctx: self.raw,
old: old,
};
f(self)
}
}
pub fn engine_info(&self) -> EngineInfoIter<Context> {
unsafe { EngineInfoIter::from_list(ffi::gpgme_ctx_get_engine_info(self.raw)) }
}
pub fn get_engine_info(&self, proto: Protocol) -> Option<EngineInfo<Context>> {
self.engine_info().find(|info| info.protocol() == proto)
}
pub fn set_engine_filename<S>(&self, proto: Protocol, filename: S) -> Result<()>
where S: Into<Vec<u8>> {
let filename = try!(CString::new(filename));
unsafe {
return_err!(ffi::gpgme_ctx_set_engine_info(self.raw, proto.raw(),
filename.as_ptr(), ptr::null()));
}
Ok(())
}
pub fn set_engine_home_dir<S>(&self, proto: Protocol, home_dir: S) -> Result<()>
where S: Into<Vec<u8>> {
let home_dir = try!(CString::new(home_dir));
unsafe {
return_err!(ffi::gpgme_ctx_set_engine_info(self.raw, proto.raw(),
ptr::null(), home_dir.as_ptr()));
}
Ok(())
}
pub fn set_engine_info<S1, S2>(&mut self, proto: Protocol, filename: S1, home_dir: S2)
-> Result<()>
where S1: Into<Vec<u8>>, S2: Into<Vec<u8>> {
let filename = try!(CString::new(filename));
let home_dir = try!(CString::new(home_dir));
unsafe {
let filename = filename.as_ptr();
let home_dir = home_dir.as_ptr();
return_err!(ffi::gpgme_ctx_set_engine_info(self.raw, proto.raw(), filename, home_dir));
}
Ok(())
}
pub fn find_trust_items<S: Into<Vec<u8>>>(&mut self, pattern: S, max_level: i32)
-> Result<TrustItems> {
let pattern = try!(CString::new(pattern.into()));
unsafe {
return_err!(ffi::gpgme_op_trustlist_start(self.raw,
pattern.as_ptr(),
max_level.into()));
}
Ok(TrustItems { ctx: self })
}
pub fn offline(&self) -> bool {
unsafe { ffi::gpgme_get_offline(self.raw) != 0 }
}
pub fn set_offline(&mut self, enabled: bool) {
unsafe {
ffi::gpgme_set_offline(self.raw, enabled as libc::c_int);
}
}
pub fn key_list_mode(&self) -> ops::KeyListMode {
unsafe { ops::KeyListMode::from_bits_truncate(ffi::gpgme_get_keylist_mode(self.raw)) }
}
pub fn set_key_list_mode(&mut self, mask: ops::KeyListMode) -> Result<()> {
unsafe {
let old = ffi::gpgme_get_keylist_mode(self.raw);
return_err!(ffi::gpgme_set_keylist_mode(self.raw,
mask.bits() |
(old & !ops::KeyListMode::all().bits())));
}
Ok(())
}
pub fn keys(&mut self) -> Result<Keys> {
Keys::new(self, None::<String>, false)
}
pub fn secret_keys(&mut self) -> Result<Keys> {
Keys::new(self, None::<String>, true)
}
pub fn find_key<S: Into<Vec<u8>>>(&self, fingerprint: S) -> Result<Key> {
let fingerprint = try!(CString::new(fingerprint));
unsafe {
let mut key = ptr::null_mut();
return_err!(ffi::gpgme_get_key(self.raw, fingerprint.as_ptr(), &mut key, 0));
Ok(Key::from_raw(key))
}
}
pub fn find_secret_key<S: Into<Vec<u8>>>(&self, fingerprint: S) -> Result<Key> {
let fingerprint = try!(CString::new(fingerprint));
unsafe {
let mut key = ptr::null_mut();
return_err!(ffi::gpgme_get_key(self.raw, fingerprint.as_ptr(), &mut key, 1));
Ok(Key::from_raw(key))
}
}
pub fn find_keys<I>(&mut self, patterns: I) -> Result<Keys>
where I: IntoIterator, I::Item: Into<Vec<u8>> {
Keys::new(self, patterns, false)
}
pub fn find_secret_keys<I>(&mut self, patterns: I) -> Result<Keys>
where I: IntoIterator, I::Item: Into<Vec<u8>> {
Keys::new(self, patterns, true)
}
pub fn generate_key<S: Into<String>>(&mut self, params: S, public: Option<&mut Data>,
secret: Option<&mut Data>)
-> Result<ops::KeyGenerateResult> {
let params = try!(CString::new(params.into()));
let public = public.map_or(ptr::null_mut(), |d| d.as_raw());
let secret = secret.map_or(ptr::null_mut(), |d| d.as_raw());
unsafe {
return_err!(ffi::gpgme_op_genkey(self.raw, params.as_ptr(), public, secret));
}
Ok(self.get_result().unwrap())
}
pub fn import(&mut self, key_data: &mut Data) -> Result<ops::ImportResult> {
unsafe {
return_err!(ffi::gpgme_op_import(self.raw, key_data.as_raw()));
}
Ok(self.get_result().unwrap())
}
pub fn import_keys<'k, I>(&mut self, keys: I) -> Result<ops::ImportResult>
where I: IntoIterator<Item = &'k Key> {
let mut ptrs: Vec<_> = keys.into_iter().map(|k| k.as_raw()).collect();
let keys = if !ptrs.is_empty() {
ptrs.push(ptr::null_mut());
ptrs.as_mut_ptr()
} else {
ptr::null_mut()
};
unsafe {
return_err!(ffi::gpgme_op_import_keys(self.raw, keys));
}
Ok(self.get_result().unwrap())
}
pub fn export_all(&mut self, mode: ops::ExportMode, data: Option<&mut Data>) -> Result<()> {
self.export(None::<String>, mode, data)
}
pub fn export<I>(&mut self, patterns: I, mode: ops::ExportMode, data: Option<&mut Data>)
-> Result<()>
where I: IntoIterator, I::Item: Into<Vec<u8>> {
let mut strings = Vec::new();
for pattern in patterns {
strings.push(try!(CString::new(pattern)));
}
let data = data.map_or(ptr::null_mut(), |d| d.as_raw());
match strings.len() {
0 | 1 => unsafe {
let pattern = strings.first().map_or(ptr::null(), |s| s.as_ptr());
return_err!(ffi::gpgme_op_export(self.raw, pattern, mode.bits(), data));
},
_ => unsafe {
let mut ptrs: Vec<_> = strings.iter().map(|s| s.as_ptr()).collect();
ptrs.push(ptr::null());
return_err!(ffi::gpgme_op_export_ext(self.raw,
ptrs.as_mut_ptr(),
mode.bits(),
data));
},
}
Ok(())
}
pub fn export_keys<'k, I>(&mut self, keys: I, mode: ops::ExportMode, data: Option<&mut Data>)
-> Result<()>
where I: IntoIterator<Item = &'k Key> {
let data = data.map_or(ptr::null_mut(), |d| d.as_raw());
let mut ptrs: Vec<_> = keys.into_iter().map(|k| k.as_raw()).collect();
let keys = if !ptrs.is_empty() {
ptrs.push(ptr::null_mut());
ptrs.as_mut_ptr()
} else {
ptr::null_mut()
};
unsafe {
return_err!(ffi::gpgme_op_export_keys(self.raw, keys, mode.bits(), data));
}
Ok(())
}
pub fn change_key_passphrase(&mut self, key: &Key) -> Result<()> {
unsafe {
return_err!(ffi::gpgme_op_passwd(self.raw, key.as_raw(), 0));
}
Ok(())
}
pub fn edit_key<E: EditHandler>(&mut self, key: &Key, handler: E, data: &mut Data)
-> Result<()> {
unsafe {
let mut wrapper = EditHandlerWrapper {
handler: handler,
response: data,
};
return_err!(ffi::gpgme_op_edit(self.raw, key.as_raw(), Some(edit_callback::<E>),
(&mut wrapper as *mut _) as *mut _, data.as_raw()));
}
Ok(())
}
pub fn edit_key_with<E: edit::Editor>(&mut self, key: &Key, editor: E, data: &mut Data)
-> Result<()> {
self.edit_key(key, edit::EditorWrapper::new(editor), data)
}
pub fn delete_key(&mut self, key: &Key) -> Result<()> {
unsafe {
return_err!(ffi::gpgme_op_delete(self.raw, key.as_raw(), 0));
}
Ok(())
}
pub fn delete_secret_key(&mut self, key: &Key) -> Result<()> {
unsafe {
return_err!(ffi::gpgme_op_delete(self.raw, key.as_raw(), 1));
}
Ok(())
}
pub fn clear_signers(&mut self) {
unsafe { ffi::gpgme_signers_clear(self.raw) }
}
pub fn add_signer(&mut self, key: &Key) -> Result<()> {
unsafe {
return_err!(ffi::gpgme_signers_add(self.raw, key.as_raw()));
}
Ok(())
}
pub fn signers_count(&self) -> u32 {
unsafe { ffi::gpgme_signers_count(self.raw).into() }
}
pub fn signers(&self) -> SignersIter {
SignersIter {
ctx: self,
current: Some(0),
}
}
pub fn clear_notations(&mut self) {
unsafe {
ffi::gpgme_sig_notation_clear(self.raw);
}
}
pub fn add_notation<S1, S2>(&mut self, name: S1, value: S2, flags: notation::Flags)
-> Result<()>
where S1: Into<String>, S2: Into<String> {
let name = try!(CString::new(name.into()));
let value = try!(CString::new(value.into()));
unsafe {
return_err!(ffi::gpgme_sig_notation_add(self.raw,
name.as_ptr(),
value.as_ptr(),
flags.bits()));
}
Ok(())
}
pub fn add_policy_url<S: Into<String>>(&mut self, url: S, critical: bool) -> Result<()> {
let url = try!(CString::new(url.into()));
unsafe {
let critical = if critical {
ffi::GPGME_SIG_NOTATION_CRITICAL
} else {
0
};
return_err!(ffi::gpgme_sig_notation_add(self.raw, ptr::null(), url.as_ptr(), critical));
}
Ok(())
}
pub fn notations(&self) -> SignatureNotationIter<Context> {
unsafe { SignatureNotationIter::from_list(ffi::gpgme_sig_notation_get(self.raw)) }
}
pub fn sign(&mut self, mode: ops::SignMode, plain: &mut Data, signature: &mut Data)
-> Result<ops::SignResult> {
unsafe {
return_err!(ffi::gpgme_op_sign(self.raw,
plain.as_raw(),
signature.as_raw(),
mode.raw()));
}
Ok(self.get_result().unwrap())
}
pub fn sign_clear(&mut self, plain: &mut Data, signed: &mut Data) -> Result<ops::SignResult> {
self.sign(ops::SIGN_MODE_CLEAR, plain, signed)
}
pub fn sign_detached(&mut self, plain: &mut Data, signature: &mut Data)
-> Result<ops::SignResult> {
self.sign(ops::SIGN_MODE_DETACH, plain, signature)
}
pub fn sign_normal(&mut self, plain: &mut Data, signed: &mut Data) -> Result<ops::SignResult> {
self.sign(ops::SIGN_MODE_NORMAL, plain, signed)
}
pub fn verify(&mut self, signature: &mut Data, signed: Option<&mut Data>,
plain: Option<&mut Data>)
-> Result<ops::VerifyResult> {
let signed = signed.map_or(ptr::null_mut(), |d| d.as_raw());
let plain = plain.map_or(ptr::null_mut(), |d| d.as_raw());
unsafe {
return_err!(ffi::gpgme_op_verify(self.raw, signature.as_raw(), signed, plain));
}
Ok(self.get_result().unwrap())
}
pub fn verify_detached(&mut self, signature: &mut Data, signed: &mut Data)
-> Result<ops::VerifyResult> {
self.verify(signature, Some(signed), None)
}
pub fn verify_opaque(&mut self, signature: &mut Data, plain: &mut Data)
-> Result<ops::VerifyResult> {
self.verify(signature, None, Some(plain))
}
pub fn encrypt<'k, I>(&mut self, recp: I, flags: ops::EncryptFlags, plain: &mut Data,
cipher: &mut Data)
-> Result<ops::EncryptResult>
where I: IntoIterator<Item = &'k Key> {
let mut ptrs: Vec<_> = recp.into_iter().map(|k| k.as_raw()).collect();
let keys = if !ptrs.is_empty() {
ptrs.push(ptr::null_mut());
ptrs.as_mut_ptr()
} else {
ptr::null_mut()
};
unsafe {
return_err!(ffi::gpgme_op_encrypt(self.raw,
keys,
flags.bits(),
plain.as_raw(),
cipher.as_raw()));
}
Ok(self.get_result().unwrap())
}
pub fn encrypt_symmetric(&mut self, flags: ops::EncryptFlags, plain: &mut Data,
cipher: &mut Data)
-> Result<()> {
unsafe {
return_err!(ffi::gpgme_op_encrypt(self.raw,
ptr::null_mut(),
flags.bits(),
plain.as_raw(),
cipher.as_raw()));
}
Ok(())
}
pub fn encrypt_and_sign<'k, I>(&mut self, recp: I, flags: ops::EncryptFlags, plain: &mut Data,
cipher: &mut Data)
-> Result<(ops::EncryptResult, ops::SignResult)>
where I: IntoIterator<Item = &'k Key> {
let mut ptrs: Vec<_> = recp.into_iter().map(|k| k.as_raw()).collect();
let keys = if !ptrs.is_empty() {
ptrs.push(ptr::null_mut());
ptrs.as_mut_ptr()
} else {
ptr::null_mut()
};
unsafe {
return_err!(ffi::gpgme_op_encrypt_sign(self.raw,
keys,
flags.bits(),
plain.as_raw(),
cipher.as_raw()))
}
Ok((self.get_result().unwrap(), self.get_result().unwrap()))
}
pub fn decrypt(&mut self, cipher: &mut Data, plain: &mut Data) -> Result<ops::DecryptResult> {
unsafe {
return_err!(ffi::gpgme_op_decrypt(self.raw, cipher.as_raw(), plain.as_raw()));
}
Ok(self.get_result().unwrap())
}
pub fn decrypt_and_verify(&mut self, cipher: &mut Data, plain: &mut Data)
-> Result<(ops::DecryptResult, ops::VerifyResult)> {
unsafe {
return_err!(ffi::gpgme_op_decrypt_verify(self.raw, cipher.as_raw(), plain.as_raw()))
}
Ok((self.get_result().unwrap(), self.get_result().unwrap()))
}
fn get_result<R: ops::OpResult>(&self) -> Option<R> {
R::from_context(self)
}
}
unsafe impl Wrapper for Context {
type Raw = ffi::gpgme_ctx_t;
unsafe fn from_raw(raw: ffi::gpgme_ctx_t) -> Context {
debug_assert!(!raw.is_null());
Context { raw: raw }
}
fn as_raw(&self) -> ffi::gpgme_ctx_t {
self.raw
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe { ffi::gpgme_release(self.raw) }
}
}
impl fmt::Debug for Context {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Context").field("raw", &self.raw).finish()
}
}
pub struct Keys<'a> {
ctx: &'a mut Context,
}
impl<'a> Keys<'a> {
fn new<'b, I>(ctx: &'b mut Context, patterns: I, secret_only: bool) -> Result<Keys<'b>>
where I: IntoIterator, I::Item: Into<Vec<u8>> {
let mut strings = Vec::new();
for pattern in patterns {
strings.push(try!(CString::new(pattern)));
}
match strings.len() {
0 | 1 => unsafe {
let pattern = strings.first().map_or(ptr::null(), |s| s.as_ptr());
return_err!(ffi::gpgme_op_keylist_start(ctx.as_raw(),
pattern,
secret_only as libc::c_int));
},
_ => unsafe {
let mut ptrs: Vec<_> = strings.iter().map(|s| s.as_ptr()).collect();
ptrs.push(ptr::null());
return_err!(ffi::gpgme_op_keylist_ext_start(ctx.as_raw(),
ptrs.as_mut_ptr(),
secret_only as libc::c_int,
0));
},
}
Ok(Keys { ctx: ctx })
}
pub fn finish(self) -> Result<ops::KeyListResult> {
let ctx = self.ctx as *mut Context;
mem::forget(self);
unsafe {
return_err!(ffi::gpgme_op_keylist_end((*ctx).as_raw()));
Ok((*ctx).get_result().unwrap())
}
}
}
impl<'a> Drop for Keys<'a> {
fn drop(&mut self) {
unsafe {
ffi::gpgme_op_keylist_end(self.ctx.as_raw());
}
}
}
impl<'a> Iterator for Keys<'a> {
type Item = Result<Key>;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let mut key = ptr::null_mut();
let result = ffi::gpgme_op_keylist_next(self.ctx.as_raw(), &mut key);
if ffi::gpgme_err_code(result) != error::GPG_ERR_EOF {
if result == 0 {
Some(Ok(Key::from_raw(key)))
} else {
Some(Err(Error::new(result)))
}
} else {
None
}
}
}
}
pub struct TrustItems<'a> {
ctx: &'a mut Context,
}
impl<'a> TrustItems<'a> {
pub fn finish(self) -> Result<()> {
let ctx = self.ctx as *mut Context;
mem::forget(self);
unsafe {
return_err!(ffi::gpgme_op_trustlist_end((*ctx).as_raw()));
}
Ok(())
}
}
impl<'a> Drop for TrustItems<'a> {
fn drop(&mut self) {
unsafe {
ffi::gpgme_op_trustlist_end(self.ctx.as_raw());
}
}
}
impl<'a> Iterator for TrustItems<'a> {
type Item = Result<TrustItem>;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let mut trust_item = ptr::null_mut();
let result = ffi::gpgme_op_trustlist_next(self.ctx.as_raw(), &mut trust_item);
if ffi::gpgme_err_code(result) != error::GPG_ERR_EOF {
if result == 0 {
Some(Ok(TrustItem::from_raw(trust_item)))
} else {
Some(Err(Error::new(result)))
}
} else {
None
}
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct SignersIter<'a> {
ctx: &'a Context,
current: Option<libc::c_int>,
}
impl<'a> Iterator for SignersIter<'a> {
type Item = Key;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
self.current.and_then(|x| {
let key = ffi::gpgme_signers_enum(self.ctx.as_raw(), x);
if !key.is_null() {
self.current = x.checked_add(1);
Some(Key::from_raw(key))
} else {
self.current = None;
None
}
})
}
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.current = self.current.and_then(|x| {
if (n as i64) <= (libc::c_int::max_value() as i64) {
x.checked_add(n as libc::c_int)
} else {
None
}
});
self.next()
}
}
pub struct PassphraseRequest<'a> {
pub uid_hint: StrResult<'a>,
pub context: StrResult<'a>,
pub prev_attempt_failed: bool,
}
pub trait PassphraseHandler: 'static + Send {
fn handle<W: io::Write>(&mut self, request: PassphraseRequest, out: W)
-> Result<()>;
}
impl<T: 'static + Send> PassphraseHandler for T
where T: FnMut(PassphraseRequest, &mut io::Write) -> Result<()> {
fn handle<W: io::Write>(&mut self, request: PassphraseRequest, mut out: W)
-> Result<()> {
(*self)(request, &mut out)
}
}
struct PassphraseHandlerGuard {
ctx: ffi::gpgme_ctx_t,
old: (ffi::gpgme_passphrase_cb_t, *mut libc::c_void),
}
impl Drop for PassphraseHandlerGuard {
fn drop(&mut self) {
unsafe {
ffi::gpgme_set_passphrase_cb(self.ctx, self.old.0, self.old.1);
}
}
}
extern "C" fn passphrase_callback<H: PassphraseHandler>(hook: *mut libc::c_void,
uid_hint: *const libc::c_char,
info: *const libc::c_char,
was_bad: libc::c_int, fd: libc::c_int)
-> ffi::gpgme_error_t {
use std::io::prelude::*;
let handler = hook as *mut H;
unsafe {
let info = PassphraseRequest {
uid_hint: utils::from_cstr(uid_hint),
context: utils::from_cstr(info),
prev_attempt_failed: was_bad != 0,
};
let mut writer = FdWriter::new(fd);
(*handler)
.handle(info, &mut writer)
.and_then(|_| writer.write_all(b"\n").map_err(Error::from))
.err()
.map_or(0, |err| err.raw())
}
}
pub struct ProgressInfo<'a> {
pub what: StrResult<'a>,
pub typ: i64,
pub current: i64,
pub total: i64,
}
pub trait ProgressHandler: 'static + Send {
fn handle(&mut self, info: ProgressInfo);
}
impl<T: 'static + Send> ProgressHandler for T where T: FnMut(ProgressInfo) {
fn handle(&mut self, info: ProgressInfo) {
(*self)(info);
}
}
pub struct ProgressHandlerGuard {
ctx: ffi::gpgme_ctx_t,
old: (ffi::gpgme_progress_cb_t, *mut libc::c_void),
}
impl Drop for ProgressHandlerGuard {
fn drop(&mut self) {
unsafe {
ffi::gpgme_set_progress_cb(self.ctx, self.old.0, self.old.1);
}
}
}
extern "C" fn progress_callback<H: ProgressHandler>(hook: *mut libc::c_void,
what: *const libc::c_char, typ: libc::c_int,
current: libc::c_int, total: libc::c_int) {
let handler = hook as *mut H;
unsafe {
let info = ProgressInfo {
what: utils::from_cstr(what),
typ: typ.into(),
current: current.into(),
total: total.into(),
};
(*handler).handle(info);
}
}
pub trait StatusHandler: 'static + Send {
fn handle(&mut self, keyword: StrResult, args: StrResult) -> Result<()>;
}
impl<T: 'static + Send> StatusHandler for T where T: FnMut(StrResult, StrResult) -> Result<()> {
fn handle(&mut self, keyword: StrResult, args: StrResult) -> Result<()> {
(*self)(keyword, args)
}
}
pub struct StatusHandlerGuard {
ctx: ffi::gpgme_ctx_t,
old: (ffi::gpgme_status_cb_t, *mut libc::c_void),
}
impl Drop for StatusHandlerGuard {
fn drop(&mut self) {
unsafe {
ffi::gpgme_set_status_cb(self.ctx, self.old.0, self.old.1);
}
}
}
extern "C" fn status_callback<H: StatusHandler>(hook: *mut libc::c_void,
keyword: *const libc::c_char, args: *const libc::c_char) -> ffi::gpgme_error_t {
let handler = hook as *mut H;
unsafe {
let keyword = utils::from_cstr(keyword);
let args = utils::from_cstr(args);
(*handler).handle(args, keyword).err().map(|err| err.raw()).unwrap_or(0)
}
}
pub struct EditStatus<'a> {
pub code: edit::StatusCode,
pub args: StrResult<'a>,
pub response: &'a mut Data<'a>,
}
pub trait EditHandler: 'static + Send {
fn handle<W: io::Write>(&mut self, status: EditStatus, out: Option<W>) -> Result<()>;
}
struct EditHandlerWrapper<'a, E: EditHandler> {
handler: E,
response: *mut Data<'a>,
}
extern "C" fn edit_callback<'a, E: EditHandler>(hook: *mut libc::c_void,
status: ffi::gpgme_status_code_t, args: *const libc::c_char,
fd: libc::c_int) -> ffi::gpgme_error_t {
let wrapper = hook as *mut EditHandlerWrapper<'a, E>;
let result = unsafe {
let status = EditStatus {
code: edit::StatusCode::from_raw(status),
args: utils::from_cstr(args),
response: &mut *(*wrapper).response,
};
if fd < 0 {
(*wrapper).handler.handle(status, None::<&mut io::Write>)
} else {
(*wrapper).handler.handle(status, Some(FdWriter::new(fd)))
}
};
result.err().map(|err| err.raw()).unwrap_or(0)
}