summaryrefslogtreecommitdiff
path: root/lib/opencdk/stream.c
blob: 7e95924aed971c6bca316a4c6eb0e8f0151eefcc (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
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
/* stream.c - The stream implementation
 * Copyright (C) 2002, 2003, 2007, 2008 Free Software Foundation, Inc.
 *
 * Author: Timo Schulz
 *
 * This file is part of OpenCDK.
 *
 * The OpenCDK library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; 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 <assert.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

#include "opencdk.h"
#include "main.h"
#include "filters.h"
#include "stream.h"
#include "types.h"

/* This is the maximal amount of bytes we map. */
#define MAX_MAP_SIZE 16777216

static int stream_flush (cdk_stream_t s);
static int stream_filter_write (cdk_stream_t s);
static int stream_cache_flush (cdk_stream_t s, FILE *fp);
struct stream_filter_s* filter_add (cdk_stream_t s, filter_fnct_t fnc, int type);

/* Customized tmpfile() version from misc.c */
FILE *my_tmpfile (void);
    

/* FIXME: The read/write/putc/getc function cannot directly
          return an error code. It is stored in an error variable
          inside the string. Right now there is no code to
          return the error code or to reset it. */

/**
 * cdk_stream_open:
 * @file: The file to open
 * @ret_s: The new STREAM object
 * 
 * Creates a new stream based on an existing file. The stream is
 * opened in read-only mode.
 **/
cdk_error_t
cdk_stream_open (const char *file, cdk_stream_t *ret_s)
{
  return _cdk_stream_open_mode (file, "rb", ret_s);
}


/* Helper function to allow to open a stream in different modes. */
cdk_error_t
_cdk_stream_open_mode (const char *file, const char *mode, cdk_stream_t *ret_s)
{
  cdk_stream_t s;
  
  if (!file || !ret_s)
    return CDK_Inv_Value;
  
  _cdk_log_debug ("open stream `%s'\n", file);
  *ret_s = NULL;
  s = cdk_calloc (1, sizeof *s);
  if (!s)
    return CDK_Out_Of_Core;
  s->fname = cdk_strdup (file);
  if (!s->fname) 
    {
      cdk_free (s);
      return CDK_Out_Of_Core;
    }
  s->fp = fopen (file, mode);
  if (!s->fp) 
    {
      cdk_free (s->fname);
      cdk_free (s);
      return CDK_File_Error;
    }
  _cdk_log_debug ("open stream fd=%d\n", fileno (s->fp));
  s->flags.write = 0;
  *ret_s = s;
  return 0;
}


/**
 * cdk_stream_new_from_cbs:
 * @cbs: the callback context with all user callback functions
 * @opa: opaque handle which is passed to all callbacks.
 * @ret_s: the allocated stream
 * 
 * This function creates a stream which uses user callback
 * for the core operations (open, close, read, write, seek).
 */
cdk_error_t
cdk_stream_new_from_cbs (cdk_stream_cbs_t cbs, void *opa,
			 cdk_stream_t *ret_s)
{
  cdk_stream_t s;

  if (!cbs || !opa || !ret_s)
    return CDK_Inv_Value;
    
  *ret_s = NULL;
  s = cdk_calloc (1, sizeof *s);
  if (!s)
    return CDK_Out_Of_Core;
  
  s->cbs.read = cbs->read;
  s->cbs.write = cbs->write;
  s->cbs.seek = cbs->seek;
  s->cbs.release = cbs->release;
  s->cbs.open = cbs->open;
  s->cbs_hd = opa;
  *ret_s = s;
  
  /* If there is a user callback for open, we need to call it
     here because read/write expects an open stream. */
  if (s->cbs.open)
    return s->cbs.open (s->cbs_hd);  
  return 0;
}


/**
 * cdk_stream_new: 
 * @file: The name of the new file
 * @ret_s: The new STREAM object
 * 
 * Create a new stream into the given file.
 **/
cdk_error_t
cdk_stream_new (const char *file, cdk_stream_t *ret_s)
{
  cdk_stream_t s;
  
  if (!ret_s)
    return CDK_Inv_Value;
  
  _cdk_log_debug ("new stream `%s'\n", file? file : "[temp]");
  *ret_s = NULL;
  s = cdk_calloc (1, sizeof *s);
  if (!s)
    return CDK_Out_Of_Core;  
  s->flags.write = 1;
  if (!file)
    s->flags.temp = 1;
  else 
    {
      s->fname = cdk_strdup (file);
      if (!s->fname) 
	{
	  cdk_free (s);
	  return CDK_Out_Of_Core;
	}
    }
  s->fp = my_tmpfile ();
  if (!s->fp) 
    {
      cdk_free (s->fname);
      cdk_free (s);
      return CDK_File_Error;
    }
  _cdk_log_debug ("new stream fd=%d\n", fileno (s->fp));
  *ret_s = s;
  return 0;
}

/**
 * cdk_stream_create: 
 * @file: the filename
 * @ret_s: the object
 *
 * Creates a new stream.
 * The difference to cdk_stream_new is, that no filtering can be used with
 * this kind of stream and everything is written directly to the stream.
 **/
cdk_error_t
cdk_stream_create (const char *file, cdk_stream_t *ret_s)
{
  cdk_stream_t s;
  
  if (!file || !ret_s)
    return CDK_Inv_Value;
    
  _cdk_log_debug ("create stream `%s'\n", file);
  *ret_s = NULL;
  s = cdk_calloc (1, sizeof *s);
  if (!s)
    return CDK_Out_Of_Core;
  s->flags.write = 1;
  s->flags.filtrated = 1;
  s->fname = cdk_strdup (file);
  if (!s->fname)
    {
      cdk_free (s);
      return CDK_Out_Of_Core;
    }
  s->fp = fopen (file, "w+b");
  if (!s->fp)
    {
      cdk_free (s->fname);
      cdk_free (s);
      return CDK_File_Error;
    }
  _cdk_log_debug ("stream create fd=%d\n", fileno (s->fp));
  *ret_s = s;
  return 0;
}
    

/**
 * cdk_stream_tmp_new:
 * @r_out: the new temp stream.
 * 
 * Allocates a new tempory stream which is not associated with a file.
 */
cdk_error_t
cdk_stream_tmp_new (cdk_stream_t *r_out)
{
  return cdk_stream_new (NULL, r_out);
}



/**
 * cdk_stream_tmp_from_mem:
 * @buf: the buffer which shall be written to the temp stream.
 * @buflen: how large the buffer is
 * @r_out: the new stream with the given contents.
 * 
 * Creates a new tempory stream with the given contests.
 */
cdk_error_t
cdk_stream_tmp_from_mem (const void *buf, size_t buflen, cdk_stream_t *r_out)
{
  cdk_stream_t s;
  cdk_error_t rc;
  int nwritten;
  
  *r_out = NULL;
  rc = cdk_stream_tmp_new (&s);
  if (rc)
    return rc;
  
  nwritten = cdk_stream_write (s, buf, buflen);
  if (nwritten == EOF)
    {
      cdk_stream_close (s);
      return s->error;
    }
  cdk_stream_seek (s, 0);
  *r_out = s;
  return 0;
}

  
cdk_error_t
_cdk_stream_fpopen (FILE *fp, unsigned write_mode, cdk_stream_t *ret_out)
{
  cdk_stream_t s;

  *ret_out = NULL;
  s = cdk_calloc (1, sizeof *s);
  if (!s)
    return CDK_Out_Of_Core;
  
  _cdk_log_debug ("stream ref fd=%d\n", fileno (fp));
  s->fp = fp;
  s->fp_ref = 1;
  s->flags.filtrated = 1;
  s->flags.write = write_mode;
  
  *ret_out = s;
  return 0;
}


cdk_error_t
_cdk_stream_append (const char *file, cdk_stream_t *ret_s)
{
  cdk_stream_t s;
  cdk_error_t rc;

  if (!ret_s)
    return CDK_Inv_Value;
  *ret_s = NULL;
  
  rc = _cdk_stream_open_mode (file, "a+b", &s);
  if (rc)
    return rc;
  
  /* In the append mode, we need to write to the flag. */
  s->flags.write = 1;
  *ret_s = s;
  return 0;
}

/**
 * cdk_stream_is_compressed:
 * @s: the stream
 *
 * Check whether stream is compressed.
 *
 * Returns: 0 if the stream is uncompressed, otherwise the compression
 *   algorithm.
 */
int
cdk_stream_is_compressed (cdk_stream_t s)
{
  if (!s)
    return 0;
  return s->flags.compressed;
}

void
_cdk_stream_set_compress_algo (cdk_stream_t s, int algo)
{
  if (!s)
    return;
  s->flags.compressed = algo;
}


cdk_error_t
cdk_stream_flush (cdk_stream_t s)
{
  cdk_error_t rc;
  
  if (!s)
    return CDK_Inv_Value;
  
  /* The user callback does not support flush */
  if (s->cbs_hd)
    return 0;
  
  /* For read-only streams, no flush is needed. */
  if (!s->flags.write)
    return 0;
  
  if (!s->flags.filtrated)
    {
      if (!cdk_stream_get_length (s))
	return 0;
      rc = cdk_stream_seek (s, 0);
      if (!rc)
	rc = stream_flush (s);
      if (!rc)
	rc = stream_filter_write (s);
      s->flags.filtrated = 1;
      if (rc)
	{
	  s->error = rc;
	  return rc;
	}      
    }
  return 0;
}


void
cdk_stream_tmp_set_mode (cdk_stream_t s, int val)
{
  if (s && s->flags.temp)
    s->fmode = val;
}


/**
 * cdk_stream_close: Close a stream and flush all buffers.
 * @s: The STREAM object.
 *
 * This function work different for read or write streams. When the
 * stream is for reading, the filtering is already done and we can
 * simply close the file and all buffers.
 * But for the case it's a write stream, we need to apply all registered
 * filters now. The file is closed in the filter function and not here.
 **/
cdk_error_t
cdk_stream_close (cdk_stream_t s)
{
  struct stream_filter_s *f, *f2;
  cdk_error_t rc;
  
  if (!s)
    return CDK_Inv_Value;
  
  _cdk_log_debug ("close stream ref=%d `%s'\n", 
		  s->fp_ref, s->fname? s->fname : "[temp]");
  
  /* In the user callback mode, we call the release cb if possible
     and just free the stream. */
  if (s->cbs_hd)
    {
      if (s->cbs.release)
	rc = s->cbs.release (s->cbs_hd);
      else
	rc = 0;
      cdk_free (s);
      return rc;
    } 
    
  
  rc = 0;
  if (!s->flags.filtrated && !s->error)
    rc = cdk_stream_flush (s);
  if (!s->fp_ref && (s->fname || s->flags.temp))
    {      
      int err;
      
      _cdk_log_debug ("close stream fd=%d\n", fileno (s->fp));
      err = fclose (s->fp);
      s->fp = NULL;
      if (err)
	rc = CDK_File_Error;
    }
  
  /* Iterate over the filter list and use the cleanup flag to
     free the allocated internal structures. */
  f = s->filters;
  while (f)
    {
      f2 = f->next;
      if (f->fnct)
	f->fnct (f->opaque, STREAMCTL_FREE, NULL, NULL);
      cdk_free (f);
      f = f2;
    }
  
  if (s->fname)
    {
      cdk_free (s->fname);
      s->fname = NULL;
    }
  
  cdk_free (s->cache.buf);
  s->cache.alloced = 0;
  
  cdk_free (s);
  return rc;
}


/**
 * cdk_stream_eof: Return if the associated file handle was set to EOF.
 * @s: The STREAM object.
 *
 * This function will only work with read streams.
 **/
int
cdk_stream_eof (cdk_stream_t s)
{
  return s? s->flags.eof : -1;
}


const char*
_cdk_stream_get_fname (cdk_stream_t s)
{
  if (!s)
    return NULL;
  if (s->flags.temp)
    return NULL;
  return s->fname? s->fname : NULL;
}


/* Return the underlying FP of the stream.
   WARNING: This handle should not be closed. */
FILE*
_cdk_stream_get_fp (cdk_stream_t s)
{
  return s? s->fp : NULL;
}


int
_cdk_stream_get_errno (cdk_stream_t s)
{
  return s? s->error : CDK_Inv_Value;
}


/**
 * cdk_stream_get_length: Return the length of the associated file handle.
 * @s: The STREAM object.
 *
 * This function should work for both read and write streams. For write
 * streams an additional flush is used to write possible pending data.
 **/
off_t
cdk_stream_get_length (cdk_stream_t s)
{
  struct stat statbuf;
  cdk_error_t rc;
  
  if (!s)
    return (off_t)-1;
  
  /* The user callback does not support stat. */
  if (s->cbs_hd)
    return 0; 
  
  rc = stream_flush (s);
  if (rc)
    {
      s->error = rc;
      return (off_t)-1;
    }
  
  if (fstat (fileno (s->fp), &statbuf))
    {
      s->error = CDK_File_Error;
      return (off_t)-1;
    }
  
  return statbuf.st_size;
}


static struct stream_filter_s*
filter_add2 (cdk_stream_t s)
{
  struct stream_filter_s *f;
  
  assert (s);
  
  f = cdk_calloc (1, sizeof *f);
  if (!f)
    return NULL;
  f->next = s->filters;
  s->filters = f;
  return f;
}


static struct stream_filter_s *
filter_search (cdk_stream_t s, filter_fnct_t fnc)
{
  struct stream_filter_s * f;
  
  assert (s);
  
  for( f = s->filters; f; f = f->next ) 
    {
      if (f->fnct == fnc)
	return f;
    }
  
  return NULL;
}

static inline
void set_opaque( struct stream_filter_s* f)
{
  switch (f->type) 
    {    
    case fARMOR   : f->opaque = &f->u.afx; break;
    case fCIPHER  : f->opaque = &f->u.cfx; break;
    case fLITERAL : f->opaque = &f->u.pfx; break;
    case fCOMPRESS: f->opaque = &f->u.zfx; break;
    case fHASH    : f->opaque = &f->u.mfx; break;
    case fTEXT    : f->opaque = &f->u.tfx; break;
    default       : f->opaque = NULL;
    }

}

struct stream_filter_s*
filter_add (cdk_stream_t s, filter_fnct_t fnc, int type)
{
  struct stream_filter_s *f;
  
  assert (s);
    
  s->flags.filtrated = 0;
  f = filter_search (s, fnc);
  if (f)
    return f;
  f = filter_add2 (s);
  if (!f)
    return NULL;
  f->fnct = fnc;
  f->flags.enabled = 1;
  f->tmp = NULL;
  f->type = type;

  set_opaque(f);

  return f;
}

static int
stream_get_mode (cdk_stream_t s)
{
  assert (s);
  
  if (s->flags.temp)
    return s->fmode;
  return s->flags.write;
}


static filter_fnct_t
stream_id_to_filter (int type)
{
  switch (type) 
    {
    case fARMOR   : return _cdk_filter_armor;
    case fLITERAL : return _cdk_filter_literal;
    case fTEXT    : return _cdk_filter_text;
/*    case fCIPHER  : return _cdk_filter_cipher; */
/*    case fCOMPRESS: return _cdk_filter_compress; */
    default       : return NULL;
    }
}


/**
 * cdk_stream_filter_disable: 
 * @s: The STREAM object
 * @type: The numberic filter ID.
 *
 * Disables the filter with the type 'type'.
 **/
cdk_error_t
cdk_stream_filter_disable (cdk_stream_t s, int type)
{
  struct stream_filter_s *f;
  filter_fnct_t fnc;
  
  if (!s)
    return CDK_Inv_Value;
  
  fnc = stream_id_to_filter (type);
  if (!fnc)
    return CDK_Inv_Value;
  f = filter_search (s, fnc);
  if (f)
    f->flags.enabled = 0;
  return 0;
}


/* WARNING: tmp should not be closed by the caller. */
static cdk_error_t
stream_fp_replace (cdk_stream_t s, FILE **tmp)
{
  int rc;
  
  assert (s);
  
  _cdk_log_debug ("replace stream fd=%d with fd=%d\n", 
		  fileno (s->fp), fileno (*tmp));
  rc = fclose (s->fp);
  if (rc)
    return CDK_File_Error;
  s->fp = *tmp;
  *tmp = NULL;
  return 0;
}


/* This function is exactly like filter_read, except the fact that we can't
   use tmpfile () all the time. That's why we open the real file when there
   is no last filter. */
static cdk_error_t
stream_filter_write (cdk_stream_t s)
{
    struct stream_filter_s * f;
    cdk_error_t rc = 0;

    assert (s);
    
    if( s->flags.filtrated )
        return CDK_Inv_Value;

    for( f = s->filters; f; f = f->next ) 
    {
      if (!f->flags.enabled)
	continue;
      /* if there is no next filter, create the final output file */
      _cdk_log_debug( "filter [write]: last filter=%d fname=%s\n",
		      f->next? 1 : 0, s->fname );
      if (!f->next && s->fname)
	f->tmp = fopen (s->fname, "w+b");
      else
	f->tmp = my_tmpfile ();
      if (!f->tmp)
	{
	  rc = CDK_File_Error;
	  break;            
        }
      /* If there is no next filter, flush the cache. We also do this
       when the next filter is the armor filter because this filter
       is special and before it starts, all data should be written. */
      if( (!f->next || f->next->type == fARMOR) && s->cache.size ) 
	{
	  rc = stream_cache_flush (s, f->tmp);
	  if (rc)
	    break;
        }
      rc = f->fnct( f->opaque, f->ctl, s->fp, f->tmp );
      _cdk_log_debug ("filter [write]: type=%d rc=%d\n", f->type, rc);
      if (!rc)
	rc = stream_fp_replace (s, &f->tmp);
      if (!rc)
	rc = cdk_stream_seek (s, 0);
      if (rc)
	{
	  _cdk_log_debug ("filter [close]: fd=%d\n", fileno (f->tmp));
	  fclose (f->tmp);
	  break;
      }
    }
  return rc;
}


/* Here all data from the file handle is passed through all filters.
   The scheme works like this:
   Create a tempfile and use it for the output of the filter. Then the
   original file handle will be closed and replace with the temp handle.
   The file pointer will be set to the begin and the game starts again. */
static cdk_error_t
stream_filter_read (cdk_stream_t s)
{
  struct stream_filter_s *f;
  cdk_error_t rc = 0;

  assert (s);
  
  if (s->flags.filtrated)
    return 0;
  
  for (f = s->filters; f; f = f->next)
    {
      if (!f->flags.enabled)
	continue;
      if (f->flags.error)
	{
	  _cdk_log_debug ("filter %s [read]: has the error flag; skipped\n",
			  s->fname? s->fname: "[temp]");
	  continue;
	}
     
      f->tmp = my_tmpfile ();
      if (!f->tmp)
	{
	  rc = CDK_File_Error;
	  break;
        }
      rc = f->fnct (f->opaque, f->ctl, s->fp, f->tmp);
      _cdk_log_debug ("filter %s [read]: type=%d rc=%d\n",
		      s->fname? s->fname : "[temp]", f->type, rc);
      if (rc)
	{
	  f->flags.error = 1;
	  break;
	}     
      
      f->flags.error = 0;
      /* If the filter is read-only, do not replace the FP because
         the contents were not altered in any way. */
        if (!f->flags.rdonly)
	{
	  rc = stream_fp_replace (s, &f->tmp);
	  if (rc)
	    break;
        }
      else 
	{
	  fclose (f->tmp);
	  f->tmp = NULL;
        }
      rc = cdk_stream_seek (s, 0);
      if (rc)
	break;
      /* Disable the filter after it was successfully used. The idea
         is the following: let's say the armor filter was pushed and
         later more filters were added. The second time the filter code
         will be executed, only the new filter should be started but
         not the old because we already used it. */
      f->flags.enabled = 0;
    }
  
  return rc;
}


void*
_cdk_stream_get_opaque (cdk_stream_t s, int fid)
{
  struct stream_filter_s * f;
  
  if (!s)
    return NULL;
  
  for (f = s->filters; f; f = f->next)
    {
      if (f->type == fid)
	return f->opaque;
    }
  return NULL;
}


/**
 * cdk_stream_read: 
 * @s: The STREAM object.
 * @buf: The buffer to insert the readed bytes.
 * @count: Request so much bytes.
 *
 * Tries to read count bytes from the STREAM object.
 * When this function is called the first time, it can take a while
 * because all filters need to be processed. Please remember that you
 * need to add the filters in reserved order.
 **/
int
cdk_stream_read (cdk_stream_t s, void *buf, size_t buflen)
{
  int nread;
  int rc;
  
  if (!s)
    {
      s->error = CDK_Inv_Value;
      return EOF;
    }  
  
  if (s->cbs_hd)
    {
      if (s->cbs.read)
	return s->cbs.read (s->cbs_hd, buf, buflen);
      return 0;
    } 
    
  if (s->flags.write && !s->flags.temp)
    {
      s->error = CDK_Inv_Mode;
      return EOF; /* This is a write stream */
    }  
  
  if (!s->flags.no_filter && !s->cache.on && !s->flags.filtrated)
    {
      rc = stream_filter_read (s);
      if (rc) 
	{
	  s->error = rc;
	  if (feof (s->fp))
	    s->flags.eof = 1;
	  return EOF;
	}
      s->flags.filtrated = 1;
    }

  if (!buf && !buflen)
    return 0;

  nread = fread (buf, 1, buflen, s->fp);
  if (!nread)
    nread = EOF;

  if (feof (s->fp))
    {
      s->error = 0;
      s->flags.eof = 1;
    }  
  return nread;
}

      
int
cdk_stream_getc (cdk_stream_t s)
{
  unsigned char buf[2];
  int nread;
  
  if (!s)
    {
      s->error = CDK_Inv_Value;
      return EOF;
    }  
  nread = cdk_stream_read (s, buf, 1);
  if (nread == EOF) 
    {
      s->error = CDK_File_Error;
      return EOF;
    }
  return buf[0];
}


/**
 * cdk_stream_write: 
 * @s: The STREAM object
 * @buf: The buffer with the values to write.
 * @count: The size of the buffer.
 *
 * Tries to write count bytes into the stream.
 * In this function we simply write the bytes to the stream. We can't
 * use the filters here because it would mean they have to support
 * partial flushing.
 **/
int
cdk_stream_write (cdk_stream_t s, const void * buf, size_t count)
{
  int nwritten;

  if (!s)
    {
      s->error = CDK_Inv_Value;
      return EOF;
    }  
  
  if (s->cbs_hd)
    {
      if (s->cbs.write)
	return s->cbs.write (s->cbs_hd, buf, count);
      return 0;
    }  
  
  if (!s->flags.write)
    {
      s->error = CDK_Inv_Mode; /* this is a read stream */
      return EOF;
    } 
  
  if (!buf && !count)
    return stream_flush (s);
  
  if (s->cache.on)
    {
      /* We need to resize the buffer if the additional data wouldn't
         fit into it. We allocate more memory to avoid to resize it the
         next time the function is used. */
      if (s->cache.size + count > s->cache.alloced)
	{
	  byte *old = s->cache.buf;
	  
	  s->cache.buf = cdk_calloc (1, s->cache.alloced+count+STREAM_BUFSIZE);
	  s->cache.alloced += (count + STREAM_BUFSIZE);
	  memcpy (s->cache.buf, old, s->cache.size);
	  cdk_free (old);
	  _cdk_log_debug ("stream: enlarge cache to %d octets\n", 
			  s->cache.alloced);
	}      
      memcpy (s->cache.buf + s->cache.size, buf, count);
      s->cache.size += count;
      return count;
    }
  
  nwritten = fwrite (buf, 1, count, s->fp);
  if (!nwritten)
    nwritten = EOF;  
  return nwritten;
}


int
cdk_stream_putc (cdk_stream_t s, int c)
{
  byte buf[2];
  int nwritten;
  
  if (!s)
    {
      s->error = CDK_Inv_Value;
      return EOF;
    }  
  buf[0] = c;
  nwritten = cdk_stream_write (s, buf, 1);
  if (nwritten == EOF) 
    return EOF;
  return 0;
}


off_t
cdk_stream_tell (cdk_stream_t s)
{  
  return s? ftell (s->fp): (off_t)-1;
}


cdk_error_t
cdk_stream_seek (cdk_stream_t s, off_t offset)
{
  off_t len;
  
  if (!s)
    return CDK_Inv_Value;
  
  if (s->cbs_hd)
    {
      if (s->cbs.seek)
	return s->cbs.seek (s->cbs_hd, offset);
      return 0;
    }  
  
  /* Set or reset the EOF flag. */
  len = cdk_stream_get_length (s);
  if (len == offset)
    s->flags.eof = 1;
  else
    s->flags.eof = 0;
  
  if (fseek (s->fp, offset, SEEK_SET))
    return CDK_File_Error;
  return 0;
}


static cdk_error_t
stream_flush (cdk_stream_t s)
{
  assert (s);
  
  /* For some constellations it cannot be assured that the
     return value is defined, thus we ignore it for now. */
  (void)fflush (s->fp);
  return 0;
}


/**
 * cdk_stream_set_armor_flag:
 * @s: the stream object
 * @type: the type of armor to use
 * 
 * If the file is in read-mode, no armor type needs to be
 * defined (armor_type=0) because the armor filter will be
 * used for decoding existing armor data.
 * For the write mode, @armor_type can be set to any valid
 * armor type (message, key, sig).
 **/
cdk_error_t
cdk_stream_set_armor_flag (cdk_stream_t s, int armor_type)
{
  struct stream_filter_s *f;

  if (!s)
    return CDK_Inv_Value;
  f = filter_add (s, _cdk_filter_armor, fARMOR);
  if (!f)
    return CDK_Out_Of_Core;
  f->u.afx.idx = f->u.afx.idx2 = armor_type;
  f->ctl = stream_get_mode (s);
  return 0;
}


/**
 * cdk_stream_set_literal_flag:
 * @s: the stream object
 * @mode: the mode to use (binary, text, unicode)
 * @fname: the file name to store in the packet.
 *
 * In read mode it kicks off the literal decoding routine to
 * unwrap the data from the packet. The @mode parameter is ignored.
 * In write mode the function can be used to wrap the stream data
 * into a literal packet with the given mode and file name.
 **/
cdk_error_t
cdk_stream_set_literal_flag (cdk_stream_t s, cdk_lit_format_t mode, 
			     const char *fname)
{
  struct stream_filter_s *f;
  const char *orig_fname;
  
  _cdk_log_debug ("stream: enable literal mode.\n");
  
  if (!s)
    return CDK_Inv_Value;

  orig_fname = _cdk_stream_get_fname (s);
  f = filter_add (s, _cdk_filter_literal, fLITERAL);
  if (!f)
    return CDK_Out_Of_Core;
  f->u.pfx.mode = mode;
  f->u.pfx.filename = fname? cdk_strdup (fname) : NULL;
  f->u.pfx.orig_filename = orig_fname? cdk_strdup (orig_fname): NULL;
  f->ctl = stream_get_mode (s);
  if (s->blkmode > 0)
    {
      f->u.pfx.blkmode.on = 1;
      f->u.pfx.blkmode.size = s->blkmode;
    }
  return 0;
}


/**
 * cdk_stream_set_cipher_flag:
 * @s: the stream object
 * @dek: the data encryption key
 * @use_mdc: 1 means to use the MDC mode
 * 
 * In read mode it kicks off the cipher filter to decrypt the data
 * from the stream with the key given in @dek.
 * In write mode the stream data will be encrypted with the DEK object
 * and optionally, the @use_mdc parameter can be used to enable the MDC mode.
 **/
cdk_error_t
cdk_stream_set_cipher_flag (cdk_stream_t s, cdk_dek_t dek, int use_mdc)
{
  
  _cdk_log_debug ("stream: enable cipher mode\n");
  if (!s)
    return CDK_Inv_Value;

#if 0
  struct stream_filter_s * f;

  f = filter_add (s, _cdk_filter_cipher, fCIPHER);
  if (!f)
    return CDK_Out_Of_Core;
  dek->use_mdc = use_mdc;
  f->ctl = stream_get_mode (s);
  f->u.cfx.dek = dek;
  f->u.cfx.mdc_method = use_mdc? GCRY_MD_SHA1 : 0;
  if (s->blkmode > 0)
    {
      f->u.cfx.blkmode.on = 1;
      f->u.cfx.blkmode.size = s->blkmode;
    }
  return 0;
#endif

  return CDK_Not_Implemented;
}


/**
 * cdk_stream_set_compress_flag:
 * @s: the stream object
 * @algo: the compression algo
 * @level: level of compression (0..9)
 * 
 * In read mode it kicks off the decompression filter to retrieve
 * the uncompressed data.
 * In write mode the stream data will be compressed with the
 * given algorithm at the given level.
 **/
cdk_error_t
cdk_stream_set_compress_flag (cdk_stream_t s, int algo, int level)
{
  
  return CDK_Not_Implemented;

#if 0
  struct stream_filter_s *f;

  if (!s)
    return CDK_Inv_Value;
  f = filter_add (s, _cdk_filter_compress, fCOMPRESS);
  if (!f)
    return CDK_Out_Of_Core;
  f->ctl = stream_get_mode (s);
  f->u.zfx.algo = algo;
  f->u.zfx.level = level;
  return 0;
#endif
}


/**
 * cdk_stream_set_text_flag:
 * @s: the stream object
 * @lf: line ending
 * 
 * Pushes the text filter to store the stream data in cannoncial format.
 **/
cdk_error_t
cdk_stream_set_text_flag (cdk_stream_t s, const char *lf)
{
  struct stream_filter_s *f;
  
  if (!s)
    return CDK_Inv_Value;
  f = filter_add (s, _cdk_filter_text, fTEXT);
  if (!f)
    return CDK_Out_Of_Core;
  f->ctl = stream_get_mode (s);
  f->u.tfx.lf = lf;
  return 0;
}


/**
 * cdk_stream_set_hash_flag:
 * @s: the stream object
 * @digest_algo: the digest algorithm to use
 * 
 * This is for read-only streams. It pushes a digest filter to
 * calculate the digest of the given stream data.
 **/
cdk_error_t
cdk_stream_set_hash_flag (cdk_stream_t s, int digest_algo)
{
  struct stream_filter_s *f;
  
  if (!s)
    return CDK_Inv_Value;    
  if (stream_get_mode (s))
    return CDK_Inv_Mode;
  f = filter_add (s, _cdk_filter_hash, fHASH);
  if (!f)
    return CDK_Out_Of_Core;
  f->ctl = stream_get_mode (s);
  f->u.mfx.digest_algo = digest_algo;
  f->flags.rdonly = 1;
  return 0;
}


/**
 * cdk_stream_enable_cache:
 * @s: the stream object
 * @val: 1=on, 0=off
 *
 * Enables or disable the cache section of a stream object.
 **/
cdk_error_t
cdk_stream_enable_cache (cdk_stream_t s, int val)
{
  if (!s)
    return CDK_Inv_Value;
  if (!s->flags.write)
    return CDK_Inv_Mode;
  s->cache.on = val;
  if (!s->cache.buf)
    {      
      s->cache.buf = cdk_calloc (1, STREAM_BUFSIZE);
      s->cache.alloced = STREAM_BUFSIZE;
      _cdk_log_debug ("stream: allocate cache of %d octets\n", STREAM_BUFSIZE);
    }  
  return 0;
}


static int
stream_cache_flush (cdk_stream_t s, FILE * fp)
{
  int nwritten;
  
  assert (s);
  
  /* FIXME: We should find a way to use cdk_stream_write here. */
  if (s->cache.size > 0)
    {
      nwritten = fwrite (s->cache.buf, 1, s->cache.size, fp);
      if (!nwritten)
	return CDK_File_Error;
      s->cache.size = 0;
      s->cache.on = 0;
      wipemem (s->cache.buf, s->cache.alloced);
    }
  return 0;
}


/**
 * cdk_stream_kick_off:
 * @inp: the input stream
 * @out: the output stream.
 * 
 * Passes the entire data from @inp into the output stream @out
 * with all the activated filters.
 */
cdk_error_t
cdk_stream_kick_off (cdk_stream_t inp, cdk_stream_t out)
{
  byte buf[BUFSIZE];
  int nread, nwritten;
  cdk_error_t rc;

  if (!inp || !out)
    return CDK_Inv_Value;
  rc = CDK_Success;
  while (!cdk_stream_eof (inp)) 
    {
      nread = cdk_stream_read (inp, buf, DIM (buf));
      if (!nread || nread == EOF)
	break;
      nwritten = cdk_stream_write (out, buf, nread);
      if (!nwritten || nwritten == EOF)
	{ /* In case of errors, we leave the loop. */
	  rc = inp->error;
	  break;
	}
    }
  
  wipemem (buf, sizeof (buf));
  return rc;
}


/**
 * cdk_stream_mmap_part:
 * @s: the stream
 * @off: the offset where to start
 * @len: how much bytes shall be mapped
 * @ret_buf: the buffer to store the content
 * @ret_buflen: length of the buffer
 *
 * Maps the data of the given stream into a memory section. @ret_count
 * contains the length of the buffer.
 **/
cdk_error_t
cdk_stream_mmap_part (cdk_stream_t s, off_t off, size_t len,
		      byte **ret_buf, size_t *ret_buflen)
{
  cdk_error_t rc;
  off_t oldpos;
  unsigned int n;  
  
  if (!ret_buf || !ret_buflen)
    return CDK_Inv_Value;
  *ret_buf = NULL;
  *ret_buflen = 0;
  
  if (!s)
    return CDK_Inv_Value;
  
  /* Memory mapping is not supported on custom I/O objects. */
  if (s->cbs_hd)
    {
      _cdk_log_debug ("cdk_stream_mmap_part: not supported on callbacks\n");
      return CDK_Inv_Mode;
    }  
  
  oldpos = cdk_stream_tell (s);
  rc = cdk_stream_flush (s);
  if (rc)
    return rc;
  rc = cdk_stream_seek (s, off);
  if (rc)
    return rc;
  if (!len)
    len = cdk_stream_get_length (s);
  if (!len)
    {
      _cdk_log_debug ("cdk_stream_mmap_part: invalid file size %lu\n", len);
      return s->error;
    }
  if (len > MAX_MAP_SIZE)
    return CDK_Too_Short;
  
  *ret_buf = cdk_calloc (1, len+1);
  *ret_buflen = len;
  n = cdk_stream_read (s, *ret_buf, len);
  if (n != len)
    *ret_buflen = n;
  rc = cdk_stream_seek (s, oldpos);
  return rc;
}


cdk_error_t
cdk_stream_mmap (cdk_stream_t inp, byte **buf, size_t *buflen)
{
  off_t len;
  
  /* We need to make sure all data is flushed before we retrieve the size. */
  cdk_stream_flush (inp);
  len = cdk_stream_get_length (inp);
  return cdk_stream_mmap_part (inp, 0, len, buf, buflen);
}


/**
 * cdk_stream_peek:
 * @inp: the input stream handle
 * @s: buffer
 * @count: number of bytes to peek
 *
 * The function acts like cdk_stream_read with the difference that
 * the file pointer is moved to the old position after the bytes were read.
 **/
int
cdk_stream_peek (cdk_stream_t inp, byte *buf, size_t buflen)
{
  off_t off;
  int nbytes;
  
  if (!inp || !buf)
    return 0;
  if (inp->cbs_hd)
    return 0;
  
  off = cdk_stream_tell (inp);
  nbytes = cdk_stream_read (inp, buf, buflen);
  if (nbytes == -1)
    return 0;  
  if (cdk_stream_seek (inp, off))
    return 0;
  return nbytes;
}


/* Try to read a line from the given stream. */
int
_cdk_stream_gets (cdk_stream_t s, char * buf, size_t count)
{
  int c, i;
  
  assert (s);
  
  i = 0;
  while (!cdk_stream_eof (s) && count > 0)
    {
      c = cdk_stream_getc (s);
      if (c == EOF || c == '\r' || c == '\n' ) 
	{
	  buf[i++] = '\0';
	  break;
	}
      buf[i++] = c;
      count--;
    }
  return i;
}


/* Try to write string into the stream @s. */
int
_cdk_stream_puts (cdk_stream_t s, const char *buf)
{
  return cdk_stream_write (s, buf, strlen (buf));
}


/* Activate the block mode for the given stream. */
cdk_error_t
_cdk_stream_set_blockmode (cdk_stream_t s, size_t nbytes)
{
  assert (s);
  
  _cdk_log_debug ("stream: activate block mode with blocksize %d\n", nbytes);
  s->blkmode = nbytes;  
  return 0;
}


/* Return the block mode state of the given stream. */
int
_cdk_stream_get_blockmode (cdk_stream_t s)
{
  return s? s->blkmode : 0;
}