summary refs log tree commit diff stats
path: root/test
Commit message (Expand)AuthorAgeFilesLines
* tc_signal: added more tests (some still fail!)hut2010-03-301-0/+54
* added RegexpSignalDispatcher though im not sure if ill use ithut2010-03-301-1/+43
* added SignalDispatcher classhut2010-03-301-0/+79
* ranger.__init__: set a default value for arghut2010-03-121-2/+0
* misc changes, make installhut2010-03-122-0/+4
* added copyright info to config files and test caseshut2010-03-0811-0/+165
* tc_colorscheme: updated testcasehut2010-02-281-1/+2
* tc_keyapi: updated testcasehut2010-02-251-1/+1
* shell_escape: added testcasehut2010-02-241-0/+7
* test/tc_commandlist: removed obsolete testhut2010-02-161-4/+6
* tc_ext: small updatehut2010-01-261-7/+10
* added testcase for openstructhut2010-01-261-0/+26
* added testcase for mount_pathhut2010-01-261-0/+25
* added unittest for flatten and uniquehut2010-01-261-0/+69
* fixed unit testshut2010-01-204-62/+82
* commandlist: bugfixhut2010-01-141-5/+6
* commandlist: aliases are now references rather than copieshut2010-01-131-2/+13
* commandlist: added alias(existing, *new)hut2010-01-131-0/+8
* commandlist: added clear()hut2010-01-131-0/+9
* fsobject.directory: removed __getitem__ (too ambiguous)hut2010-01-131-2/+0
* commandlist: improvements and test casehut2010-01-131-0/+54
* random cleanups and fixeshut2010-01-071-0/+1
* bookmarks: added testcase, documentation, settinghut2010-01-011-0/+73
* fixed tc_displayablehut2009-12-311-9/+11
* added documentation, clean uphut2009-12-312-7/+7
* removed test/stuff directoryhut2009-12-306-236/+0
* fixed a few things~hut2009-12-301-11/+0
* updated testhut2009-12-291-2/+2
* test case for keyapi.Wrapperhut2009-12-271-0/+24
* fixed colorschemes, added unittest for colorschemeshut2009-12-171-0/+31
* extended history by a couple of methodshut2009-12-171-7/+10
* fixed directory testhut2009-12-141-0/+3
* updated / added testshut2009-12-135-4/+213
* clean ups, commentshut2009-12-132-5/+8
* clean upshut2009-12-113-8/+5
* run all tests with a single executablehut2009-12-111-0/+5
* Reorganization of gui/widget hierarchy and directory structurehut2009-12-111-1/+1
* restructurationshut2009-12-111-2/+2
* moved/fixed testshut2009-12-117-1/+209
* fixed directory testhut2009-12-061-19/+0
* History Object + Test Casehut2009-12-051-0/+44
* random improvementshut2009-11-291-17/+18
* more VROOMhut2009-11-272-12/+22
* implemented more stuffhut2009-11-252-9/+10
* corrected test, added some stuffhut2009-11-242-5/+50
* stuffhut2009-11-241-1/+2
* better implementation of directories/fileshut2009-11-243-25/+54
* test cases for directory.pyhut2009-11-233-0/+68
com> 2015-03-23 23:38:06 +0000 Added pgpkeyid account setting, send signed presence' href='/danisanti/profani-tty/commit/src/pgp/gpg.c?id=475dfebd97b8adace3ee56683b968da752a3ae02'>475dfebd ^
2490c3ed ^
55c2d1cc ^







39d183fe ^
dd346eef ^

53035f5e ^
8a90e1ac ^
53035f5e ^

1f4fd0fc ^
53035f5e ^




1f4fd0fc ^
53035f5e ^





1f4fd0fc ^
aee832f7 ^
53035f5e ^
1f4fd0fc ^
dd346eef ^


55c2d1cc ^
2490c3ed ^

fd866155 ^

2490c3ed ^
551f7df1 ^
55c2d1cc ^
cb19be2f ^



53035f5e ^


551f7df1 ^




fc1ee791 ^


17919298 ^
358e9d6a ^
fc1ee791 ^


17919298 ^
358e9d6a ^
fc1ee791 ^

cb19be2f ^


53035f5e ^









358e9d6a ^


39d183fe ^
358e9d6a ^
a3a73cf0 ^

33172cb9 ^
358e9d6a ^
a3a73cf0 ^
fc1ee791 ^
358e9d6a ^



fc1ee791 ^
358e9d6a ^


fc1ee791 ^
358e9d6a ^
fc1ee791 ^
358e9d6a ^


fc1ee791 ^



358e9d6a ^
fc1ee791 ^

358e9d6a ^

fc1ee791 ^

358e9d6a ^


fc1ee791 ^
358e9d6a ^


2af5c151 ^
358e9d6a ^









fc1ee791 ^
358e9d6a ^


e2a528ca ^
358e9d6a ^

fc1ee791 ^
358e9d6a ^
b1ab4b28 ^
358e9d6a ^


55c2d1cc ^



fc1ee791 ^
2af5c151 ^
358e9d6a ^





fc1ee791 ^
358e9d6a ^




fc1ee791 ^

55c2d1cc ^
358e9d6a ^

fc1ee791 ^


358e9d6a ^

fc1ee791 ^

53035f5e ^









358e9d6a ^


39d183fe ^
358e9d6a ^








592a3695 ^
2af5c151 ^

358e9d6a ^




fc1ee791 ^


358e9d6a ^
fc1ee791 ^
55c2d1cc ^



2af5c151 ^
358e9d6a ^

2490c3ed ^

39d183fe ^
f6a91145 ^

























39d183fe ^
2490c3ed ^


f6a91145 ^
2490c3ed ^
2af5c151 ^
2490c3ed ^
2af5c151 ^
2490c3ed ^
475dfebd ^
2490c3ed ^


d6ff72cf ^
2490c3ed ^
f6a91145 ^

2490c3ed ^
f6a91145 ^
2af5c151 ^
f6a91145 ^
















2490c3ed ^
8a5d1fef ^
f6a91145 ^
8a5d1fef ^
f6a91145 ^



















8a5d1fef ^
2af5c151 ^
f6a91145 ^
2490c3ed ^
2490c3ed ^



cb19be2f ^









2490c3ed ^

fd866155 ^
f6a91145 ^






39d183fe ^
fc1ee791 ^
551f7df1 ^
fc1ee791 ^
551f7df1 ^

fd866155 ^





6617bb5a ^
88fd2a25 ^
57ca441f ^




88fd2a25 ^
57ca441f ^







88fd2a25 ^
57ca441f ^



88fd2a25 ^

57ca441f ^
88fd2a25 ^
57ca441f ^


88fd2a25 ^


57ca441f ^


39d183fe ^
6617bb5a ^
fc1ee791 ^

6617bb5a ^

551f7df1 ^
39d183fe ^
551f7df1 ^






2af5c151 ^
551f7df1 ^




0f6bc9b5 ^
2af5c151 ^
551f7df1 ^
2af5c151 ^


551f7df1 ^


2af5c151 ^


551f7df1 ^








592a3695 ^





55c2d1cc ^



592a3695 ^


551f7df1 ^


d501576f ^
551f7df1 ^

475dfebd ^
39d183fe ^
475dfebd ^
73e1654f ^


475dfebd ^
73e1654f ^

475dfebd ^
dd346eef ^

73e1654f ^

2af5c151 ^
73e1654f ^
475dfebd ^
3b79d5aa ^
73e1654f ^

475dfebd ^
73e1654f ^

3b79d5aa ^
2af5c151 ^
73e1654f ^
475dfebd ^
73e1654f ^


475dfebd ^
475dfebd ^





2af5c151 ^
73e1654f ^
2af5c151 ^


73e1654f ^
475dfebd ^
73e1654f ^
2af5c151 ^



73e1654f ^
475dfebd ^
2af5c151 ^
73e1654f ^

475dfebd ^

475dfebd ^

73e1654f ^
44aa2fd1 ^
2af5c151 ^




73e1654f ^
475dfebd ^
4d18c5ff ^


53035f5e ^
73e1654f ^
475dfebd ^

39d183fe ^
7b138b71 ^
475dfebd ^
55c2d1cc ^




eb5cb7b2 ^


66467f97 ^
eb5cb7b2 ^


7b138b71 ^
eb5cb7b2 ^







7b138b71 ^



eb5cb7b2 ^


7b138b71 ^
eb5cb7b2 ^
7b138b71 ^







eb5cb7b2 ^

eb5cb7b2 ^
2af5c151 ^

eb5cb7b2 ^



2af5c151 ^

7b138b71 ^

2af5c151 ^
eb5cb7b2 ^

eb5cb7b2 ^

475dfebd ^
eb5cb7b2 ^
2af5c151 ^


eb5cb7b2 ^
2af5c151 ^




eb5cb7b2 ^

eb5cb7b2 ^


39d183fe ^

0f6bc9b5 ^
0f6bc9b5 ^

2af5c151 ^
0f6bc9b5 ^




dd346eef ^

2af5c151 ^
0f6bc9b5 ^
2af5c151 ^



0f6bc9b5 ^


2af5c151 ^
2af5c151 ^
0f6bc9b5 ^

2af5c151 ^
c0763874 ^
0f6bc9b5 ^


c0763874 ^

7b138b71 ^
c0763874 ^
7b138b71 ^
c0763874 ^
fc1ee791 ^
c0763874 ^



7b138b71 ^
c0763874 ^


7b138b71 ^





c0763874 ^
7b138b71 ^


c0763874 ^


0f6bc9b5 ^








4d18c5ff ^


53035f5e ^
0f6bc9b5 ^


2af5c151 ^





39d183fe ^

cb19be2f ^









39d183fe ^
688be91c ^





















eb5cb7b2 ^
39d183fe ^
eb5cb7b2 ^

027fa2a7 ^
eb5cb7b2 ^
027fa2a7 ^
eb5cb7b2 ^
027fa2a7 ^
475dfebd ^
eb5cb7b2 ^
475dfebd ^
eb5cb7b2 ^
027fa2a7 ^
475dfebd ^
027fa2a7 ^
475dfebd ^
eb5cb7b2 ^


475dfebd ^
027fa2a7 ^
551f7df1 ^


39d183fe ^
551f7df1 ^


0f6bc9b5 ^
551f7df1 ^


0f6bc9b5 ^
551f7df1 ^





358e9d6a ^

fc1ee791 ^
358e9d6a ^

fc1ee791 ^



358e9d6a ^
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


        
                                                            













                                                                       
                                                                      














                                                                                
                   
 

                   
                   

                     
 
                 
                        


                  
                   
                    
                         
                               
                  
 

                                                            
                                                        
                                                      
 
                              
                           
 

                            
 


                                

                           

                                                                                                           
                                
 
    







                                               
                     

                                                                                                             
                     
                                                           

                                              
 




                                                                       
 





                                            
 
                                                                           
     
 


             
    

                

                                                          
                                                                
 
                                                                                                           



                                         


                              




                 


                                      
     
 


                                    
     
 

                   


                              









                                  


    
                                           
 

                                                
                 
                                                           
                                   
                                           



                                         
                                                           


                                       
                                                                                 
                
                                                                     


         



                                          
 

                                                   

     

                                                                                   


                      
                                                           


                                          
 









                                                                                                               
                                                                              


                                                              
                          

                                   
                                                       
                                       
                                                                                                                        


                         



                                                                        
                          
                                 





                       
                    




                         

                                      
                                                                                                               

     


                                    

     

                   









                                  


        
                                                            








                                                                                                               
                                               

                       




                                                                                                  


                                                           
 
                                    



                                                                
                         

                

 
                  

























                                                      
           


                        
                                                                                                               
 
                    
                            
 
                
                                                                                                    


                    
                                                 
                                    

                                                 
                        
                                              
 
















                                                                         
             
 
                                                                          
 



















                                                                                       
 
                                 
                                                     
         



                       









                                                                  

                  
 






                                 
           
                   
 
                   

 





                      
        
                                                        




                                                                                                               
                                                 







                                                                                                  
                                                 



                           

                                           
                           
                     


                       


                         


        
                                          
 

                                                         

 
    
                                                               






                                          
 




                                                                                                               
                                                                                                         
                           
                                                                                                     


                                  


                                                              


                                   








                                                                                                 





                                                                                                        



                                                                            


                                 


         
                       

 
     
                                                       
 


                                          
                                                                                                               

                    
 

                                                                                    

                                            
 
                               
                                                                                                  
                           

                    
 

                                        
                         
 
                
                                                                                                      


                           
 





                                   
                          
                                                                              


                             
                                 
 
                           



                                                                             
                
                                                                                                      
                                        

                    

                        

                   
                                                                         
                     




                                                                               
     
 


                                                
 
                  

 
     
                                                                                         
 




                                                                      


                    
                        


                   
                   







                                                                                                               



                                                                                                           


                           
                           
 







                                                                                                         

                       
                                                                 

                        



                                                                                   

                              

                                  
 

                                                                                                          

                    
 
               


                                                                    
                     




                                                                             

     


                  

                                       
 

                                          
 




                                                                                                               

                                                                                    
                                                                                                   
                             



                                                                                               


                                                           
                                    
 

                                                                                                          
                                       
                           


                    

                                                              
                                                   
                                                      
                           
                            
                                                                  



                                                                                             
                                                          


                                     





                                                      
         


                                                                                    


                       








                                                                       


                                                
 


                  





                                     

                                                    









                                                           
     





















                                              
            
                                                          

                
                     
 
                          
                               
                       
         
              
 
                               
                        
         
     
 


                                                     
 
                    


            
                                                                                             


                                           
                                        


                                        
                                        





                                     

           
                   

                      



                                                                               
 
/*
 * gpg.c
 *
 * Copyright (C) 2012 - 2016 James Booth <boothj5@gmail.com>
 *
 * This file is part of Profanity.
 *
 * Profanity is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Profanity is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Profanity.  If not, see <https://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give permission to
 * link the code of portions of this program with the OpenSSL library under
 * certain conditions as described in each individual source file, and
 * distribute linked combinations including the two.
 *
 * You must obey the GNU General Public License in all respects for all of the
 * code used other than OpenSSL. If you modify file(s) with this exception, you
 * may extend this exception to your version of the file(s), but you are not
 * obligated to do so. If you do not wish to do so, delete this exception
 * statement from your version. If you delete this exception statement from all
 * source files in the program, then also delete it here.
 *
 */

#include "config.h"

#include <locale.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>

#include <glib.h>
#include <glib/gstdio.h>
#include <gpgme.h>

#include "log.h"
#include "common.h"
#include "pgp/gpg.h"
#include "config/files.h"
#include "tools/autocomplete.h"
#include "ui/ui.h"

#define PGP_SIGNATURE_HEADER "-----BEGIN PGP SIGNATURE-----"
#define PGP_SIGNATURE_FOOTER "-----END PGP SIGNATURE-----"
#define PGP_MESSAGE_HEADER "-----BEGIN PGP MESSAGE-----"
#define PGP_MESSAGE_FOOTER "-----END PGP MESSAGE-----"

static const char *libversion;
static GHashTable *pubkeys;

static gchar *pubsloc;
static GKeyFile *pubkeyfile;

static char *passphrase;
static char *passphrase_attempt;

static Autocomplete key_ac;

static char* _remove_header_footer(char *str, const char *const footer);
static char* _add_header_footer(const char *const str, const char *const header, const char *const footer);
static void _save_pubkeys(void);

void
_p_gpg_free_pubkeyid(ProfPGPPubKeyId *pubkeyid)
{
    if (pubkeyid) {
        free(pubkeyid->id);
    }
    free(pubkeyid);
}

static gpgme_error_t*
_p_gpg_passphrase_cb(void *hook, const char *uid_hint, const char *passphrase_info, int prev_was_bad, int fd)
{
    if (passphrase) {
        gpgme_io_write(fd, passphrase, strlen(passphrase));
    } else {
        GString *pass_term = g_string_new("");

        char *password = ui_ask_pgp_passphrase(uid_hint, prev_was_bad);
        if (password) {
            g_string_append(pass_term, password);
            free(password);
        }

        g_string_append(pass_term, "\n");
        if (passphrase_attempt) {
            free(passphrase_attempt);
        }
        passphrase_attempt = pass_term->str;
        g_string_free(pass_term, FALSE);

        gpgme_io_write(fd, passphrase_attempt, strlen(passphrase_attempt));
    }

    return 0;
}

void
p_gpg_init(void)
{
    libversion = gpgme_check_version(NULL);
    log_debug("GPG: Found gpgme version: %s", libversion);
    gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));

    pubkeys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)_p_gpg_free_pubkeyid);

    key_ac = autocomplete_new();
    GHashTable *keys = p_gpg_list_keys();
    p_gpg_free_keys(keys);

    passphrase = NULL;
    passphrase_attempt = NULL;
}

void
p_gpg_close(void)
{
    if (pubkeys) {
        g_hash_table_destroy(pubkeys);
        pubkeys = NULL;
    }

    if (pubkeyfile) {
        g_key_file_free(pubkeyfile);
        pubkeyfile = NULL;
    }

    free(pubsloc);
    pubsloc = NULL;

    autocomplete_free(key_ac);
    key_ac = NULL;

    if (passphrase) {
        free(passphrase);
        passphrase = NULL;
    }

    if (passphrase_attempt) {
        free(passphrase_attempt);
        passphrase_attempt = NULL;
    }
}

void
p_gpg_on_connect(const char *const barejid)
{
    char *pgpdir = files_get_data_path(DIR_PGP);
    GString *pubsfile = g_string_new(pgpdir);
    free(pgpdir);
    gchar *account_dir = str_replace(barejid, "@", "_at_");
    g_string_append(pubsfile, "/");
    g_string_append(pubsfile, account_dir);
    free(account_dir);

    // mkdir if doesn't exist for account
    errno = 0;
    int res = g_mkdir_with_parents(pubsfile->str, S_IRWXU);
    if (res == -1) {
        char *errmsg = strerror(errno);
        if (errmsg) {
            log_error("Error creating directory: %s, %s", pubsfile->str, errmsg);
        } else {
            log_error("Error creating directory: %s", pubsfile->str);
        }
    }

    // create or read publickeys
    g_string_append(pubsfile, "/pubkeys");
    pubsloc = pubsfile->str;
    g_string_free(pubsfile, FALSE);

    if (g_file_test(pubsloc, G_FILE_TEST_EXISTS)) {
        g_chmod(pubsloc, S_IRUSR | S_IWUSR);
    }

    pubkeyfile = g_key_file_new();
    g_key_file_load_from_file(pubkeyfile, pubsloc, G_KEY_FILE_KEEP_COMMENTS, NULL);

    // load each keyid
    gsize len = 0;
    gchar **jids = g_key_file_get_groups(pubkeyfile, &len);

    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);

    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        g_strfreev(jids);
        return;
    }

    int i = 0;
    for (i = 0; i < len; i++) {
        GError *gerr = NULL;
        gchar *jid = jids[i];
        gchar *keyid = g_key_file_get_string(pubkeyfile, jid, "keyid", &gerr);
        if (gerr) {
            log_error("Error loading PGP key id for %s", jid);
            g_error_free(gerr);
            g_free(keyid);
        } else {
            gpgme_key_t key = NULL;
            error = gpgme_get_key(ctx, keyid, &key, 0);
            if (error || key == NULL) {
                log_warning("GPG: Failed to get key for %s: %s %s", jid, gpgme_strsource(error), gpgme_strerror(error));
                continue;
            }

            ProfPGPPubKeyId *pubkeyid = malloc(sizeof(ProfPGPPubKeyId));
            pubkeyid->id = strdup(keyid);
            pubkeyid->received = FALSE;
            g_hash_table_replace(pubkeys, strdup(jid), pubkeyid);
            g_free(keyid);
            gpgme_key_unref(key);
        }
    }

    gpgme_release(ctx);
    g_strfreev(jids);

    _save_pubkeys();
}

void
p_gpg_on_disconnect(void)
{
    if (pubkeys) {
        g_hash_table_destroy(pubkeys);
        pubkeys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)_p_gpg_free_pubkeyid);
    }

    if (pubkeyfile) {
        g_key_file_free(pubkeyfile);
        pubkeyfile = NULL;
    }

    free(pubsloc);
    pubsloc = NULL;

    if (passphrase) {
        free(passphrase);
        passphrase = NULL;
    }

    if (passphrase_attempt) {
        free(passphrase_attempt);
        passphrase_attempt = NULL;
    }
}

gboolean
p_gpg_addkey(const char *const jid, const char *const keyid)
{
    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);
    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return FALSE;
    }

    gpgme_key_t key = NULL;
    error = gpgme_get_key(ctx, keyid, &key, 0);
    gpgme_release(ctx);

    if (error || key == NULL) {
        log_error("GPG: Failed to get key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return FALSE;
    }

    // save to public key file
    g_key_file_set_string(pubkeyfile, jid, "keyid", keyid);
    _save_pubkeys();

    // update in memory pubkeys list
    ProfPGPPubKeyId *pubkeyid = malloc(sizeof(ProfPGPPubKeyId));
    pubkeyid->id = strdup(keyid);
    pubkeyid->received = FALSE;
    g_hash_table_replace(pubkeys, strdup(jid), pubkeyid);
    gpgme_key_unref(key);

    return TRUE;
}

static ProfPGPKey*
_p_gpg_key_new(void)
{
    ProfPGPKey *p_pgpkey = malloc(sizeof(ProfPGPKey));
    p_pgpkey->id = NULL;
    p_pgpkey->name = NULL;
    p_pgpkey->fp = NULL;
    p_pgpkey->encrypt = FALSE;
    p_pgpkey->sign = FALSE;
    p_pgpkey->certify = FALSE;
    p_pgpkey->authenticate = FALSE;
    p_pgpkey->secret = FALSE;

    return p_pgpkey;
}

static void
_p_gpg_free_key(ProfPGPKey *key)
{
    if (key) {
        free(key->id);
        free(key->name);
        free(key->fp);
        free(key);
    }
}

GHashTable*
p_gpg_list_keys(void)
{
    gpgme_error_t error;
    GHashTable *result = g_hash_table_new_full(g_str_hash, g_str_equal, free, (GDestroyNotify)_p_gpg_free_key);

    gpgme_ctx_t ctx;
    error = gpgme_new(&ctx);

    if (error) {
        log_error("GPG: Could not list keys. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return NULL;
    }

    error = gpgme_op_keylist_start(ctx, NULL, 0);
    if (error == GPG_ERR_NO_ERROR) {
        gpgme_key_t key;
        error = gpgme_op_keylist_next(ctx, &key);
        while (!error) {
            gpgme_subkey_t sub = key->subkeys;

            ProfPGPKey *p_pgpkey = _p_gpg_key_new();
            p_pgpkey->id = strdup(sub->keyid);
            p_pgpkey->name = strdup(key->uids->uid);
            p_pgpkey->fp = strdup(sub->fpr);
            if (sub->can_encrypt) p_pgpkey->encrypt = TRUE;
            if (sub->can_authenticate) p_pgpkey->authenticate = TRUE;
            if (sub->can_certify) p_pgpkey->certify = TRUE;
            if (sub->can_sign) p_pgpkey->sign = TRUE;

            sub = sub->next;
            while (sub) {
                if (sub->can_encrypt) p_pgpkey->encrypt = TRUE;
                if (sub->can_authenticate) p_pgpkey->authenticate = TRUE;
                if (sub->can_certify) p_pgpkey->certify = TRUE;
                if (sub->can_sign) p_pgpkey->sign = TRUE;

                sub = sub->next;
            }

            g_hash_table_insert(result, strdup(p_pgpkey->name), p_pgpkey);

            gpgme_key_unref(key);
            error = gpgme_op_keylist_next(ctx, &key);
        }
    }

    error = gpgme_op_keylist_start(ctx, NULL, 1);
    if (error == GPG_ERR_NO_ERROR) {
        gpgme_key_t key;
        error = gpgme_op_keylist_next(ctx, &key);
        while (!error) {
            gpgme_subkey_t sub = key->subkeys;
            while (sub) {
                if (sub->secret) {
                    ProfPGPKey *p_pgpkey = g_hash_table_lookup(result, key->uids->uid);
                    if (p_pgpkey) {
                        p_pgpkey->secret = TRUE;
                    }
                }
                sub = sub->next;
            }

            gpgme_key_unref(key);
            error = gpgme_op_keylist_next(ctx, &key);
        }
    }

    gpgme_release(ctx);

    autocomplete_clear(key_ac);
    GList *ids = g_hash_table_get_keys(result);
    GList *curr = ids;
    while (curr) {
        ProfPGPKey *key = g_hash_table_lookup(result, curr->data);
        autocomplete_add(key_ac, key->id);
        curr = curr->next;
    }
    g_list_free(ids);

    return result;
}

void
p_gpg_free_keys(GHashTable *keys)
{
    g_hash_table_destroy(keys);
}


GHashTable*
p_gpg_pubkeys(void)
{
    return pubkeys;
}

const char*
p_gpg_libver(void)
{
    return libversion;
}

gboolean
p_gpg_valid_key(const char *const keyid, char **err_str)
{
    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);
    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        *err_str = strdup(gpgme_strerror(error));
        return FALSE;
    }

    gpgme_key_t key = NULL;
    error = gpgme_get_key(ctx, keyid, &key, 1);

    if (error || key == NULL) {
        log_error("GPG: Failed to get key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        *err_str = strdup(gpgme_strerror(error));
        gpgme_release(ctx);
        return FALSE;
    }

    if (key == NULL) {
        *err_str = strdup("Unknown error");
        gpgme_release(ctx);
        return FALSE;
    }

    gpgme_release(ctx);
    gpgme_key_unref(key);
    return TRUE;

}

gboolean
p_gpg_available(const char *const barejid)
{
    char *pubkey = g_hash_table_lookup(pubkeys, barejid);
    return (pubkey != NULL);
}

void
p_gpg_verify(const char *const barejid, const char *const sign)
{
    if (!sign) {
        return;
    }

    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);

    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return;
    }

    char *sign_with_header_footer = _add_header_footer(sign, PGP_SIGNATURE_HEADER, PGP_SIGNATURE_FOOTER);
    gpgme_data_t sign_data;
    gpgme_data_new_from_mem(&sign_data, sign_with_header_footer, strlen(sign_with_header_footer), 1);
    free(sign_with_header_footer);

    gpgme_data_t plain_data;
    gpgme_data_new(&plain_data);

    error = gpgme_op_verify(ctx, sign_data, NULL, plain_data);
    gpgme_data_release(sign_data);
    gpgme_data_release(plain_data);

    if (error) {
        log_error("GPG: Failed to verify. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return;
    }

    gpgme_verify_result_t result = gpgme_op_verify_result(ctx);
    if (result) {
        if (result->signatures) {
            gpgme_key_t key = NULL;
            error = gpgme_get_key(ctx, result->signatures->fpr, &key, 0);
            if (error) {
                log_debug("Could not find PGP key with ID %s for %s", result->signatures->fpr, barejid);
            } else {
                log_debug("Fingerprint found for %s: %s ", barejid, key->subkeys->fpr);
                ProfPGPPubKeyId *pubkeyid = malloc(sizeof(ProfPGPPubKeyId));
                pubkeyid->id = strdup(key->subkeys->keyid);
                pubkeyid->received = TRUE;
                g_hash_table_replace(pubkeys, strdup(barejid), pubkeyid);
            }

            gpgme_key_unref(key);
        }
    }

    gpgme_release(ctx);
}

char*
p_gpg_sign(const char *const str, const char *const fp)
{
    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);
    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return NULL;
    }

    gpgme_set_passphrase_cb(ctx, (gpgme_passphrase_cb_t)_p_gpg_passphrase_cb, NULL);

    gpgme_key_t key = NULL;
    error = gpgme_get_key(ctx, fp, &key, 1);

    if (error || key == NULL) {
        log_error("GPG: Failed to get key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return NULL;
    }

    gpgme_signers_clear(ctx);
    error = gpgme_signers_add(ctx, key);
    gpgme_key_unref(key);

    if (error) {
        log_error("GPG: Failed to load signer. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return NULL;
    }

    char *str_or_empty = NULL;
    if (str) {
        str_or_empty = strdup(str);
    } else {
        str_or_empty = strdup("");
    }
    gpgme_data_t str_data;
    gpgme_data_new_from_mem(&str_data, str_or_empty, strlen(str_or_empty), 1);
    free(str_or_empty);

    gpgme_data_t signed_data;
    gpgme_data_new(&signed_data);

    gpgme_set_armor(ctx,1);
    error = gpgme_op_sign(ctx, str_data, signed_data, GPGME_SIG_MODE_DETACH);
    gpgme_data_release(str_data);
    gpgme_release(ctx);

    if (error) {
        log_error("GPG: Failed to sign string. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_data_release(signed_data);
        return NULL;
    }

    char *result = NULL;

    size_t len = 0;
    char *signed_str = gpgme_data_release_and_get_mem(signed_data, &len);
    if (signed_str) {
        GString *signed_gstr = g_string_new("");
        g_string_append_len(signed_gstr, signed_str, len);
        result = _remove_header_footer(signed_gstr->str, PGP_SIGNATURE_FOOTER);
        g_string_free(signed_gstr, TRUE);
        gpgme_free(signed_str);
    }

    if (passphrase_attempt) {
        passphrase = strdup(passphrase_attempt);
    }

    return result;
}

char*
p_gpg_encrypt(const char *const barejid, const char *const message, const char *const fp)
{
    ProfPGPPubKeyId *pubkeyid = g_hash_table_lookup(pubkeys, barejid);
    if (!pubkeyid) {
        return NULL;
    }
    if (!pubkeyid->id) {
        return NULL;
    }

    gpgme_key_t keys[3];

    keys[0] = NULL;
    keys[1] = NULL;
    keys[2] = NULL;

    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);
    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return NULL;
    }

    gpgme_key_t receiver_key;
    error = gpgme_get_key(ctx, pubkeyid->id, &receiver_key, 0);
    if (error || receiver_key == NULL) {
        log_error("GPG: Failed to get receiver_key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return NULL;
    }
    keys[0] = receiver_key;

    gpgme_key_t sender_key = NULL;
    error = gpgme_get_key(ctx, fp, &sender_key, 0);
    if (error || sender_key == NULL) {
        log_error("GPG: Failed to get sender_key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return NULL;
    }
    keys[1] = sender_key;

    gpgme_data_t plain;
    gpgme_data_new_from_mem(&plain, message, strlen(message), 1);

    gpgme_data_t cipher;
    gpgme_data_new(&cipher);

    gpgme_set_armor(ctx, 1);
    error = gpgme_op_encrypt(ctx, keys, GPGME_ENCRYPT_ALWAYS_TRUST, plain, cipher);
    gpgme_data_release(plain);
    gpgme_release(ctx);
    gpgme_key_unref(receiver_key);
    gpgme_key_unref(sender_key);

    if (error) {
        log_error("GPG: Failed to encrypt message. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return NULL;
    }

    size_t len;
    char *cipher_str = gpgme_data_release_and_get_mem(cipher, &len);

    char *result = NULL;
    if (cipher_str) {
        GString *cipher_gstr = g_string_new("");
        g_string_append_len(cipher_gstr, cipher_str, len);
        result = _remove_header_footer(cipher_gstr->str, PGP_MESSAGE_FOOTER);
        g_string_free(cipher_gstr, TRUE);
        gpgme_free(cipher_str);
    }

    return result;
}

char*
p_gpg_decrypt(const char *const cipher)
{
    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);

    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return NULL;
    }

    gpgme_set_passphrase_cb(ctx, (gpgme_passphrase_cb_t)_p_gpg_passphrase_cb, NULL);

    char *cipher_with_headers = _add_header_footer(cipher, PGP_MESSAGE_HEADER, PGP_MESSAGE_FOOTER);
    gpgme_data_t cipher_data;
    gpgme_data_new_from_mem(&cipher_data, cipher_with_headers, strlen(cipher_with_headers), 1);
    free(cipher_with_headers);

    gpgme_data_t plain_data;
    gpgme_data_new(&plain_data);

    error = gpgme_op_decrypt(ctx, cipher_data, plain_data);
    gpgme_data_release(cipher_data);

    if (error) {
        log_error("GPG: Failed to encrypt message. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_data_release(plain_data);
        gpgme_release(ctx);
        return NULL;
    }

    gpgme_decrypt_result_t res = gpgme_op_decrypt_result(ctx);
    if (res) {
        GString *recipients_str = g_string_new("");
        gpgme_recipient_t recipient = res->recipients;
        while (recipient) {
            gpgme_key_t key;
            error = gpgme_get_key(ctx, recipient->keyid, &key, 1);

            if (!error && key) {
                const char *addr = gpgme_key_get_string_attr(key, GPGME_ATTR_EMAIL, NULL, 0);
                if (addr) {
                    g_string_append(recipients_str, addr);
                }
                gpgme_key_unref(key);
            }

            if (recipient->next) {
                g_string_append(recipients_str, ", ");
            }

            recipient = recipient->next;
        }

        log_debug("GPG: Decrypted message for recipients: %s", recipients_str->str);
        g_string_free(recipients_str, TRUE);
    }
    gpgme_release(ctx);

    size_t len = 0;
    char *plain_str = gpgme_data_release_and_get_mem(plain_data, &len);
    char *result = NULL;
    if (plain_str) {
        plain_str[len] = 0;
        result = g_strdup(plain_str);
    }
    gpgme_free(plain_str);

    if (passphrase_attempt) {
        passphrase = strdup(passphrase_attempt);
    }

    return result;
}

void
p_gpg_free_decrypted(char *decrypted)
{
    g_free(decrypted);
}

char*
p_gpg_autocomplete_key(const char *const search_str)
{
    return autocomplete_complete(key_ac, search_str, TRUE);
}

void
p_gpg_autocomplete_key_reset(void)
{
    autocomplete_reset(key_ac);
}

char*
p_gpg_format_fp_str(char *fp)
{
    if (!fp) {
        return NULL;
    }

    GString *format = g_string_new("");
    int i;
    int len = strlen(fp);
    for (i = 0; i < len; i++) {
        g_string_append_c(format, fp[i]);
        if (((i+1) % 4 == 0) && (i+1 < len)) {
            g_string_append_c(format, ' ');
        }
    }

    char *result = format->str;
    g_string_free(format, FALSE);

    return result;
}

static char*
_remove_header_footer(char *str, const char *const footer)
{
    int pos = 0;
    int newlines = 0;

    while (newlines < 3) {
        if (str[pos] == '\n') {
            newlines++;
        }
        pos++;

        if (str[pos] == '\0') {
            return NULL;
        }
    }

    char *stripped = strdup(&str[pos]);
    char *footer_start = g_strrstr(stripped, footer);
    footer_start[0] = '\0';

    return stripped;
}

static char*
_add_header_footer(const char *const str, const char *const header, const char *const footer)
{
    GString *result_str = g_string_new("");

    g_string_append(result_str, header);
    g_string_append(result_str, "\n\n");
    g_string_append(result_str, str);
    g_string_append(result_str, "\n");
    g_string_append(result_str, footer);

    char *result = result_str->str;
    g_string_free(result_str, FALSE);

    return result;
}

static void
_save_pubkeys(void)
{
    gsize g_data_size;
    gchar *g_pubkeys_data = g_key_file_to_data(pubkeyfile, &g_data_size, NULL);
    g_file_set_contents(pubsloc, g_pubkeys_data, g_data_size, NULL);
    g_chmod(pubsloc, S_IRUSR | S_IWUSR);
    g_free(g_pubkeys_data);
}