summaryrefslogtreecommitdiffstats
path: root/kio/misc/kssld/kssld.cpp
blob: 22bf6ab848c4bd3dc6b025c179f599cadadff867 (plain)
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
/*
   This file is part of the KDE libraries

   Copyright (c) 2001-2005 George Staikos <staikos@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <tqtimer.h>

#include "kssld.h"
#include <kconfig.h>
#include <ksimpleconfig.h>
#include <ksslcertchain.h>
#include <ksslcertificate.h>
#include <ksslcertificatehome.h>
#include <ksslpkcs12.h>
#include <ksslx509map.h>
#include <tqptrlist.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <pwd.h>
#include <unistd.h>
#include <tqfile.h>
#include <tqsortedlist.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <tqdatetime.h>

#include <kmdcodec.h>
#include <kopenssl.h>

// See design notes at end

extern "C" {
	KDE_EXPORT KDEDModule *create_kssld(const TQCString &name) {
		return new KSSLD(name);
	}

	KDE_EXPORT void *__kde_do_unload;
}


static void updatePoliciesConfig(TDEConfig *cfg) {
	TQStringList groups = cfg->groupList();

	for (TQStringList::Iterator i = groups.begin(); i != groups.end(); ++i) {
		if ((*i).isEmpty() || *i == "General") {
			continue;
		}

		cfg->setGroup(*i);

		// remove it if it has expired
		if (!cfg->readBoolEntry("Permanent") && cfg->readDateTimeEntry("Expires") < TQDateTime::currentDateTime()) {
			cfg->deleteGroup(*i);
			continue;
		}

		TQString encodedCertStr = cfg->readEntry("Certificate");
		TQCString encodedCert = encodedCertStr.local8Bit();
	       	KSSLCertificate *newCert = KSSLCertificate::fromString(encodedCert);
		if (!newCert) {
			cfg->deleteGroup(*i);
			continue;
		}

		KSSLCertificateCache::KSSLCertificatePolicy policy = (KSSLCertificateCache::KSSLCertificatePolicy) cfg->readNumEntry("Policy");
		bool permanent = cfg->readBoolEntry("Permanent");
		TQDateTime expires = cfg->readDateTimeEntry("Expires");
		TQStringList hosts = cfg->readListEntry("Hosts");
		TQStringList chain = cfg->readListEntry("Chain");
		cfg->deleteGroup(*i);

		cfg->setGroup(newCert->getMD5Digest());
		cfg->writeEntry("Certificate", encodedCertStr);
		cfg->writeEntry("Policy", policy);
		cfg->writeEntry("Permanent", permanent);
		cfg->writeEntry("Expires", expires);
		cfg->writeEntry("Hosts", hosts);
		cfg->writeEntry("Chain", chain);
		delete newCert;
	}

	cfg->setGroup("General");
	cfg->writeEntry("policies version", 2);

	cfg->sync();
}


KSSLD::KSSLD(const TQCString &name) : KDEDModule(name)
{
// ----------------------- FOR THE CACHE ------------------------------------	
	cfg = new KSimpleConfig("ksslpolicies", false);
	cfg->setGroup("General");
	if (2 != cfg->readNumEntry("policies version", 0)) {
		::updatePoliciesConfig(cfg);
	}
	TDEGlobal::dirs()->addResourceType("kssl", KStandardDirs::kde_default("data") + "kssl");
	caVerifyUpdate();
	cacheLoadDefaultPolicies();
	certList.setAutoDelete(false);
	kossl = KOSSL::self();

// ----------------------- FOR THE HOME -------------------------------------
}
  

KSSLD::~KSSLD()
{
// ----------------------- FOR THE CACHE ------------------------------------	
	cacheClearList();
	delete cfg;

// ----------------------- FOR THE HOME -------------------------------------
}

  


// A node in the cache
class KSSLCNode {
	public:
		KSSLCertificate *cert;
		KSSLCertificateCache::KSSLCertificatePolicy policy;
		bool permanent;
		TQDateTime expires;
		TQStringList hosts;
		KSSLCNode() { cert = 0L;
				policy = KSSLCertificateCache::Unknown; 
				permanent = true;
			}
		~KSSLCNode() { delete cert; }
};



void KSSLD::cacheSaveToDisk() {
KSSLCNode *node;

	cfg->setGroup("General");
	cfg->writeEntry("policies version", 2);

	for (node = certList.first(); node; node = certList.next()) {
		if (node->permanent ||
			node->expires > TQDateTime::currentDateTime()) {
			// First convert to a binary format and then write the
			// kconfig entry write the (CN, policy, cert) to
			// KSimpleConfig
			cfg->setGroup(node->cert->getMD5Digest());
			cfg->writeEntry("Certificate", node->cert->toString());
			cfg->writeEntry("Policy", node->policy);
			cfg->writeEntry("Expires", node->expires);
			cfg->writeEntry("Permanent", node->permanent);
			cfg->writeEntry("Hosts", node->hosts);

			// Also write the chain
			TQStringList qsl;
			TQPtrList<KSSLCertificate> cl =
						node->cert->chain().getChain();
			for (KSSLCertificate *c = cl.first();
							c != 0;
							c = cl.next()) {
				//kdDebug() << "Certificate in chain: "
				//	    <<  c->toString() << endl;
				qsl << c->toString();
			}

			cl.setAutoDelete(true);
			cfg->writeEntry("Chain", qsl);
		}
	}  

	cfg->sync();

	// insure proper permissions -- contains sensitive data
	TQString cfgName(TDEGlobal::dirs()->findResource("config", "ksslpolicies"));

	if (!cfgName.isEmpty()) {
		::chmod(TQFile::encodeName(cfgName), 0600);
	}
}


void KSSLD::cacheReload() {
	cacheClearList();
	delete cfg;
	cfg = new KSimpleConfig("ksslpolicies", false);
	cacheLoadDefaultPolicies();
}


void KSSLD::cacheClearList() {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		certList.remove(node);
		delete node;
	}

	skEmail.clear();
	skMD5Digest.clear();
}


void KSSLD::cacheLoadDefaultPolicies() {
TQStringList groups = cfg->groupList();

	for (TQStringList::Iterator i = groups.begin();
				i != groups.end();
				++i) {
		if ((*i).isEmpty() || *i == "General") {
			continue;
		}

		cfg->setGroup(*i);

		// remove it if it has expired
		if (!cfg->readBoolEntry("Permanent") &&
			cfg->readDateTimeEntry("Expires") <
				TQDateTime::currentDateTime()) {
			cfg->deleteGroup(*i);
			continue;
		}

		TQCString encodedCert;
		KSSLCertificate *newCert;

		encodedCert = cfg->readEntry("Certificate").local8Bit();
	       	newCert = KSSLCertificate::fromString(encodedCert);

		if (!newCert) {
		       continue;
		}

		KSSLCNode *n = new KSSLCNode;
		n->cert = newCert;
		n->policy = (KSSLCertificateCache::KSSLCertificatePolicy) cfg->readNumEntry("Policy");
		n->permanent = cfg->readBoolEntry("Permanent");
		n->expires = cfg->readDateTimeEntry("Expires");
		n->hosts = cfg->readListEntry("Hosts");
		newCert->chain().setCertChain(cfg->readListEntry("Chain"));
		certList.append(n); 
		searchAddCert(newCert);
	}
}


void KSSLD::cacheAddCertificate(KSSLCertificate cert, 
			KSSLCertificateCache::KSSLCertificatePolicy policy,
			bool permanent) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {
			node->policy = policy;
			node->permanent = permanent;

			if (!permanent) {
				node->expires = TQDateTime::currentDateTime();
				// FIXME: make this configurable
				node->expires = TQT_TQDATETIME_OBJECT(node->expires.addSecs(3600));
			}

			cacheSaveToDisk();
			return;
		}
	}

	KSSLCNode *n = new KSSLCNode;
	n->cert = cert.replicate();
	n->policy = policy;
	n->permanent = permanent;
	// remove the old one
	cacheRemoveByCertificate(*(n->cert));
	certList.prepend(n); 

	if (!permanent) {
		n->expires = TQDateTime::currentDateTime();
		n->expires = TQT_TQDATETIME_OBJECT(n->expires.addSecs(3600));
	}

	searchAddCert(n->cert);
	cacheSaveToDisk();
}


KSSLCertificateCache::KSSLCertificatePolicy KSSLD::cacheGetPolicyByCN(TQString cn) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
			if (!node->permanent &&
				node->expires < TQDateTime::currentDateTime()) {
				certList.remove(node);
				cfg->deleteGroup(node->cert->getMD5Digest());
				delete node;
				continue;
			}

			certList.remove(node);
			certList.prepend(node);
			cacheSaveToDisk();
			return node->policy;
		}
	}

	cacheSaveToDisk();

return KSSLCertificateCache::Unknown;
}


KSSLCertificateCache::KSSLCertificatePolicy KSSLD::cacheGetPolicyByCertificate(KSSLCertificate cert) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {  
			if (!node->permanent &&
				node->expires < TQDateTime::currentDateTime()) {
				certList.remove(node);
				cfg->deleteGroup(node->cert->getMD5Digest());
				delete node;
				cacheSaveToDisk();
				return KSSLCertificateCache::Unknown;
			}

			certList.remove(node);
			certList.prepend(node);
			return node->policy;
		}
	}

return KSSLCertificateCache::Unknown;
}


bool KSSLD::cacheSeenCN(TQString cn) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
			if (!node->permanent &&
				node->expires < TQDateTime::currentDateTime()) {
				certList.remove(node);
				cfg->deleteGroup(node->cert->getMD5Digest());
				delete node;
				cacheSaveToDisk();
				continue;
			}

			certList.remove(node);
			certList.prepend(node);
			return true;
		}
	}

return false;
}


bool KSSLD::cacheSeenCertificate(KSSLCertificate cert) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {
			if (!node->permanent &&
				node->expires < TQDateTime::currentDateTime()) {
				certList.remove(node);
				cfg->deleteGroup(node->cert->getMD5Digest());
				delete node;
				cacheSaveToDisk();
				return false;
			}

			certList.remove(node);
			certList.prepend(node);
			return true;
		}
	}

return false;
}


bool KSSLD::cacheIsPermanent(KSSLCertificate cert) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {
			if (!node->permanent && node->expires <
					TQDateTime::currentDateTime()) {
				certList.remove(node);
				cfg->deleteGroup(node->cert->getMD5Digest());
				delete node;
				cacheSaveToDisk();
				return false;
			}

			certList.remove(node);
			certList.prepend(node);
			return node->permanent;
		}
	}

return false;
}


bool KSSLD::cacheRemoveBySubject(TQString subject) {
KSSLCNode *node;
bool gotOne = false;

	for (node = certList.first(); node; node = certList.next()) {
		if (node->cert->getSubject() == subject) {
			certList.remove(node);
			cfg->deleteGroup(node->cert->getMD5Digest());
			searchRemoveCert(node->cert);
			delete node;
			gotOne = true;
		}
	}

	cacheSaveToDisk();

return gotOne;
}


bool KSSLD::cacheRemoveByCN(TQString cn) {
KSSLCNode *node;
bool gotOne = false;

	for (node = certList.first(); node; node = certList.next()) {
		if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
			certList.remove(node);
			cfg->deleteGroup(node->cert->getMD5Digest());
			searchRemoveCert(node->cert);
			delete node;
			gotOne = true;
		}
	}

	cacheSaveToDisk();

return gotOne;
}


bool KSSLD::cacheRemoveByCertificate(KSSLCertificate cert) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {
			certList.remove(node);
			cfg->deleteGroup(node->cert->getMD5Digest());
			searchRemoveCert(node->cert);
			delete node;
			cacheSaveToDisk();
			return true;
		}
	}

return false;
}


bool KSSLD::cacheModifyByCN(TQString cn,
                            KSSLCertificateCache::KSSLCertificatePolicy policy,                             bool permanent,
                            TQDateTime expires) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
			node->permanent = permanent;
			node->expires = expires;
			node->policy = policy;
			certList.remove(node);
			certList.prepend(node);
			cacheSaveToDisk();
			return true;
		}
	}

return false;
}


bool KSSLD::cacheModifyByCertificate(KSSLCertificate cert,
                             KSSLCertificateCache::KSSLCertificatePolicy policy,
			     bool permanent,
			     TQDateTime expires) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {
			node->permanent = permanent;
			node->expires = expires;
			node->policy = policy;
			certList.remove(node);
			certList.prepend(node);
			cacheSaveToDisk();
			return true;
		}
	}

return false;
}


TQStringList KSSLD::cacheGetHostList(KSSLCertificate cert) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {
			if (!node->permanent && node->expires <
				       TQDateTime::currentDateTime()) {
				certList.remove(node);
				cfg->deleteGroup(node->cert->getMD5Digest());
				searchRemoveCert(node->cert);
				delete node;
				cacheSaveToDisk();
				return TQStringList();
			}

			certList.remove(node);
			certList.prepend(node);
			return node->hosts;
		}
	}

return TQStringList();
}


bool KSSLD::cacheAddHost(KSSLCertificate cert, TQString host) {
KSSLCNode *node;

	if (host.isEmpty())
		return true;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {
			if (!node->permanent && node->expires <
				       	TQDateTime::currentDateTime()) {
				certList.remove(node);
				cfg->deleteGroup(node->cert->getMD5Digest());
				searchRemoveCert(node->cert);
				delete node;
				cacheSaveToDisk();
				return false;
			}

			if (!node->hosts.contains(host)) {
				node->hosts << host;
			}

			certList.remove(node);
			certList.prepend(node);
			cacheSaveToDisk();
			return true;
		}
	}

return false;
}


bool KSSLD::cacheRemoveHost(KSSLCertificate cert, TQString host) {
KSSLCNode *node;

	for (node = certList.first(); node; node = certList.next()) {
		if (cert == *(node->cert)) {
			if (!node->permanent && node->expires <
				       	TQDateTime::currentDateTime()) {
				certList.remove(node);
				cfg->deleteGroup(node->cert->getMD5Digest());
				searchRemoveCert(node->cert);
				delete node;
				cacheSaveToDisk();
				return false;
			}
			node->hosts.remove(host);
			certList.remove(node);
			certList.prepend(node);
			cacheSaveToDisk();
			return true;
		}
	}

return false;
}




///////////////////////////////////////////////////////////////////////////

void KSSLD::caVerifyUpdate() {
	TQString path = TDEGlobal::dirs()->saveLocation("kssl") + "/ca-bundle.crt";
	if (!TQFile::exists(path))
		return;
	
	cfg->setGroup(TQString::null);
	TQ_UINT32 newStamp = TDEGlobal::dirs()->calcResourceHash("config", "ksslcalist", true);
	TQ_UINT32 oldStamp = cfg->readUnsignedNumEntry("ksslcalistStamp");
	if (oldStamp != newStamp)
	{
		caRegenerate();
		cfg->writeEntry("ksslcalistStamp", newStamp);
		cfg->sync();
	}
}

bool KSSLD::caRegenerate() {
TQString path = TDEGlobal::dirs()->saveLocation("kssl") + "/ca-bundle.crt";

TQFile out(path);

	if (!out.open(IO_WriteOnly))
		return false;

TDEConfig cfg("ksslcalist", true, false);

TQStringList x = cfg.groupList();

	for (TQStringList::Iterator i = x.begin();
				   i != x.end();
				   ++i) {
		if ((*i).isEmpty() || *i == "<default>") continue;

		cfg.setGroup(*i);

		if (!cfg.readBoolEntry("site", false)) continue;

		TQString cert = cfg.readEntry("x509", "");
		if (cert.length() <= 0) continue;

		unsigned int xx = cert.length() - 1;
		for (unsigned int j = 0; j < xx/64; j++) {
			cert.insert(64*(j+1)+j, '\n');
		}
		out.writeBlock("-----BEGIN CERTIFICATE-----\n", 28);
		out.writeBlock(cert.latin1(), cert.length());
		out.writeBlock("\n-----END CERTIFICATE-----\n\n", 28);
		out.flush();
	}

return true;
}



bool KSSLD::caAdd(TQString certificate, bool ssl, bool email, bool code) {
KSSLCertificate *x = KSSLCertificate::fromString(certificate.local8Bit());

	if (!x) return false;

TDEConfig cfg("ksslcalist", false, false);

	cfg.setGroup(x->getSubject());
	cfg.writeEntry("x509", certificate);
	cfg.writeEntry("site", ssl);
	cfg.writeEntry("email", email);
	cfg.writeEntry("code", code);

	cfg.sync();
	delete x;

return true;
}


/**
  * @internal
  * Returns a list of certificates as QStrings read from the given file
  */
static TQStringList caReadCerticatesFromFile(TQString filename) {

	TQStringList certificates;
	TQString certificate, temp;
	TQFile file(filename);

	if (!file.open(IO_ReadOnly))
		return certificates;

	while (!file.atEnd()) {
		file.readLine(temp, 999);
		if (temp.startsWith("-----BEGIN CERTIFICATE-----")) {
			certificate = TQString::null;
			continue;
		}

		if (temp.startsWith("-----END CERTIFICATE-----")) {
			certificates.append(certificate);
			certificate = TQString::null;
			continue;
		}

		certificate += temp.stripWhiteSpace();
	}

	file.close();

	return certificates;
}

bool KSSLD::caAddFromFile(TQString filename, bool ssl, bool email, bool code) {

	TQStringList certificates;
	certificates = caReadCerticatesFromFile(filename);
	if (certificates.isEmpty())
		return false;

	bool ok = true;

	for (TQStringList::Iterator it = certificates.begin();
					it != certificates.end(); ++it ) {
		ok &= caAdd(*it, ssl, email, code);
	}

	return ok;
}

bool KSSLD::caRemoveFromFile(TQString filename) {

	TQStringList certificates;
	certificates = caReadCerticatesFromFile(filename);
	if (certificates.isEmpty())
		return false;

	bool ok = true;

	for (TQStringList::Iterator it = certificates.begin();
					it != certificates.end(); ++it ) {
		TQString certificate = *it;
		KSSLCertificate *x = KSSLCertificate::fromString(certificate.local8Bit());
		ok &= x && caRemove(x->getSubject());
		delete x;
	}

	return ok;
}


TQStringList KSSLD::caList() {
TQStringList x;
TDEConfig cfg("ksslcalist", true, false);

	x = cfg.groupList();
	x.remove("<default>");

return x;
}


bool KSSLD::caUseForSSL(TQString subject) {
TDEConfig cfg("ksslcalist", true, false);

	if (!cfg.hasGroup(subject))
		return false;

	cfg.setGroup(subject);
return cfg.readBoolEntry("site", false);
}



bool KSSLD::caUseForEmail(TQString subject) {
TDEConfig cfg("ksslcalist", true, false);

	if (!cfg.hasGroup(subject))
		return false;

	cfg.setGroup(subject);
return cfg.readBoolEntry("email", false);
}



bool KSSLD::caUseForCode(TQString subject) {
TDEConfig cfg("ksslcalist", true, false);

	if (!cfg.hasGroup(subject))
		return false;

	cfg.setGroup(subject);
return cfg.readBoolEntry("code", false);
}


bool KSSLD::caRemove(TQString subject) {
TDEConfig cfg("ksslcalist", false, false);
	if (!cfg.hasGroup(subject))
		return false;

	cfg.deleteGroup(subject);
	cfg.sync();

return true;
}


TQString KSSLD::caGetCert(TQString subject) {
TDEConfig cfg("ksslcalist", true, false);
	if (!cfg.hasGroup(subject))
		return TQString::null;

	cfg.setGroup(subject);

return cfg.readEntry("x509", TQString::null);
}


bool KSSLD::caSetUse(TQString subject, bool ssl, bool email, bool code) {
TDEConfig cfg("ksslcalist", false, false);
	if (!cfg.hasGroup(subject))
		return false;

	cfg.setGroup(subject);

	cfg.writeEntry("site", ssl);
	cfg.writeEntry("email", email);
	cfg.writeEntry("code", code);
	cfg.sync();

return true;
}

///////////////////////////////////////////////////////////////////////////

void KSSLD::searchAddCert(KSSLCertificate *cert) {
	skMD5Digest.insert(cert->getMD5Digest(), cert, true);

	TQStringList mails;
	cert->getEmails(mails);
	for(TQStringList::const_iterator iter = mails.begin(); iter != mails.end(); ++iter) {
		TQString email = static_cast<const TQString &>(*iter).lower();
		TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(email);

		if (it == skEmail.end())
			it = skEmail.insert(email, TQPtrVector<KSSLCertificate>());

		TQPtrVector<KSSLCertificate> &elem = *it;
		
		if (elem.findRef(cert) == -1) {
			unsigned int n = 0;
			for(; n < elem.size(); n++) {
				if (!elem.at(n)) {
					elem.insert(n, cert);
					break;
				}
			}
			if (n == elem.size()) {
				elem.resize(n+1);
				elem.insert(n, cert);
			}
		}
	}	
}


void KSSLD::searchRemoveCert(KSSLCertificate *cert) {
	skMD5Digest.remove(cert->getMD5Digest());

	TQStringList mails;
	cert->getEmails(mails);
	for(TQStringList::const_iterator iter = mails.begin(); iter != mails.end(); ++iter) {
		TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(static_cast<const TQString &>(*iter).lower());

		if (it == skEmail.end())
		       break;

		TQPtrVector<KSSLCertificate> &elem = *it;

		int n = elem.findRef(cert);
		if (n != -1)
			elem.remove(n);
	}
}	


TQStringList KSSLD::getKDEKeyByEmail(const TQString &email) {
	TQStringList rc;
	TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(email.lower());

	kdDebug() << "GETKDEKey " << email.latin1() << endl;

	if (it == skEmail.end())
		return rc;

	TQPtrVector<KSSLCertificate> &elem = *it;
	for (unsigned int n = 0; n < elem.size(); n++) {
		KSSLCertificate *cert = elem.at(n);
		if (cert) {
			rc.append(cert->getKDEKey());
		}
	}

	kdDebug() << "ergebnisse: " << rc.size() << " " << elem.size() << endl;
	return rc;
}


KSSLCertificate KSSLD::getCertByMD5Digest(const TQString &key) {
	TQMap<TQString, KSSLCertificate *>::iterator iter = skMD5Digest.find(key);
	
	kdDebug() << "Searching cert for " << key.latin1() << endl;

	if (iter != skMD5Digest.end())
		return **iter;
	
	KSSLCertificate rc; // FIXME: Better way to return a not found condition?
	kdDebug() << "Not found: " << rc.toString().latin1() << endl;
	return rc;
}	


///////////////////////////////////////////////////////////////////////////

//
//  Certificate Home methods
//

TQStringList KSSLD::getHomeCertificateList() {
	return KSSLCertificateHome::getCertificateList();
}

bool KSSLD::addHomeCertificateFile(TQString filename, TQString password, bool storePass) {
	return KSSLCertificateHome::addCertificate(filename, password, storePass);
}

bool KSSLD::addHomeCertificatePKCS12(TQString base64cert, TQString passToStore) {
	bool ok;
	KSSLPKCS12 *pkcs12 = KSSLPKCS12::fromString(base64cert, passToStore);
	ok = KSSLCertificateHome::addCertificate(pkcs12, passToStore);
	delete pkcs12;
	return ok;
}

bool KSSLD::deleteHomeCertificateByFile(TQString filename, TQString password) {
	return KSSLCertificateHome::deleteCertificate(filename, password);
}

bool KSSLD::deleteHomeCertificateByPKCS12(TQString base64cert, TQString password) {
	bool ok;
	KSSLPKCS12 *pkcs12 = KSSLPKCS12::fromString(base64cert, password);
	ok = KSSLCertificateHome::deleteCertificate(pkcs12);
	delete pkcs12;
	return ok;
}

bool KSSLD::deleteHomeCertificateByName(TQString name) {
	return KSSLCertificateHome::deleteCertificateByName(name);
}



///////////////////////////////////////////////////////////////////////////

#include "kssld.moc"


/*

  DESIGN     - KSSLCertificateCache
  ------

  This is the first implementation and I think this cache actually needs
  experimentation to determine which implementation works best.  My current
  options are:

   (1) Store copies of the X509 certificates in a TQPtrList using a self
       organizing heuristic as described by Munro and Suwanda.
   (2) Store copies of the X509 certificates in a tree structure, perhaps
       a redblack tree, avl tree, or even just a simple binary tree.
   (3) Store the CN's in a tree or list and use them as a hash to retrieve
       the X509 certificates.
   (4) Create "nodes" containing the X509 certificate and place them in
       two structures concurrently, one organized by CN, the other by
       X509 serial number.

  This implementation uses (1).  (4) is definitely attractive, but I don't
  think it will be necessary to go so crazy with performance, and perhaps
  end up performing poorly in situations where there are very few entries in
  the cache (which is most likely the case most of the time).  The style of
  heuristic is move-to-front, not swap-forward.  This seems to make more
  sense because the typical user will hit a site at least a few times in a
  row before moving to a new one.

  What I worry about most with respect to performance is that cryptographic
  routines are expensive and if we have to perform them on each X509
  certificate until the right one is found, we will perform poorly.

  All in all, this code is actually quite crucial for performance on SSL
  website, especially those with many image files loaded via SSL.  If a
  site loads 15 images, we will have to run through this code 15 times.
  A heuristic for self organization will make each successive lookup faster.
  Sounds good, doesn't it?

  DO NOT ATTEMPT TO GUESS WHICH CERTIFICATES ARE ACCEPTIBLE IN YOUR CODE!!
  ALWAYS USE THE CACHE.  IT MAY CHECK THINGS THAT YOU DON'T THINK OF, AND
  ALSO IF THERE IS A BUG IN THE CHECKING CODE, IF IT IS ALL CONTAINED IN
  THIS LIBRARY, A MINOR FIX WILL FIX ALL APPLICATIONS.
 */