summaryrefslogtreecommitdiff
path: root/src/warc.c
blob: 5bdda1b5423be819f06d46d5518d1d8d32cd6fdf (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
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
/* Utility functions for writing WARC files.
   Copyright (C) 2011, 2012 Free Software Foundation, Inc.

This file is part of GNU Wget.

GNU Wget 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.

GNU Wget 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 Wget.  If not, see <http://www.gnu.org/licenses/>.

Additional permission under GNU GPL version 3 section 7

If you modify this program, or any covered work, by linking or
combining it with the OpenSSL project's OpenSSL library (or a
modified version of that library), containing parts covered by the
terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
grants you additional permission to convey the resulting work.
Corresponding Source for a non-source form of such a combination
shall include the source code for the parts of OpenSSL used as well
as that of the covered work.  */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include "wget.h"
#include "hash.h"
#include "utils.h"
#include "version.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <tmpdir.h>
#include <sha1.h>
#include <base32.h>
#include <unistd.h>
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif

#ifdef HAVE_LIBUUID
#include <uuid/uuid.h>
#elif HAVE_UUID_CREATE
#include <uuid.h>
#endif

#ifndef WINDOWS
#include <libgen.h>
#else
#include <fcntl.h>
#endif

#include "warc.h"
#include "exits.h"

#ifndef O_TEMPORARY
#define O_TEMPORARY 0
#endif


/* The log file (a temporary file that contains a copy
   of the wget log). */
static FILE *warc_log_fp;

/* The manifest file (a temporary file that contains the
   warcinfo uuid of every file in this crawl). */
static FILE *warc_manifest_fp;

/* The current WARC file (or NULL, if WARC is disabled). */
static FILE *warc_current_file;

#ifdef HAVE_LIBZ
/* The gzip stream for the current WARC file
   (or NULL, if WARC or gzip is disabled). */
static gzFile warc_current_gzfile;

/* The offset of the current gzip record in the WARC file. */
static off_t warc_current_gzfile_offset;

/* The uncompressed size (so far) of the current record. */
static off_t warc_current_gzfile_uncompressed_size;
# endif

/* This is true until a warc_write_* method fails. */
static bool warc_write_ok;

/* The current CDX file (or NULL, if CDX is disabled). */
static FILE *warc_current_cdx_file;

/* The record id of the warcinfo record of the current WARC file.  */
static char *warc_current_warcinfo_uuid_str;

/* The file name of the current WARC file. */
static char *warc_current_filename;

/* The serial number of the current WARC file.  This number is
   incremented each time a new file is opened and is used in the
   WARC file's filename. */
static int warc_current_file_number;

/* The table of CDX records, if deduplication is enabled. */
static struct hash_table * warc_cdx_dedup_table;

static bool warc_start_new_file (bool meta);


struct warc_cdx_record
{
  char *url;
  char *uuid;
  char digest[SHA1_DIGEST_SIZE];
};

static unsigned long
warc_hash_sha1_digest (const void *key)
{
  /* We just use some of the first bytes of the digest. */
  unsigned long v = 0;
  memcpy (&v, key, sizeof (unsigned long));
  return v;
}

static int
warc_cmp_sha1_digest (const void *digest1, const void *digest2)
{
  return !memcmp (digest1, digest2, SHA1_DIGEST_SIZE);
}



/* Writes SIZE bytes from BUFFER to the current WARC file,
   through gzwrite if compression is enabled.
   Returns the number of uncompressed bytes written.  */
static size_t
warc_write_buffer (const char *buffer, size_t size)
{
#ifdef HAVE_LIBZ
  if (warc_current_gzfile)
    {
      warc_current_gzfile_uncompressed_size += size;
      return gzwrite (warc_current_gzfile, buffer, size);
    }
  else
#endif
    return fwrite (buffer, 1, size, warc_current_file);
}

/* Writes STR to the current WARC file.
   Returns false and set warc_write_ok to false if there
   is an error.  */
static bool
warc_write_string (const char *str)
{
  size_t n;

  if (!warc_write_ok)
    return false;

  n = strlen (str);
  if (n != warc_write_buffer (str, n))
    warc_write_ok = false;

  return warc_write_ok;
}


#define EXTRA_GZIP_HEADER_SIZE 14
#define GZIP_STATIC_HEADER_SIZE  10
#define FLG_FEXTRA          0x04
#define OFF_FLG             3

/* Starts a new WARC record.  Writes the version header.
   If opt.warc_maxsize is set and the current file is becoming
   too large, this will open a new WARC file.

   If compression is enabled, this will start a new
   gzip stream in the current WARC file.

   Returns false and set warc_write_ok to false if there
   is an error.  */
static bool
warc_write_start_record (void)
{
  if (!warc_write_ok)
    return false;

  fflush (warc_current_file);
  if (opt.warc_maxsize > 0 && ftello (warc_current_file) >= opt.warc_maxsize)
    warc_start_new_file (false);

#ifdef HAVE_LIBZ
  /* Start a GZIP stream, if required. */
  if (opt.warc_compression_enabled)
    {
      /* Record the starting offset of the new record. */
      warc_current_gzfile_offset = ftello (warc_current_file);

      /* Reserve space for the extra GZIP header field.
         In warc_write_end_record we will fill this space
         with information about the uncompressed and
         compressed size of the record. */
      fseek (warc_current_file, EXTRA_GZIP_HEADER_SIZE, SEEK_CUR);
      fflush (warc_current_file);

      /* Start a new GZIP stream. */
      warc_current_gzfile = gzdopen (dup (fileno (warc_current_file)), "wb9");
      warc_current_gzfile_uncompressed_size = 0;

      if (warc_current_gzfile == NULL)
        {
          logprintf (LOG_NOTQUIET,
_("Error opening GZIP stream to WARC file.\n"));
          warc_write_ok = false;
          return false;
        }
    }
#endif

  warc_write_string ("WARC/1.0\r\n");
  return warc_write_ok;
}

/* Writes a WARC header to the current WARC record.
   This method may be run after warc_write_start_record and
   before warc_write_block_from_file.  */
static bool
warc_write_header (const char *name, const char *value)
{
  if (value)
    {
      warc_write_string (name);
      warc_write_string (": ");
      warc_write_string (value);
      warc_write_string ("\r\n");
    }
  return warc_write_ok;
}

/* Copies the contents of DATA_IN to the WARC record.
   Adds a Content-Length header to the WARC record.
   Run this method after warc_write_header,
   then run warc_write_end_record. */
static bool
warc_write_block_from_file (FILE *data_in)
{
  /* Add the Content-Length header. */
  char content_length[MAX_INT_TO_STRING_LEN(off_t)];
  char buffer[BUFSIZ];
  size_t s;

  fseeko (data_in, 0L, SEEK_END);
  number_to_string (content_length, ftello (data_in));
  warc_write_header ("Content-Length", content_length);

  /* End of the WARC header section. */
  warc_write_string ("\r\n");

  if (fseeko (data_in, 0L, SEEK_SET) != 0)
    warc_write_ok = false;

  /* Copy the data in the file to the WARC record. */
  while (warc_write_ok && (s = fread (buffer, 1, BUFSIZ, data_in)) > 0)
    {
      if (warc_write_buffer (buffer, s) < s)
        warc_write_ok = false;
    }

  return warc_write_ok;
}

/* Run this method to close the current WARC record.

   If compression is enabled, this method closes the
   current GZIP stream and fills the extra GZIP header
   with the uncompressed and compressed length of the
   record. */
static bool
warc_write_end_record (void)
{
  warc_write_buffer ("\r\n\r\n", 4);

#ifdef HAVE_LIBZ
  /* We start a new gzip stream for each record.  */
  if (warc_write_ok && warc_current_gzfile)
    {
      char extra_header[EXTRA_GZIP_HEADER_SIZE];
      char static_header[GZIP_STATIC_HEADER_SIZE];
      off_t current_offset, uncompressed_size, compressed_size;
      size_t result;

      if (gzclose (warc_current_gzfile) != Z_OK)
        {
          warc_write_ok = false;
          return false;
        }

      fflush (warc_current_file);
      fseeko (warc_current_file, 0, SEEK_END);

      /* The WARC standard suggests that we add 'skip length' data in the
         extra header field of the GZIP stream.

         In warc_write_start_record we reserved space for this extra header.
         This extra space starts at warc_current_gzfile_offset and fills
         EXTRA_GZIP_HEADER_SIZE bytes.  The static GZIP header starts at
         warc_current_gzfile_offset + EXTRA_GZIP_HEADER_SIZE.

         We need to do three things:
         1. Move the static GZIP header to warc_current_gzfile_offset;
         2. Set the FEXTRA flag in the GZIP header;
         3. Write the extra GZIP header after the static header, that is,
            starting at warc_current_gzfile_offset + GZIP_STATIC_HEADER_SIZE.
      */

      /* Calculate the uncompressed and compressed sizes. */
      current_offset = ftello (warc_current_file);
      uncompressed_size = current_offset - warc_current_gzfile_offset;
      compressed_size = warc_current_gzfile_uncompressed_size;

      /* Go back to the static GZIP header. */
      fseeko (warc_current_file, warc_current_gzfile_offset
              + EXTRA_GZIP_HEADER_SIZE, SEEK_SET);

      /* Read the header. */
      result = fread (static_header, 1, GZIP_STATIC_HEADER_SIZE,
                             warc_current_file);
      if (result != GZIP_STATIC_HEADER_SIZE)
        {
          warc_write_ok = false;
          return false;
        }

      /* Set the FEXTRA flag in the flags byte of the header. */
      static_header[OFF_FLG] = static_header[OFF_FLG] | FLG_FEXTRA;

      /* Write the header back to the file, but starting at
         warc_current_gzfile_offset. */
      fseeko (warc_current_file, warc_current_gzfile_offset, SEEK_SET);
      fwrite (static_header, 1, GZIP_STATIC_HEADER_SIZE, warc_current_file);

      /* Prepare the extra GZIP header. */
      /* XLEN, the length of the extra header fields.  */
      extra_header[0]  = ((EXTRA_GZIP_HEADER_SIZE - 2) & 255);
      extra_header[1]  = ((EXTRA_GZIP_HEADER_SIZE - 2) >> 8) & 255;
      /* The extra header field identifier for the WARC skip length. */
      extra_header[2]  = 's';
      extra_header[3]  = 'l';
      /* The size of the field value (8 bytes).  */
      extra_header[4]  = (8 & 255);
      extra_header[5]  = ((8 >> 8) & 255);
      /* The size of the uncompressed record.  */
      extra_header[6]  = (uncompressed_size & 255);
      extra_header[7]  = (uncompressed_size >> 8) & 255;
      extra_header[8]  = (uncompressed_size >> 16) & 255;
      extra_header[9]  = (uncompressed_size >> 24) & 255;
      /* The size of the compressed record.  */
      extra_header[10] = (compressed_size & 255);
      extra_header[11] = (compressed_size >> 8) & 255;
      extra_header[12] = (compressed_size >> 16) & 255;
      extra_header[13] = (compressed_size >> 24) & 255;

      /* Write the extra header after the static header. */
      fseeko (warc_current_file, warc_current_gzfile_offset
              + GZIP_STATIC_HEADER_SIZE, SEEK_SET);
      fwrite (extra_header, 1, EXTRA_GZIP_HEADER_SIZE, warc_current_file);

      /* Done, move back to the end of the file. */
      fflush (warc_current_file);
      fseeko (warc_current_file, 0, SEEK_END);
    }
#endif /* HAVE_LIBZ */

  return warc_write_ok;
}


/* Writes the WARC-Date header for the given timestamp to
   the current WARC record.
   If timestamp is NULL, the current time will be used.  */
static bool
warc_write_date_header (const char *timestamp)
{
  char current_timestamp[21];

  return warc_write_header ("WARC-Date", timestamp ? timestamp :
                            warc_timestamp (current_timestamp, sizeof(current_timestamp)));
}

/* Writes the WARC-IP-Address header for the given IP to
   the current WARC record.  If IP is NULL, no header will
   be written.  */
static bool
warc_write_ip_header (ip_address *ip)
{
  if (ip != NULL)
    return warc_write_header ("WARC-IP-Address", print_address (ip));
  else
    return warc_write_ok;
}


/* warc_sha1_stream_with_payload is a modified copy of sha1_stream
   from gnulib/sha1.c.  This version calculates two digests in one go.

   Compute SHA1 message digests for bytes read from STREAM.  The
   digest of the complete file will be written into the 16 bytes
   beginning at RES_BLOCK.

   If payload_offset >= 0, a second digest will be calculated of the
   portion of the file starting at payload_offset and continuing to
   the end of the file.  The digest number will be written into the
   16 bytes beginning ad RES_PAYLOAD.  */
static int
warc_sha1_stream_with_payload (FILE *stream, void *res_block, void *res_payload,
                               off_t payload_offset)
{
#define BLOCKSIZE 32768

  struct sha1_ctx ctx_block;
  struct sha1_ctx ctx_payload;
  off_t pos;
  off_t sum;

  char *buffer = malloc (BLOCKSIZE + 72);
  if (!buffer)
    return 1;

  /* Initialize the computation context.  */
  sha1_init_ctx (&ctx_block);
  if (payload_offset >= 0)
    sha1_init_ctx (&ctx_payload);

  pos = 0;

  /* Iterate over full file contents.  */
  while (1)
    {
      /* We read the file in blocks of BLOCKSIZE bytes.  One call of the
         computation function processes the whole buffer so that with the
         next round of the loop another block can be read.  */
      off_t n;
      sum = 0;

      /* Read block.  Take care for partial reads.  */
      while (1)
        {
          n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);

          sum += n;
          pos += n;

          if (sum == BLOCKSIZE)
            break;

          if (n == 0)
            {
              /* Check for the error flag IFF N == 0, so that we don't
                 exit the loop after a partial read due to e.g., EAGAIN
                 or EWOULDBLOCK.  */
              if (ferror (stream))
                {
                  xfree (buffer);
                  return 1;
                }
              goto process_partial_block;
            }

          /* We've read at least one byte, so ignore errors.  But always
             check for EOF, since feof may be true even though N > 0.
             Otherwise, we could end up calling fread after EOF.  */
          if (feof (stream))
            goto process_partial_block;
        }

      /* Process buffer with BLOCKSIZE bytes.  Note that
                        BLOCKSIZE % 64 == 0
       */
      sha1_process_block (buffer, BLOCKSIZE, &ctx_block);
      if (payload_offset >= 0 && payload_offset < pos)
        {
          /* At least part of the buffer contains data from payload. */
          off_t start_of_payload = payload_offset - (pos - BLOCKSIZE);
          if (start_of_payload <= 0)
            /* All bytes in the buffer belong to the payload. */
            start_of_payload = 0;

          /* Process the payload part of the buffer.
             Note: we can't use  sha1_process_block  here even if we
             process the complete buffer.  Because the payload doesn't
             have to start with a full block, there may still be some
             bytes left from the previous buffer.  Therefore, we need
             to continue with  sha1_process_bytes.  */
          sha1_process_bytes (buffer + start_of_payload,
                              BLOCKSIZE - start_of_payload, &ctx_payload);
        }
    }

 process_partial_block:;

  /* Process any remaining bytes.  */
  if (sum > 0)
    {
      sha1_process_bytes (buffer, sum, &ctx_block);
      if (payload_offset >= 0 && payload_offset < pos)
        {
          /* At least part of the buffer contains data from payload. */
          off_t start_of_payload = payload_offset - (pos - sum);
          if (start_of_payload <= 0)
            /* All bytes in the buffer belong to the payload. */
            start_of_payload = 0;

          /* Process the payload part of the buffer. */
          sha1_process_bytes (buffer + start_of_payload,
                              sum - start_of_payload, &ctx_payload);
        }
    }

  /* Construct result in desired memory.  */
  sha1_finish_ctx (&ctx_block,   res_block);
  if (payload_offset >= 0)
    sha1_finish_ctx (&ctx_payload, res_payload);
  xfree (buffer);
  return 0;

#undef BLOCKSIZE
}

/* Converts the SHA1 digest to a base32-encoded string.
   "sha1:DIGEST\0"  (Allocates a new string for the response.)  */
static char *
warc_base32_sha1_digest (char *sha1_digest)
{
  /* length: "sha1:" + digest + "\0" */
  char *sha1_base32 = malloc (BASE32_LENGTH(SHA1_DIGEST_SIZE) + 1 + 5 );
  base32_encode (sha1_digest, SHA1_DIGEST_SIZE, sha1_base32 + 5,
                 BASE32_LENGTH(SHA1_DIGEST_SIZE) + 1);
  memcpy (sha1_base32, "sha1:", 5);
  sha1_base32[BASE32_LENGTH(SHA1_DIGEST_SIZE) + 5] = '\0';
  return sha1_base32;
}


/* Sets the digest headers of the record.
   This method will calculate the block digest and, if payload_offset >= 0,
   will also calculate the payload digest of the payload starting at the
   provided offset.  */
static void
warc_write_digest_headers (FILE *file, long payload_offset)
{
  if (opt.warc_digests_enabled)
    {
      /* Calculate the block and payload digests. */
      char sha1_res_block[SHA1_DIGEST_SIZE];
      char sha1_res_payload[SHA1_DIGEST_SIZE];

      rewind (file);
      if (warc_sha1_stream_with_payload (file, sha1_res_block,
          sha1_res_payload, payload_offset) == 0)
        {
          char *digest;

          digest = warc_base32_sha1_digest (sha1_res_block);
          warc_write_header ("WARC-Block-Digest", digest);
          xfree (digest);

          if (payload_offset >= 0)
            {
              digest = warc_base32_sha1_digest (sha1_res_payload);
              warc_write_header ("WARC-Payload-Digest", digest);
              xfree (digest);
            }
        }
    }
}


/* Fills timestamp with the current time and date.
   The UTC time is formatted following ISO 8601, as required
   for use in the WARC-Date header.
   The timestamp will be 21 characters long. */
char *
warc_timestamp (char *timestamp, size_t timestamp_size)
{
  time_t rawtime = time (NULL);
  struct tm * timeinfo = gmtime (&rawtime);

  if (strftime (timestamp, timestamp_size, "%Y-%m-%dT%H:%M:%SZ", timeinfo) == 0 && timestamp_size > 0)
    *timestamp = 0;

  return timestamp;
}

#if HAVE_LIBUUID || HAVE_UUID_CREATE
/* Fills urn_str with a UUID in the format required
   for the WARC-Record-Id header.
   The string will be 47 characters long. */
void
warc_uuid_str (char *urn_str)
{
  char uuid_str[37];

  uuid_t record_id;
#if HAVE_UUID_CREATE
  uuid_create (&record_id, NULL);
  uuid_to_string (&record_id, &uuid_str, NULL);
#else
  uuid_generate (record_id);
  uuid_unparse (record_id, uuid_str);
#endif

  sprintf (urn_str, "<urn:uuid:%s>", uuid_str);
}
#else
/* Fills urn_str with a UUID based on random numbers in the format
   required for the WARC-Record-Id header.
   (See RFC 4122, UUID version 4.)

   Note: this is a fallback method, it is much better to use the
   methods provided by libuuid.

   The string will be 47 characters long. */
void
warc_uuid_str (char *urn_str)
{
  /* RFC 4122, a version 4 UUID with only random numbers */

  unsigned char uuid_data[16];
  int i;
  for (i=0; i<16; i++)
    uuid_data[i] = random_number (255);

  /* Set the four most significant bits (bits 12 through 15) of the
	*  time_hi_and_version field to the 4-bit version number */
  uuid_data[6] = (uuid_data[6] & 0x0F) | 0x40;

  /* Set the two most significant bits (bits 6 and 7) of the
	*  clock_seq_hi_and_reserved to zero and one, respectively. */
  uuid_data[8] = (uuid_data[8] & 0xBF) | 0x80;

  sprintf (urn_str,
    "<urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x>",
    uuid_data[0], uuid_data[1], uuid_data[2], uuid_data[3], uuid_data[4],
    uuid_data[5], uuid_data[6], uuid_data[7], uuid_data[8], uuid_data[9],
    uuid_data[10], uuid_data[11], uuid_data[12], uuid_data[13], uuid_data[14],
    uuid_data[15]);
}
#endif

/* Write a warcinfo record to the current file.
   Updates warc_current_warcinfo_uuid_str. */
static bool
warc_write_warcinfo_record (char *filename)
{
  FILE *warc_tmp;
  char timestamp[22];
  char *filename_copy, *filename_basename;

  /* Write warc-info record as the first record of the file. */
  /* We add the record id of this info record to the other records in the
     file. */
  warc_current_warcinfo_uuid_str = (char *) malloc (48);
  warc_uuid_str (warc_current_warcinfo_uuid_str);

  warc_timestamp (timestamp, sizeof(timestamp));

  filename_copy = strdup (filename);
  filename_basename = strdup (basename (filename_copy));

  warc_write_start_record ();
  warc_write_header ("WARC-Type", "warcinfo");
  warc_write_header ("Content-Type", "application/warc-fields");
  warc_write_header ("WARC-Date", timestamp);
  warc_write_header ("WARC-Record-ID", warc_current_warcinfo_uuid_str);
  warc_write_header ("WARC-Filename", filename_basename);

  /* Create content.  */
  warc_tmp = warc_tempfile ();
  if (warc_tmp == NULL)
    {
      xfree (filename_copy);
      xfree (filename_basename);
      return false;
    }

  fprintf (warc_tmp, "software: Wget/%s (%s)\r\n", version_string, OS_TYPE);
  fprintf (warc_tmp, "format: WARC File Format 1.0\r\n");
  fprintf (warc_tmp,
"conformsTo: http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf\r\n");
  fprintf (warc_tmp, "robots: %s\r\n", (opt.use_robots ? "classic" : "off"));
  fprintf (warc_tmp, "wget-arguments: %s\r\n", program_argstring);
  /* Add the user headers, if any. */
  if (opt.warc_user_headers)
    {
      int i;
      for (i = 0; opt.warc_user_headers[i]; i++)
        fprintf (warc_tmp, "%s\r\n", opt.warc_user_headers[i]);
    }
  fprintf(warc_tmp, "\r\n");

  warc_write_digest_headers (warc_tmp, -1);
  warc_write_block_from_file (warc_tmp);
  warc_write_end_record ();

  if (! warc_write_ok)
    logprintf (LOG_NOTQUIET, _("Error writing warcinfo record to WARC file.\n"));

  xfree (filename_copy);
  xfree (filename_basename);
  fclose (warc_tmp);
  return warc_write_ok;
}

/* Opens a new WARC file.
   If META is true, generates a filename ending with 'meta.warc.gz'.

   This method will:
   1. close the current WARC file (if there is one);
   2. increment warc_current_file_number;
   3. open a new WARC file;
   4. write the initial warcinfo record.

   Returns true on success, false otherwise.
   */
static bool
warc_start_new_file (bool meta)
{
#ifdef __VMS
# define WARC_GZ "warc-gz"
#else /* def __VMS */
# define WARC_GZ "warc.gz"
#endif /* def __VMS [else] */

#ifdef HAVE_LIBZ
  const char *extension = (opt.warc_compression_enabled ? WARC_GZ : "warc");
#else
  const char *extension = "warc";
#endif

  int base_filename_length;
  char *new_filename;

  if (opt.warc_filename == NULL)
    return false;

  if (warc_current_file != NULL)
    fclose (warc_current_file);

  xfree (warc_current_warcinfo_uuid_str);
  xfree (warc_current_filename);

  warc_current_file_number++;

  base_filename_length = strlen (opt.warc_filename);
  /* filename format:  base + "-" + 5 digit serial number + ".warc.gz" */
  new_filename = malloc (base_filename_length + 1 + 5 + 8 + 1);
  warc_current_filename = new_filename;

  /* If max size is enabled, we add a serial number to the file names. */
  if (meta)
    sprintf (new_filename, "%s-meta.%s", opt.warc_filename, extension);
  else if (opt.warc_maxsize > 0)
    {
      sprintf (new_filename, "%s-%05d.%s", opt.warc_filename,
               warc_current_file_number, extension);
    }
  else
    sprintf (new_filename, "%s.%s", opt.warc_filename, extension);

  logprintf (LOG_VERBOSE, _("Opening WARC file %s.\n\n"), quote (new_filename));

  /* Open the WARC file. */
  warc_current_file = fopen (new_filename, "wb+");
  if (warc_current_file == NULL)
    {
      logprintf (LOG_NOTQUIET, _("Error opening WARC file %s.\n"),
                 quote (new_filename));
      return false;
    }

  if (! warc_write_warcinfo_record (new_filename))
    return false;

  /* Add warcinfo uuid to manifest. */
  if (warc_manifest_fp)
    fprintf (warc_manifest_fp, "%s\n", warc_current_warcinfo_uuid_str);

  return true;
}

/* Opens the CDX file for output. */
static bool
warc_start_cdx_file (void)
{
  int filename_length = strlen (opt.warc_filename);
  char *cdx_filename = alloca (filename_length + 4 + 1);
  memcpy (cdx_filename, opt.warc_filename, filename_length);
  memcpy (cdx_filename + filename_length, ".cdx", 5);
  warc_current_cdx_file = fopen (cdx_filename, "a+");
  if (warc_current_cdx_file == NULL)
    return false;

  /* Print the CDX header.
   *
   * a - original url
   * b - date
   * m - mime type
   * s - response code
   * k - new style checksum
   * r - redirect
   * M - meta tags
   * V - compressed arc file offset
   * g - file name
   * u - record-id
   */
  fprintf (warc_current_cdx_file, " CDX a b a m s k r M V g u\n");
  fflush (warc_current_cdx_file);

  return true;
}

#define CDX_FIELDSEP " \t\r\n"

/* Parse the CDX header and find the field numbers of the original url,
   checksum and record ID fields. */
static bool
warc_parse_cdx_header (char *lineptr, int *field_num_original_url,
                       int *field_num_checksum, int *field_num_record_id)
{
  char *token;
  char *save_ptr;

  *field_num_original_url = -1;
  *field_num_checksum = -1;
  *field_num_record_id = -1;

  token = strtok_r (lineptr, CDX_FIELDSEP, &save_ptr);

  if (token != NULL && strcmp (token, "CDX") == 0)
    {
      int field_num = 0;
      while (token != NULL)
        {
          token = strtok_r (NULL, CDX_FIELDSEP, &save_ptr);
          if (token != NULL)
            {
              switch (token[0])
                {
                case 'a':
                  *field_num_original_url = field_num;
                  break;
                case 'k':
                  *field_num_checksum = field_num;
                  break;
                case 'u':
                  *field_num_record_id = field_num;
                  break;
                }
            }
          field_num++;
        }
    }

  return *field_num_original_url != -1
         && *field_num_checksum != -1
         && *field_num_record_id != -1;
}

/* Parse the CDX record and add it to the warc_cdx_dedup_table hash table. */
static void
warc_process_cdx_line (char *lineptr, int field_num_original_url,
                       int field_num_checksum, int field_num_record_id)
{
  char *original_url = NULL;
  char *checksum = NULL;
  char *record_id = NULL;
  char *token;
  char *save_ptr;
  int field_num = 0;

  /* Read this line to get the fields we need. */
  token = strtok_r (lineptr, CDX_FIELDSEP, &save_ptr);
  while (token != NULL)
    {
      char **val;
      if (field_num == field_num_original_url)
        val = &original_url;
      else if (field_num == field_num_checksum)
        val = &checksum;
      else if (field_num == field_num_record_id)
        val = &record_id;
      else
        val = NULL;

      if (val != NULL)
        *val = strdup (token);

      token = strtok_r (NULL, CDX_FIELDSEP, &save_ptr);
      field_num++;
    }

  if (original_url != NULL && checksum != NULL && record_id != NULL)
    {
      /* For some extra efficiency, we decode the base32 encoded
         checksum value.  This should produce exactly SHA1_DIGEST_SIZE
         bytes.  */
      size_t checksum_l;
      char * checksum_v;
      base32_decode_alloc (checksum, strlen (checksum), &checksum_v,
                           &checksum_l);
      xfree (checksum);

      if (checksum_v != NULL && checksum_l == SHA1_DIGEST_SIZE)
        {
          /* This is a valid line with a valid checksum. */
          struct warc_cdx_record *rec;
          rec = malloc (sizeof (struct warc_cdx_record));
          rec->url = original_url;
          rec->uuid = record_id;
          memcpy (rec->digest, checksum_v, SHA1_DIGEST_SIZE);
          hash_table_put (warc_cdx_dedup_table, rec->digest, rec);
          xfree (checksum_v);
        }
      else
        {
          xfree (original_url);
          xfree (checksum_v);
          xfree (record_id);
        }
    }
  else
    {
      xfree(checksum);
      xfree(original_url);
      xfree(record_id);
    }
}

/* Loads the CDX file from opt.warc_cdx_dedup_filename and fills
   the warc_cdx_dedup_table. */
static bool
warc_load_cdx_dedup_file (void)
{
  FILE *f;
  char *lineptr = NULL;
  size_t n = 0;
  ssize_t line_length;
  int field_num_original_url = -1;
  int field_num_checksum = -1;
  int field_num_record_id = -1;

  f = fopen (opt.warc_cdx_dedup_filename, "r");
  if (f == NULL)
    return false;

  /* The first line should contain the CDX header.
     Format:  " CDX x x x x x"
     where x are field type indicators.  For our purposes, we only
     need 'a' (the original url), 'k' (the SHA1 checksum) and
     'u' (the WARC record id). */
  line_length = getline (&lineptr, &n, f);
  if (line_length != -1)
    warc_parse_cdx_header (lineptr, &field_num_original_url,
                           &field_num_checksum, &field_num_record_id);

  /* If the file contains all three fields, read the complete file. */
  if (field_num_original_url == -1
      || field_num_checksum == -1
      || field_num_record_id == -1)
    {
      if (field_num_original_url == -1)
        logprintf (LOG_NOTQUIET,
_("CDX file does not list original urls. (Missing column 'a'.)\n"));
      if (field_num_checksum == -1)
        logprintf (LOG_NOTQUIET,
_("CDX file does not list checksums. (Missing column 'k'.)\n"));
      if (field_num_record_id == -1)
        logprintf (LOG_NOTQUIET,
_("CDX file does not list record ids. (Missing column 'u'.)\n"));
    }
  else
    {
      int nrecords;

      /* Initialize the table. */
      warc_cdx_dedup_table = hash_table_new (1000, warc_hash_sha1_digest,
                                             warc_cmp_sha1_digest);

      do
        {
          line_length = getline (&lineptr, &n, f);
          if (line_length != -1)
            {
              warc_process_cdx_line (lineptr, field_num_original_url,
                            field_num_checksum, field_num_record_id);
            }

        }
      while (line_length != -1);

      /* Print results. */
      nrecords = hash_table_count (warc_cdx_dedup_table);
      logprintf (LOG_VERBOSE, ngettext ("Loaded %d record from CDX.\n\n",
                                        "Loaded %d records from CDX.\n\n",
                                         nrecords),
                              nrecords);
    }

  xfree (lineptr);
  fclose (f);

  return true;
}
#undef CDX_FIELDSEP

/* Returns the existing duplicate CDX record for the given url and payload
   digest.  Returns NULL if the url is not found or if the payload digest
   does not match, or if CDX deduplication is disabled. */
static struct warc_cdx_record *
warc_find_duplicate_cdx_record (char *url, char *sha1_digest_payload)
{
  struct warc_cdx_record *rec_existing;

  if (warc_cdx_dedup_table == NULL)
    return NULL;

  rec_existing = hash_table_get (warc_cdx_dedup_table, sha1_digest_payload);

  if (rec_existing && strcmp (rec_existing->url, url) == 0)
    return rec_existing;
  else
    return NULL;
}

/* Initializes the WARC writer (if opt.warc_filename is set).
   This should be called before any WARC record is written. */
void
warc_init (void)
{
  warc_write_ok = true;

  if (opt.warc_filename != NULL)
    {
      if (opt.warc_cdx_dedup_filename != NULL)
        {
          if (! warc_load_cdx_dedup_file ())
            {
              logprintf (LOG_NOTQUIET,
                         _("Could not read CDX file %s for deduplication.\n"),
                         quote (opt.warc_cdx_dedup_filename));
              exit (WGET_EXIT_GENERIC_ERROR);
            }
        }

      warc_manifest_fp = warc_tempfile ();
      if (warc_manifest_fp == NULL)
        {
          logprintf (LOG_NOTQUIET,
                     _("Could not open temporary WARC manifest file.\n"));
          exit (WGET_EXIT_GENERIC_ERROR);
        }

      if (opt.warc_keep_log)
        {
          warc_log_fp = warc_tempfile ();
          if (warc_log_fp == NULL)
            {
              logprintf (LOG_NOTQUIET,
                         _("Could not open temporary WARC log file.\n"));
              exit (WGET_EXIT_GENERIC_ERROR);
            }
          log_set_warc_log_fp (warc_log_fp);
        }

      warc_current_file_number = -1;
      if (! warc_start_new_file (false))
        {
          logprintf (LOG_NOTQUIET, _("Could not open WARC file.\n"));
          exit (WGET_EXIT_GENERIC_ERROR);
        }

      if (opt.warc_cdx_enabled)
        {
          if (! warc_start_cdx_file ())
            {
              logprintf (LOG_NOTQUIET,
                         _("Could not open CDX file for output.\n"));
              exit (WGET_EXIT_GENERIC_ERROR);
            }
        }
    }
}

/* Writes metadata (manifest, configuration, log file) to the WARC file. */
static void
warc_write_metadata (void)
{
  char manifest_uuid[48];
  FILE *warc_tmp_fp;

  /* If there are multiple WARC files, the metadata should be written to a separate file. */
  if (opt.warc_maxsize > 0)
    warc_start_new_file (true);

  warc_uuid_str (manifest_uuid);

  fflush (warc_manifest_fp);
  warc_write_metadata_record (manifest_uuid,
                              "metadata://gnu.org/software/wget/warc/MANIFEST.txt",
                              NULL, NULL, NULL, "text/plain",
                              warc_manifest_fp, -1);
  /* warc_write_resource_record has closed warc_manifest_fp. */

  warc_tmp_fp = warc_tempfile ();
  if (warc_tmp_fp == NULL)
    {
      logprintf (LOG_NOTQUIET, _("Could not open temporary WARC file.\n"));
      exit (WGET_EXIT_GENERIC_ERROR);
    }
  fflush (warc_tmp_fp);
  fprintf (warc_tmp_fp, "%s\n", program_argstring);

  warc_write_resource_record (NULL,
                   "metadata://gnu.org/software/wget/warc/wget_arguments.txt",
                              NULL, manifest_uuid, NULL, "text/plain",
                              warc_tmp_fp, -1);
  /* warc_write_resource_record has closed warc_tmp_fp. */

  if (warc_log_fp != NULL)
    {
      warc_write_resource_record (NULL,
                              "metadata://gnu.org/software/wget/warc/wget.log",
                                  NULL, manifest_uuid, NULL, "text/plain",
                                  warc_log_fp, -1);
      /* warc_write_resource_record has closed warc_log_fp. */

      warc_log_fp = NULL;
      log_set_warc_log_fp (NULL);
    }
}

/* Finishes the WARC writing.
   This should be called at the end of the program. */
void
warc_close (void)
{
  if (warc_current_file != NULL)
    {
      warc_write_metadata ();
      xfree (warc_current_warcinfo_uuid_str);
      fclose (warc_current_file);
    }
  if (warc_current_cdx_file != NULL)
    fclose (warc_current_cdx_file);
  if (warc_log_fp != NULL)
    {
      fclose (warc_log_fp);
      log_set_warc_log_fp (NULL);
    }
}

/* Creates a temporary file for writing WARC output.
   The temporary file will be created in opt.warc_tempdir.
   Returns the pointer to the temporary file, or NULL. */
FILE *
warc_tempfile (void)
{
  char filename[100];
  int fd;

  if (path_search (filename, 100, opt.warc_tempdir, "wget", true) == -1)
    return NULL;

#ifdef __VMS
  /* 2013-07-12 SMS.
   * mkostemp()+unlink()+fdopen() scheme causes trouble on VMS, so use
   * mktemp() to uniquify the (VMS-style) name, and then use a normal
   * fopen() with a "create temp file marked for delete" option.
   */
  {
    char *tfn;

    tfn = mktemp (filename);            /* Get unique name from template. */
    if (tfn == NULL)
      return NULL;
    return fopen (tfn, "w+", "fop=tmd");    /* Create auto-delete temp file. */
  }
#else /* def __VMS */
  fd = mkostemp (filename, O_TEMPORARY);
  if (fd < 0)
    return NULL;

#if !O_TEMPORARY
  if (unlink (filename) < 0)
    {
      close(fd);
      return NULL;
    }
#endif

  return fdopen (fd, "wb+");
#endif /* def __VMS [else] */
}


/* Writes a request record to the WARC file.
   url  is the target uri of the request,
   timestamp_str  is the timestamp of the request (generated with warc_timestamp),
   record_uuid  is the uuid of the request (generated with warc_uuid_str),
   body  is a pointer to a file containing the request headers and body.
   ip  is the ip address of the server (or NULL),
   Calling this function will close body.
   Returns true on success, false on error. */
bool
warc_write_request_record (char *url, char *timestamp_str, char *record_uuid,
                           ip_address *ip, FILE *body, off_t payload_offset)
{
  warc_write_start_record ();
  warc_write_header ("WARC-Type", "request");
  warc_write_header ("WARC-Target-URI", url);
  warc_write_header ("Content-Type", "application/http;msgtype=request");
  warc_write_date_header (timestamp_str);
  warc_write_header ("WARC-Record-ID", record_uuid);
  warc_write_ip_header (ip);
  warc_write_header ("WARC-Warcinfo-ID", warc_current_warcinfo_uuid_str);
  warc_write_digest_headers (body, payload_offset);
  warc_write_block_from_file (body);
  warc_write_end_record ();

  fclose (body);

  return warc_write_ok;
}

/* Writes a response record to the CDX file.
   url  is the target uri of the request/response,
   timestamp_str  is the timestamp of the request that generated this response,
                  (generated with warc_timestamp),
   mime_type  is the mime type of the response body (will be printed to CDX),
   response_code  is the HTTP response code (will be printed to CDX),
   payload_digest  is the sha1 digest of the payload,
   redirect_location  is the contents of the Location: header, or NULL (will be printed to CDX),
   offset  is the position of the WARC record in the WARC file,
   warc_filename  is the filename of the WARC,
   response_uuid  is the uuid of the response.
   Returns true on success, false on error. */
static bool
warc_write_cdx_record (const char *url, const char *timestamp_str,
                       const char *mime_type, int response_code,
                       const char *payload_digest, const char *redirect_location,
                       off_t offset, const char *warc_filename _GL_UNUSED,
                       const char *response_uuid)
{
  /* Transform the timestamp. */
  char timestamp_str_cdx[15];
  char offset_string[MAX_INT_TO_STRING_LEN(off_t)];
  const char *checksum;

  memcpy (timestamp_str_cdx     , timestamp_str     , 4); /* "YYYY" "-" */
  memcpy (timestamp_str_cdx +  4, timestamp_str +  5, 2); /* "mm"   "-" */
  memcpy (timestamp_str_cdx +  6, timestamp_str +  8, 2); /* "dd"   "T" */
  memcpy (timestamp_str_cdx +  8, timestamp_str + 11, 2); /* "HH"   ":" */
  memcpy (timestamp_str_cdx + 10, timestamp_str + 14, 2); /* "MM"   ":" */
  memcpy (timestamp_str_cdx + 12, timestamp_str + 17, 2); /* "SS"   "Z" */
  timestamp_str_cdx[14] = '\0';

  /* Rewrite the checksum. */
  if (payload_digest != NULL)
    checksum = payload_digest + 5; /* Skip the "sha1:" */
  else
    checksum = "-";

  if (mime_type == NULL || strlen(mime_type) == 0)
    mime_type = "-";
  if (redirect_location == NULL || strlen(redirect_location) == 0)
    redirect_location = "-";

  number_to_string (offset_string, offset);

  /* Print the CDX line. */
  fprintf (warc_current_cdx_file, "%s %s %s %s %d %s %s - %s %s %s\n", url,
           timestamp_str_cdx, url, mime_type, response_code, checksum,
           redirect_location, offset_string, warc_current_filename,
           response_uuid);
  fflush (warc_current_cdx_file);

  return true;
}

/* Writes a revisit record to the WARC file.
   url  is the target uri of the request/response,
   timestamp_str  is the timestamp of the request that generated this response
                  (generated with warc_timestamp),
   concurrent_to_uuid  is the uuid of the request for that generated this response
                 (generated with warc_uuid_str),
   refers_to_uuid  is the uuid of the original response
                 (generated with warc_uuid_str),
   payload_digest  is the sha1 digest of the payload,
   ip  is the ip address of the server (or NULL),
   body  is a pointer to a file containing the response headers (without payload).
   Calling this function will close body.
   Returns true on success, false on error. */
static bool
warc_write_revisit_record (char *url, char *timestamp_str,
                           char *concurrent_to_uuid, char *payload_digest,
                           char *refers_to, ip_address *ip, FILE *body)
{
  char revisit_uuid [48];
  char *block_digest = NULL;
  char sha1_res_block[SHA1_DIGEST_SIZE];

  warc_uuid_str (revisit_uuid);

  sha1_stream (body, sha1_res_block);
  block_digest = warc_base32_sha1_digest (sha1_res_block);

  warc_write_start_record ();
  warc_write_header ("WARC-Type", "revisit");
  warc_write_header ("WARC-Record-ID", revisit_uuid);
  warc_write_header ("WARC-Warcinfo-ID", warc_current_warcinfo_uuid_str);
  warc_write_header ("WARC-Concurrent-To", concurrent_to_uuid);
  warc_write_header ("WARC-Refers-To", refers_to);
  warc_write_header ("WARC-Profile", "http://netpreserve.org/warc/1.0/revisit/identical-payload-digest");
  warc_write_header ("WARC-Truncated", "length");
  warc_write_header ("WARC-Target-URI", url);
  warc_write_date_header (timestamp_str);
  warc_write_ip_header (ip);
  warc_write_header ("Content-Type", "application/http;msgtype=response");
  warc_write_header ("WARC-Block-Digest", block_digest);
  warc_write_header ("WARC-Payload-Digest", payload_digest);
  warc_write_block_from_file (body);
  warc_write_end_record ();

  fclose (body);
  xfree (block_digest);

  return warc_write_ok;
}

/* Writes a response record to the WARC file.
   url  is the target uri of the request/response,
   timestamp_str  is the timestamp of the request that generated this response
                  (generated with warc_timestamp),
   concurrent_to_uuid  is the uuid of the request for that generated this response
                 (generated with warc_uuid_str),
   ip  is the ip address of the server (or NULL),
   body  is a pointer to a file containing the response headers and body.
   mime_type  is the mime type of the response body (will be printed to CDX),
   response_code  is the HTTP response code (will be printed to CDX),
   redirect_location  is the contents of the Location: header, or NULL (will be printed to CDX),
   Calling this function will close body.
   Returns true on success, false on error. */
bool
warc_write_response_record (char *url, char *timestamp_str,
                            char *concurrent_to_uuid, ip_address *ip,
                            FILE *body, off_t payload_offset, char *mime_type,
                            int response_code, char *redirect_location)
{
  char *block_digest = NULL;
  char *payload_digest = NULL;
  char sha1_res_block[SHA1_DIGEST_SIZE];
  char sha1_res_payload[SHA1_DIGEST_SIZE];
  char response_uuid [48];
  off_t offset;

  if (opt.warc_digests_enabled)
    {
      /* Calculate the block and payload digests. */
      rewind (body);
      if (warc_sha1_stream_with_payload (body, sha1_res_block, sha1_res_payload,
          payload_offset) == 0)
        {
          /* Decide (based on url + payload digest) if we have seen this
             data before. */
          struct warc_cdx_record *rec_existing;
          rec_existing = warc_find_duplicate_cdx_record (url, sha1_res_payload);
          if (rec_existing != NULL)
            {
              bool result;

              /* Found an existing record. */
              logprintf (LOG_VERBOSE,
          _("Found exact match in CDX file. Saving revisit record to WARC.\n"));

              /* Remove the payload from the file. */
              if (payload_offset > 0)
                {
                  if (ftruncate (fileno (body), payload_offset) == -1)
                    return false;
                }

              /* Send the original payload digest. */
              payload_digest = warc_base32_sha1_digest (sha1_res_payload);
              result = warc_write_revisit_record (url, timestamp_str,
                         concurrent_to_uuid, payload_digest, rec_existing->uuid,
                         ip, body);
              xfree (payload_digest);

              return result;
            }

          block_digest = warc_base32_sha1_digest (sha1_res_block);
          payload_digest = warc_base32_sha1_digest (sha1_res_payload);
        }
    }

  /* Not a revisit, just store the record. */

  warc_uuid_str (response_uuid);

  fseeko (warc_current_file, 0L, SEEK_END);
  offset = ftello (warc_current_file);

  warc_write_start_record ();
  warc_write_header ("WARC-Type", "response");
  warc_write_header ("WARC-Record-ID", response_uuid);
  warc_write_header ("WARC-Warcinfo-ID", warc_current_warcinfo_uuid_str);
  warc_write_header ("WARC-Concurrent-To", concurrent_to_uuid);
  warc_write_header ("WARC-Target-URI", url);
  warc_write_date_header (timestamp_str);
  warc_write_ip_header (ip);
  warc_write_header ("WARC-Block-Digest", block_digest);
  warc_write_header ("WARC-Payload-Digest", payload_digest);
  warc_write_header ("Content-Type", "application/http;msgtype=response");
  warc_write_block_from_file (body);
  warc_write_end_record ();

  fclose (body);

  if (warc_write_ok && opt.warc_cdx_enabled)
    {
      /* Add this record to the CDX. */
      warc_write_cdx_record (url, timestamp_str, mime_type, response_code,
      payload_digest, redirect_location, offset, warc_current_filename,
      response_uuid);
    }

  xfree (block_digest);
  xfree (payload_digest);

  return warc_write_ok;
}

/* Writes a resource or metadata record to the WARC file.
   warc_type  is either "resource" or "metadata",
   resource_uuid  is the uuid of the resource (or NULL),
   url  is the target uri of the resource,
   timestamp_str  is the timestamp (generated with warc_timestamp),
   concurrent_to_uuid  is the uuid of the record that generated this,
   resource (generated with warc_uuid_str) or NULL,
   ip  is the ip address of the server (or NULL),
   content_type  is the mime type of the body (or NULL),
   body  is a pointer to a file containing the resource data.
   Calling this function will close body.
   Returns true on success, false on error. */
static bool
warc_write_record (const char *record_type, char *resource_uuid,
                 const char *url, const char *timestamp_str,
                 const char *concurrent_to_uuid,
                 ip_address *ip, const char *content_type, FILE *body,
                 off_t payload_offset)
{
  if (resource_uuid == NULL)
    {
      resource_uuid = alloca (48);
      warc_uuid_str (resource_uuid);
    }

  if (content_type == NULL)
    content_type = "application/octet-stream";

  warc_write_start_record ();
  warc_write_header ("WARC-Type", record_type);
  warc_write_header ("WARC-Record-ID", resource_uuid);
  warc_write_header ("WARC-Warcinfo-ID", warc_current_warcinfo_uuid_str);
  warc_write_header ("WARC-Concurrent-To", concurrent_to_uuid);
  warc_write_header ("WARC-Target-URI", url);
  warc_write_date_header (timestamp_str);
  warc_write_ip_header (ip);
  warc_write_digest_headers (body, payload_offset);
  warc_write_header ("Content-Type", content_type);
  warc_write_block_from_file (body);
  warc_write_end_record ();

  fclose (body);

  return warc_write_ok;
}

/* Writes a resource record to the WARC file.
   resource_uuid  is the uuid of the resource (or NULL),
   url  is the target uri of the resource,
   timestamp_str  is the timestamp (generated with warc_timestamp),
   concurrent_to_uuid  is the uuid of the record that generated this,
   resource (generated with warc_uuid_str) or NULL,
   ip  is the ip address of the server (or NULL),
   content_type  is the mime type of the body (or NULL),
   body  is a pointer to a file containing the resource data.
   Calling this function will close body.
   Returns true on success, false on error. */
bool
warc_write_resource_record (char *resource_uuid, const char *url,
                 const char *timestamp_str, const char *concurrent_to_uuid,
                 ip_address *ip, const char *content_type, FILE *body,
                 off_t payload_offset)
{
  return warc_write_record ("resource",
      resource_uuid, url, timestamp_str, concurrent_to_uuid,
      ip, content_type, body, payload_offset);
}

/* Writes a metadata record to the WARC file.
   record_uuid  is the uuid of the record (or NULL),
   url  is the target uri of the record,
   timestamp_str  is the timestamp (generated with warc_timestamp),
   concurrent_to_uuid  is the uuid of the record that generated this,
   record (generated with warc_uuid_str) or NULL,
   ip  is the ip address of the server (or NULL),
   content_type  is the mime type of the body (or NULL),
   body  is a pointer to a file containing the record data.
   Calling this function will close body.
   Returns true on success, false on error. */
bool
warc_write_metadata_record (char *record_uuid, const char *url,
                 const char *timestamp_str, const char *concurrent_to_uuid,
                 ip_address *ip, const char *content_type, FILE *body,
                 off_t payload_offset)
{
  return warc_write_record ("metadata",
      record_uuid, url, timestamp_str, concurrent_to_uuid,
      ip, content_type, body, payload_offset);
}