blob: ccb3ef38b5e476764b5970f06a7f810e5c89165c [file] [log] [blame]
halcanary34422612015-10-12 10:11:18 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
halcanary488165e2016-04-22 06:10:21 -07008#include "SkMD5.h"
halcanaryffe54002016-03-29 09:09:29 -07009#include "SkMilestone.h"
Hal Canaryfdcfb8b2018-06-13 09:42:32 -040010#include "SkPDFMetadata.h"
halcanary34422612015-10-12 10:11:18 -070011#include "SkPDFTypes.h"
Hal Canaryd6e6e662017-06-17 10:38:13 -040012#include "SkUtils.h"
13
bungeman221524d2016-01-05 14:59:40 -080014#include <utility>
halcanary34422612015-10-12 10:11:18 -070015
halcanary9f4b3322016-06-30 08:22:04 -070016#define SKPDF_STRING(X) SKPDF_STRING_IMPL(X)
17#define SKPDF_STRING_IMPL(X) #X
18#define SKPDF_PRODUCER "Skia/PDF m" SKPDF_STRING(SK_MILESTONE)
19#define SKPDF_CUSTOM_PRODUCER_KEY "ProductionLibrary"
20
halcanary34422612015-10-12 10:11:18 -070021static SkString pdf_date(const SkTime::DateTime& dt) {
22 int timeZoneMinutes = SkToInt(dt.fTimeZoneMinutes);
23 char timezoneSign = timeZoneMinutes >= 0 ? '+' : '-';
24 int timeZoneHours = SkTAbs(timeZoneMinutes) / 60;
25 timeZoneMinutes = SkTAbs(timeZoneMinutes) % 60;
26 return SkStringPrintf(
27 "D:%04u%02u%02u%02u%02u%02u%c%02d'%02d'",
28 static_cast<unsigned>(dt.fYear), static_cast<unsigned>(dt.fMonth),
29 static_cast<unsigned>(dt.fDay), static_cast<unsigned>(dt.fHour),
30 static_cast<unsigned>(dt.fMinute),
31 static_cast<unsigned>(dt.fSecond), timezoneSign, timeZoneHours,
32 timeZoneMinutes);
33}
34
Hal Canary691fd1b2018-02-28 14:10:42 -050035static bool utf8_is_pdfdocencoding(const char* src, size_t len) {
36 const uint8_t* end = (const uint8_t*)src + len;
37 for (const uint8_t* ptr = (const uint8_t*)src; ptr < end; ++ptr) {
38 uint8_t v = *ptr;
39 // See Table D.2 (PDFDocEncoding Character Set) in the PDF3200_2008 spec.
40 if ((v > 23 && v < 32) || v > 126) {
41 return false;
42 }
43 }
44 return true;
45}
46
47void write_utf16be(char** ptr, uint16_t value) {
48 *(*ptr)++ = (value >> 8);
49 *(*ptr)++ = (value & 0xFF);
50}
51
52// Please Note: This "abuses" the SkString, which "should" only hold UTF8.
53// But the SkString is written as if it is really just a ref-counted array of
54// chars, so this works, as long as we handle endiness and conversions ourselves.
55//
56// Input: UTF-8
57// Output UTF-16-BE
58static SkString to_utf16be(const char* src, size_t len) {
59 SkString ret;
60 const char* const end = src + len;
61 size_t n = 1; // BOM
62 for (const char* ptr = src; ptr < end;) {
63 SkUnichar u = SkUTF8_NextUnicharWithError(&ptr, end);
64 if (u < 0) {
65 break;
66 }
67 n += SkUTF16_FromUnichar(u);
68 }
69 ret.resize(2 * n);
70 char* out = ret.writable_str();
71 write_utf16be(&out, 0xFEFF); // BOM
72 for (const char* ptr = src; ptr < end;) {
73 SkUnichar u = SkUTF8_NextUnicharWithError(&ptr, end);
74 if (u < 0) {
75 break;
76 }
77 uint16_t utf16[2];
78 size_t l = SkUTF16_FromUnichar(u, utf16);
79 write_utf16be(&out, utf16[0]);
80 if (l == 2) {
81 write_utf16be(&out, utf16[1]);
82 }
83 }
84 SkASSERT(out == ret.writable_str() + 2 * n);
85 return ret;
86}
87
88// Input: UTF-8
89// Output UTF-16-BE OR PDFDocEncoding (if that encoding is identical to ASCII encoding).
90//
91// See sections 14.3.3 (Document Information Dictionary) and 7.9.2.2 (Text String Type)
92// of the PDF32000_2008 spec.
93static SkString convert(const SkString& s) {
94 return utf8_is_pdfdocencoding(s.c_str(), s.size()) ? s : to_utf16be(s.c_str(), s.size());
95}
96static SkString convert(const char* src) {
97 size_t len = strlen(src);
98 return utf8_is_pdfdocencoding(src, len) ? SkString(src, len) : to_utf16be(src, len);
99}
100
halcanary4b656662016-04-27 07:45:18 -0700101namespace {
102static const struct {
103 const char* const key;
104 SkString SkDocument::PDFMetadata::*const valuePtr;
105} gMetadataKeys[] = {
106 {"Title", &SkDocument::PDFMetadata::fTitle},
107 {"Author", &SkDocument::PDFMetadata::fAuthor},
108 {"Subject", &SkDocument::PDFMetadata::fSubject},
109 {"Keywords", &SkDocument::PDFMetadata::fKeywords},
110 {"Creator", &SkDocument::PDFMetadata::fCreator},
111};
112} // namespace
113
halcanary4b656662016-04-27 07:45:18 -0700114sk_sp<SkPDFObject> SkPDFMetadata::MakeDocumentInformationDict(
115 const SkDocument::PDFMetadata& metadata) {
halcanaryece83922016-03-08 08:32:12 -0800116 auto dict = sk_make_sp<SkPDFDict>();
halcanary4b656662016-04-27 07:45:18 -0700117 for (const auto keyValuePtr : gMetadataKeys) {
118 const SkString& value = metadata.*(keyValuePtr.valuePtr);
119 if (value.size() > 0) {
Hal Canary691fd1b2018-02-28 14:10:42 -0500120 dict->insertString(keyValuePtr.key, convert(value));
halcanary34422612015-10-12 10:11:18 -0700121 }
122 }
halcanary9f4b3322016-06-30 08:22:04 -0700123 if (metadata.fProducer.isEmpty()) {
Hal Canary691fd1b2018-02-28 14:10:42 -0500124 dict->insertString("Producer", convert(SKPDF_PRODUCER));
halcanary9f4b3322016-06-30 08:22:04 -0700125 } else {
Hal Canary691fd1b2018-02-28 14:10:42 -0500126 dict->insertString("Producer", convert(metadata.fProducer));
127 dict->insertString(SKPDF_CUSTOM_PRODUCER_KEY, convert(SKPDF_PRODUCER));
halcanary9f4b3322016-06-30 08:22:04 -0700128 }
halcanary4b656662016-04-27 07:45:18 -0700129 if (metadata.fCreation.fEnabled) {
Hal Canary691fd1b2018-02-28 14:10:42 -0500130 dict->insertString("CreationDate", pdf_date(metadata.fCreation.fDateTime));
halcanary34422612015-10-12 10:11:18 -0700131 }
halcanary4b656662016-04-27 07:45:18 -0700132 if (metadata.fModified.fEnabled) {
133 dict->insertString("ModDate", pdf_date(metadata.fModified.fDateTime));
halcanary34422612015-10-12 10:11:18 -0700134 }
Kevin Lubickf7621cb2018-04-16 15:51:44 -0400135 return std::move(dict);
halcanary34422612015-10-12 10:11:18 -0700136}
137
halcanary4b656662016-04-27 07:45:18 -0700138SkPDFMetadata::UUID SkPDFMetadata::CreateUUID(
139 const SkDocument::PDFMetadata& metadata) {
halcanary34422612015-10-12 10:11:18 -0700140 // The main requirement is for the UUID to be unique; the exact
141 // format of the data that will be hashed is not important.
142 SkMD5 md5;
143 const char uuidNamespace[] = "org.skia.pdf\n";
Hal Canaryc172f9b2017-05-27 20:29:44 -0400144 md5.writeText(uuidNamespace);
benjaminwagnerec4d4d72016-03-25 12:59:53 -0700145 double msec = SkTime::GetMSecs();
halcanary34422612015-10-12 10:11:18 -0700146 md5.write(&msec, sizeof(msec));
147 SkTime::DateTime dateTime;
148 SkTime::GetDateTime(&dateTime);
149 md5.write(&dateTime, sizeof(dateTime));
halcanary4b656662016-04-27 07:45:18 -0700150 if (metadata.fCreation.fEnabled) {
151 md5.write(&metadata.fCreation.fDateTime,
152 sizeof(metadata.fCreation.fDateTime));
halcanary34422612015-10-12 10:11:18 -0700153 }
halcanary4b656662016-04-27 07:45:18 -0700154 if (metadata.fModified.fEnabled) {
155 md5.write(&metadata.fModified.fDateTime,
156 sizeof(metadata.fModified.fDateTime));
halcanary34422612015-10-12 10:11:18 -0700157 }
halcanary4b656662016-04-27 07:45:18 -0700158
159 for (const auto keyValuePtr : gMetadataKeys) {
Hal Canaryc172f9b2017-05-27 20:29:44 -0400160 md5.writeText(keyValuePtr.key);
halcanary34422612015-10-12 10:11:18 -0700161 md5.write("\037", 1);
halcanary4b656662016-04-27 07:45:18 -0700162 const SkString& value = metadata.*(keyValuePtr.valuePtr);
163 md5.write(value.c_str(), value.size());
halcanary34422612015-10-12 10:11:18 -0700164 md5.write("\036", 1);
165 }
166 SkMD5::Digest digest;
167 md5.finish(digest);
168 // See RFC 4122, page 6-7.
169 digest.data[6] = (digest.data[6] & 0x0F) | 0x30;
170 digest.data[8] = (digest.data[6] & 0x3F) | 0x80;
171 static_assert(sizeof(digest) == sizeof(UUID), "uuid_size");
172 SkPDFMetadata::UUID uuid;
173 memcpy(&uuid, &digest, sizeof(digest));
174 return uuid;
175}
176
halcanary4b656662016-04-27 07:45:18 -0700177sk_sp<SkPDFObject> SkPDFMetadata::MakePdfId(const UUID& doc,
178 const UUID& instance) {
halcanary34422612015-10-12 10:11:18 -0700179 // /ID [ <81b14aafa313db63dbd6f981e49f94f4>
180 // <81b14aafa313db63dbd6f981e49f94f4> ]
halcanaryece83922016-03-08 08:32:12 -0800181 auto array = sk_make_sp<SkPDFArray>();
halcanary4b656662016-04-27 07:45:18 -0700182 static_assert(sizeof(SkPDFMetadata::UUID) == 16, "uuid_size");
halcanary34422612015-10-12 10:11:18 -0700183 array->appendString(
184 SkString(reinterpret_cast<const char*>(&doc), sizeof(UUID)));
185 array->appendString(
186 SkString(reinterpret_cast<const char*>(&instance), sizeof(UUID)));
Kevin Lubickf7621cb2018-04-16 15:51:44 -0400187 return std::move(array);
halcanary34422612015-10-12 10:11:18 -0700188}
189
Hal Canaryd6e6e662017-06-17 10:38:13 -0400190// Convert a block of memory to hexadecimal. Input and output pointers will be
191// moved to end of the range.
192static void hexify(const uint8_t** inputPtr, char** outputPtr, int count) {
193 SkASSERT(inputPtr && *inputPtr);
194 SkASSERT(outputPtr && *outputPtr);
195 while (count-- > 0) {
196 uint8_t value = *(*inputPtr)++;
197 *(*outputPtr)++ = SkHexadecimalDigits::gLower[value >> 4];
198 *(*outputPtr)++ = SkHexadecimalDigits::gLower[value & 0xF];
199 }
200}
201
halcanary34422612015-10-12 10:11:18 -0700202static SkString uuid_to_string(const SkPDFMetadata::UUID& uuid) {
203 // 8-4-4-4-12
204 char buffer[36]; // [32 + 4]
halcanary34422612015-10-12 10:11:18 -0700205 char* ptr = buffer;
206 const uint8_t* data = uuid.fData;
Hal Canaryd6e6e662017-06-17 10:38:13 -0400207 hexify(&data, &ptr, 4);
halcanary34422612015-10-12 10:11:18 -0700208 *ptr++ = '-';
Hal Canaryd6e6e662017-06-17 10:38:13 -0400209 hexify(&data, &ptr, 2);
halcanary34422612015-10-12 10:11:18 -0700210 *ptr++ = '-';
Hal Canaryd6e6e662017-06-17 10:38:13 -0400211 hexify(&data, &ptr, 2);
halcanary34422612015-10-12 10:11:18 -0700212 *ptr++ = '-';
Hal Canaryd6e6e662017-06-17 10:38:13 -0400213 hexify(&data, &ptr, 2);
halcanary34422612015-10-12 10:11:18 -0700214 *ptr++ = '-';
Hal Canaryd6e6e662017-06-17 10:38:13 -0400215 hexify(&data, &ptr, 6);
halcanary34422612015-10-12 10:11:18 -0700216 SkASSERT(ptr == buffer + 36);
217 SkASSERT(data == uuid.fData + 16);
218 return SkString(buffer, 36);
219}
halcanary34422612015-10-12 10:11:18 -0700220
221namespace {
halcanary70d15542015-11-22 12:55:04 -0800222class PDFXMLObject final : public SkPDFObject {
halcanary34422612015-10-12 10:11:18 -0700223public:
bungeman221524d2016-01-05 14:59:40 -0800224 PDFXMLObject(SkString xml) : fXML(std::move(xml)) {}
halcanary34422612015-10-12 10:11:18 -0700225 void emitObject(SkWStream* stream,
halcanary530032a2016-08-18 14:22:52 -0700226 const SkPDFObjNumMap& omap) const override {
halcanary34422612015-10-12 10:11:18 -0700227 SkPDFDict dict("Metadata");
228 dict.insertName("Subtype", "XML");
229 dict.insertInt("Length", fXML.size());
halcanary530032a2016-08-18 14:22:52 -0700230 dict.emitObject(stream, omap);
halcanary34422612015-10-12 10:11:18 -0700231 static const char streamBegin[] = " stream\n";
Hal Canaryc172f9b2017-05-27 20:29:44 -0400232 stream->writeText(streamBegin);
halcanary34422612015-10-12 10:11:18 -0700233 // Do not compress this. The standard requires that a
234 // program that does not understand PDF can grep for
Hal Canary55325b72017-01-03 10:36:17 -0500235 // "<?xpacket" and extract the entire XML.
halcanary34422612015-10-12 10:11:18 -0700236 stream->write(fXML.c_str(), fXML.size());
237 static const char streamEnd[] = "\nendstream";
Hal Canaryc172f9b2017-05-27 20:29:44 -0400238 stream->writeText(streamEnd);
halcanary34422612015-10-12 10:11:18 -0700239 }
240
241private:
242 const SkString fXML;
243};
244} // namespace
245
246static int count_xml_escape_size(const SkString& input) {
247 int extra = 0;
248 for (size_t i = 0; i < input.size(); ++i) {
249 if (input[i] == '&') {
250 extra += 4; // strlen("&amp;") - strlen("&")
251 } else if (input[i] == '<') {
252 extra += 3; // strlen("&lt;") - strlen("<")
253 }
254 }
255 return extra;
256}
257
258const SkString escape_xml(const SkString& input,
259 const char* before = nullptr,
260 const char* after = nullptr) {
261 if (input.size() == 0) {
262 return input;
263 }
264 // "&" --> "&amp;" and "<" --> "&lt;"
265 // text is assumed to be in UTF-8
266 // all strings are xml content, not attribute values.
267 size_t beforeLen = before ? strlen(before) : 0;
268 size_t afterLen = after ? strlen(after) : 0;
269 int extra = count_xml_escape_size(input);
270 SkString output(input.size() + extra + beforeLen + afterLen);
271 char* out = output.writable_str();
272 if (before) {
273 strncpy(out, before, beforeLen);
274 out += beforeLen;
275 }
276 static const char kAmp[] = "&amp;";
277 static const char kLt[] = "&lt;";
278 for (size_t i = 0; i < input.size(); ++i) {
279 if (input[i] == '&') {
280 strncpy(out, kAmp, strlen(kAmp));
281 out += strlen(kAmp);
282 } else if (input[i] == '<') {
283 strncpy(out, kLt, strlen(kLt));
284 out += strlen(kLt);
285 } else {
286 *out++ = input[i];
287 }
288 }
289 if (after) {
290 strncpy(out, after, afterLen);
291 out += afterLen;
292 }
293 // Validate that we haven't written outside of our string.
294 SkASSERT(out == &output.writable_str()[output.size()]);
295 *out = '\0';
halcanary78daeff2016-04-07 12:34:59 -0700296 return output;
halcanary34422612015-10-12 10:11:18 -0700297}
298
halcanary4b656662016-04-27 07:45:18 -0700299sk_sp<SkPDFObject> SkPDFMetadata::MakeXMPObject(
300 const SkDocument::PDFMetadata& metadata,
301 const UUID& doc,
302 const UUID& instance) {
halcanary34422612015-10-12 10:11:18 -0700303 static const char templateString[] =
304 "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
305 "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"\n"
306 " x:xmptk=\"Adobe XMP Core 5.4-c005 78.147326, "
307 "2012/08/23-13:03:03\">\n"
308 "<rdf:RDF "
309 "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
310 "<rdf:Description rdf:about=\"\"\n"
311 " xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n"
312 " xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n"
313 " xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n"
314 " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n"
315 " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
316 "<pdfaid:part>2</pdfaid:part>\n"
317 "<pdfaid:conformance>B</pdfaid:conformance>\n"
318 "%s" // ModifyDate
319 "%s" // CreateDate
halcanary34422612015-10-12 10:11:18 -0700320 "%s" // xmp:CreatorTool
321 "<dc:format>application/pdf</dc:format>\n"
322 "%s" // dc:title
323 "%s" // dc:description
324 "%s" // author
325 "%s" // keywords
326 "<xmpMM:DocumentID>uuid:%s</xmpMM:DocumentID>\n"
327 "<xmpMM:InstanceID>uuid:%s</xmpMM:InstanceID>\n"
halcanary9f4b3322016-06-30 08:22:04 -0700328 "%s" // pdf:Producer
halcanary34422612015-10-12 10:11:18 -0700329 "%s" // pdf:Keywords
330 "</rdf:Description>\n"
331 "</rdf:RDF>\n"
332 "</x:xmpmeta>\n" // Note: the standard suggests 4k of padding.
333 "<?xpacket end=\"w\"?>\n";
334
335 SkString creationDate;
336 SkString modificationDate;
halcanary4b656662016-04-27 07:45:18 -0700337 if (metadata.fCreation.fEnabled) {
halcanary34422612015-10-12 10:11:18 -0700338 SkString tmp;
halcanary4b656662016-04-27 07:45:18 -0700339 metadata.fCreation.fDateTime.toISO8601(&tmp);
halcanary34422612015-10-12 10:11:18 -0700340 SkASSERT(0 == count_xml_escape_size(tmp));
341 // YYYY-mm-ddTHH:MM:SS[+|-]ZZ:ZZ; no need to escape
halcanaryd51bdae2016-04-25 09:25:35 -0700342 creationDate = SkStringPrintf("<xmp:CreateDate>%s</xmp:CreateDate>\n",
343 tmp.c_str());
halcanary34422612015-10-12 10:11:18 -0700344 }
halcanary4b656662016-04-27 07:45:18 -0700345 if (metadata.fModified.fEnabled) {
halcanary34422612015-10-12 10:11:18 -0700346 SkString tmp;
halcanary4b656662016-04-27 07:45:18 -0700347 metadata.fModified.fDateTime.toISO8601(&tmp);
halcanary34422612015-10-12 10:11:18 -0700348 SkASSERT(0 == count_xml_escape_size(tmp));
halcanaryd51bdae2016-04-25 09:25:35 -0700349 modificationDate = SkStringPrintf(
halcanary34422612015-10-12 10:11:18 -0700350 "<xmp:ModifyDate>%s</xmp:ModifyDate>\n", tmp.c_str());
halcanary34422612015-10-12 10:11:18 -0700351 }
halcanary4b656662016-04-27 07:45:18 -0700352 SkString title =
353 escape_xml(metadata.fTitle,
354 "<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">",
355 "</rdf:li></rdf:Alt></dc:title>\n");
356 SkString author =
357 escape_xml(metadata.fAuthor, "<dc:creator><rdf:Bag><rdf:li>",
358 "</rdf:li></rdf:Bag></dc:creator>\n");
halcanary34422612015-10-12 10:11:18 -0700359 // TODO: in theory, XMP can support multiple authors. Split on a delimiter?
halcanary78daeff2016-04-07 12:34:59 -0700360 SkString subject = escape_xml(
halcanary4b656662016-04-27 07:45:18 -0700361 metadata.fSubject,
halcanary78daeff2016-04-07 12:34:59 -0700362 "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">",
363 "</rdf:li></rdf:Alt></dc:description>\n");
halcanary4b656662016-04-27 07:45:18 -0700364 SkString keywords1 =
365 escape_xml(metadata.fKeywords, "<dc:subject><rdf:Bag><rdf:li>",
366 "</rdf:li></rdf:Bag></dc:subject>\n");
367 SkString keywords2 = escape_xml(metadata.fKeywords, "<pdf:Keywords>",
368 "</pdf:Keywords>\n");
halcanary34422612015-10-12 10:11:18 -0700369 // TODO: in theory, keywords can be a list too.
halcanary9f4b3322016-06-30 08:22:04 -0700370
halcanary492d6b52016-07-07 12:28:30 -0700371 SkString producer("<pdf:Producer>" SKPDF_PRODUCER "</pdf:Producer>\n");
halcanary9f4b3322016-06-30 08:22:04 -0700372 if (!metadata.fProducer.isEmpty()) {
373 // TODO: register a developer prefix to make
374 // <skia:SKPDF_CUSTOM_PRODUCER_KEY> a real XML tag.
375 producer = escape_xml(
376 metadata.fProducer, "<pdf:Producer>",
377 "</pdf:Producer>\n<!-- <skia:" SKPDF_CUSTOM_PRODUCER_KEY ">"
378 SKPDF_PRODUCER "</skia:" SKPDF_CUSTOM_PRODUCER_KEY "> -->\n");
379 }
380
halcanary4b656662016-04-27 07:45:18 -0700381 SkString creator = escape_xml(metadata.fCreator, "<xmp:CreatorTool>",
halcanary34422612015-10-12 10:11:18 -0700382 "</xmp:CreatorTool>\n");
383 SkString documentID = uuid_to_string(doc); // no need to escape
384 SkASSERT(0 == count_xml_escape_size(documentID));
385 SkString instanceID = uuid_to_string(instance);
386 SkASSERT(0 == count_xml_escape_size(instanceID));
halcanary4b656662016-04-27 07:45:18 -0700387 return sk_make_sp<PDFXMLObject>(SkStringPrintf(
halcanary34422612015-10-12 10:11:18 -0700388 templateString, modificationDate.c_str(), creationDate.c_str(),
halcanary4b656662016-04-27 07:45:18 -0700389 creator.c_str(), title.c_str(), subject.c_str(), author.c_str(),
390 keywords1.c_str(), documentID.c_str(), instanceID.c_str(),
halcanary9f4b3322016-06-30 08:22:04 -0700391 producer.c_str(), keywords2.c_str()));
halcanary34422612015-10-12 10:11:18 -0700392}
393
halcanary9f4b3322016-06-30 08:22:04 -0700394#undef SKPDF_CUSTOM_PRODUCER_KEY
395#undef SKPDF_PRODUCER
halcanary8cd4a242016-04-07 08:56:15 -0700396#undef SKPDF_STRING
397#undef SKPDF_STRING_IMPL