1 /*
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
8 #include "SkMD5.h"
9 #include "SkMilestone.h"
10 #include "SkPDFMetadata.h"
11 #include "SkPDFTypes.h"
12 #include "SkUtils.h"
13
14 #include <utility>
15
16 #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
pdf_date(const SkTime::DateTime & dt)21 static 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
utf8_is_pdfdocencoding(const char * src,size_t len)35 static 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
write_utf16be(char ** ptr,uint16_t value)47 void 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
to_utf16be(const char * src,size_t len)58 static 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.
convert(const SkString & s)93 static SkString convert(const SkString& s) {
94 return utf8_is_pdfdocencoding(s.c_str(), s.size()) ? s : to_utf16be(s.c_str(), s.size());
95 }
convert(const char * src)96 static 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
101 namespace {
102 static 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
MakeDocumentInformationDict(const SkDocument::PDFMetadata & metadata)114 sk_sp<SkPDFObject> SkPDFMetadata::MakeDocumentInformationDict(
115 const SkDocument::PDFMetadata& metadata) {
116 auto dict = sk_make_sp<SkPDFDict>();
117 for (const auto keyValuePtr : gMetadataKeys) {
118 const SkString& value = metadata.*(keyValuePtr.valuePtr);
119 if (value.size() > 0) {
120 dict->insertString(keyValuePtr.key, convert(value));
121 }
122 }
123 if (metadata.fProducer.isEmpty()) {
124 dict->insertString("Producer", convert(SKPDF_PRODUCER));
125 } else {
126 dict->insertString("Producer", convert(metadata.fProducer));
127 dict->insertString(SKPDF_CUSTOM_PRODUCER_KEY, convert(SKPDF_PRODUCER));
128 }
129 if (metadata.fCreation.fEnabled) {
130 dict->insertString("CreationDate", pdf_date(metadata.fCreation.fDateTime));
131 }
132 if (metadata.fModified.fEnabled) {
133 dict->insertString("ModDate", pdf_date(metadata.fModified.fDateTime));
134 }
135 return dict;
136 }
137
CreateUUID(const SkDocument::PDFMetadata & metadata)138 SkPDFMetadata::UUID SkPDFMetadata::CreateUUID(
139 const SkDocument::PDFMetadata& metadata) {
140 // 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";
144 md5.writeText(uuidNamespace);
145 double msec = SkTime::GetMSecs();
146 md5.write(&msec, sizeof(msec));
147 SkTime::DateTime dateTime;
148 SkTime::GetDateTime(&dateTime);
149 md5.write(&dateTime, sizeof(dateTime));
150 if (metadata.fCreation.fEnabled) {
151 md5.write(&metadata.fCreation.fDateTime,
152 sizeof(metadata.fCreation.fDateTime));
153 }
154 if (metadata.fModified.fEnabled) {
155 md5.write(&metadata.fModified.fDateTime,
156 sizeof(metadata.fModified.fDateTime));
157 }
158
159 for (const auto keyValuePtr : gMetadataKeys) {
160 md5.writeText(keyValuePtr.key);
161 md5.write("\037", 1);
162 const SkString& value = metadata.*(keyValuePtr.valuePtr);
163 md5.write(value.c_str(), value.size());
164 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
MakePdfId(const UUID & doc,const UUID & instance)177 sk_sp<SkPDFObject> SkPDFMetadata::MakePdfId(const UUID& doc,
178 const UUID& instance) {
179 // /ID [ <81b14aafa313db63dbd6f981e49f94f4>
180 // <81b14aafa313db63dbd6f981e49f94f4> ]
181 auto array = sk_make_sp<SkPDFArray>();
182 static_assert(sizeof(SkPDFMetadata::UUID) == 16, "uuid_size");
183 array->appendString(
184 SkString(reinterpret_cast<const char*>(&doc), sizeof(UUID)));
185 array->appendString(
186 SkString(reinterpret_cast<const char*>(&instance), sizeof(UUID)));
187 return array;
188 }
189
190 // Convert a block of memory to hexadecimal. Input and output pointers will be
191 // moved to end of the range.
hexify(const uint8_t ** inputPtr,char ** outputPtr,int count)192 static 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
uuid_to_string(const SkPDFMetadata::UUID & uuid)202 static SkString uuid_to_string(const SkPDFMetadata::UUID& uuid) {
203 // 8-4-4-4-12
204 char buffer[36]; // [32 + 4]
205 char* ptr = buffer;
206 const uint8_t* data = uuid.fData;
207 hexify(&data, &ptr, 4);
208 *ptr++ = '-';
209 hexify(&data, &ptr, 2);
210 *ptr++ = '-';
211 hexify(&data, &ptr, 2);
212 *ptr++ = '-';
213 hexify(&data, &ptr, 2);
214 *ptr++ = '-';
215 hexify(&data, &ptr, 6);
216 SkASSERT(ptr == buffer + 36);
217 SkASSERT(data == uuid.fData + 16);
218 return SkString(buffer, 36);
219 }
220
221 namespace {
222 class PDFXMLObject final : public SkPDFObject {
223 public:
PDFXMLObject(SkString xml)224 PDFXMLObject(SkString xml) : fXML(std::move(xml)) {}
emitObject(SkWStream * stream,const SkPDFObjNumMap & omap) const225 void emitObject(SkWStream* stream,
226 const SkPDFObjNumMap& omap) const override {
227 SkPDFDict dict("Metadata");
228 dict.insertName("Subtype", "XML");
229 dict.insertInt("Length", fXML.size());
230 dict.emitObject(stream, omap);
231 static const char streamBegin[] = " stream\n";
232 stream->writeText(streamBegin);
233 // Do not compress this. The standard requires that a
234 // program that does not understand PDF can grep for
235 // "<?xpacket" and extract the entire XML.
236 stream->write(fXML.c_str(), fXML.size());
237 static const char streamEnd[] = "\nendstream";
238 stream->writeText(streamEnd);
239 }
240
241 private:
242 const SkString fXML;
243 };
244 } // namespace
245
count_xml_escape_size(const SkString & input)246 static 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("&") - strlen("&")
251 } else if (input[i] == '<') {
252 extra += 3; // strlen("<") - strlen("<")
253 }
254 }
255 return extra;
256 }
257
escape_xml(const SkString & input,const char * before=nullptr,const char * after=nullptr)258 const 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 // "&" --> "&" and "<" --> "<"
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[] = "&";
277 static const char kLt[] = "<";
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';
296 return output;
297 }
298
MakeXMPObject(const SkDocument::PDFMetadata & metadata,const UUID & doc,const UUID & instance)299 sk_sp<SkPDFObject> SkPDFMetadata::MakeXMPObject(
300 const SkDocument::PDFMetadata& metadata,
301 const UUID& doc,
302 const UUID& instance) {
303 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
320 "%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"
328 "%s" // pdf:Producer
329 "%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;
337 if (metadata.fCreation.fEnabled) {
338 SkString tmp;
339 metadata.fCreation.fDateTime.toISO8601(&tmp);
340 SkASSERT(0 == count_xml_escape_size(tmp));
341 // YYYY-mm-ddTHH:MM:SS[+|-]ZZ:ZZ; no need to escape
342 creationDate = SkStringPrintf("<xmp:CreateDate>%s</xmp:CreateDate>\n",
343 tmp.c_str());
344 }
345 if (metadata.fModified.fEnabled) {
346 SkString tmp;
347 metadata.fModified.fDateTime.toISO8601(&tmp);
348 SkASSERT(0 == count_xml_escape_size(tmp));
349 modificationDate = SkStringPrintf(
350 "<xmp:ModifyDate>%s</xmp:ModifyDate>\n", tmp.c_str());
351 }
352 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");
359 // TODO: in theory, XMP can support multiple authors. Split on a delimiter?
360 SkString subject = escape_xml(
361 metadata.fSubject,
362 "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">",
363 "</rdf:li></rdf:Alt></dc:description>\n");
364 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");
369 // TODO: in theory, keywords can be a list too.
370
371 SkString producer("<pdf:Producer>" SKPDF_PRODUCER "</pdf:Producer>\n");
372 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
381 SkString creator = escape_xml(metadata.fCreator, "<xmp:CreatorTool>",
382 "</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));
387 return sk_make_sp<PDFXMLObject>(SkStringPrintf(
388 templateString, modificationDate.c_str(), creationDate.c_str(),
389 creator.c_str(), title.c_str(), subject.c_str(), author.c_str(),
390 keywords1.c_str(), documentID.c_str(), instanceID.c_str(),
391 producer.c_str(), keywords2.c_str()));
392 }
393
394 #undef SKPDF_CUSTOM_PRODUCER_KEY
395 #undef SKPDF_PRODUCER
396 #undef SKPDF_STRING
397 #undef SKPDF_STRING_IMPL
398