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 "src/pdf/SkPDFMetadata.h"
9
10#include "include/private/SkTo.h"
11#include "src/core/SkMD5.h"
12#include "src/core/SkUtils.h"
13#include "src/pdf/SkPDFTypes.h"
14
15#include <utility>
16
17static constexpr SkTime::DateTime kZeroTime = {0, 0, 0, 0, 0, 0, 0, 0};
18
19static bool operator!=(const SkTime::DateTime& u, const SkTime::DateTime& v) {
20 return u.fTimeZoneMinutes != v.fTimeZoneMinutes ||
21 u.fYear != v.fYear ||
22 u.fMonth != v.fMonth ||
23 u.fDayOfWeek != v.fDayOfWeek ||
24 u.fDay != v.fDay ||
25 u.fHour != v.fHour ||
26 u.fMinute != v.fMinute ||
27 u.fSecond != v.fSecond;
28}
29
30static SkString pdf_date(const SkTime::DateTime& dt) {
31 int timeZoneMinutes = SkToInt(dt.fTimeZoneMinutes);
32 char timezoneSign = timeZoneMinutes >= 0 ? '+' : '-';
33 int timeZoneHours = SkTAbs(timeZoneMinutes) / 60;
34 timeZoneMinutes = SkTAbs(timeZoneMinutes) % 60;
35 return SkStringPrintf(
36 "D:%04u%02u%02u%02u%02u%02u%c%02d'%02d'",
37 static_cast<unsigned>(dt.fYear), static_cast<unsigned>(dt.fMonth),
38 static_cast<unsigned>(dt.fDay), static_cast<unsigned>(dt.fHour),
39 static_cast<unsigned>(dt.fMinute),
40 static_cast<unsigned>(dt.fSecond), timezoneSign, timeZoneHours,
41 timeZoneMinutes);
42}
43
44static bool utf8_is_pdfdocencoding(const char* src, size_t len) {
45 const uint8_t* end = (const uint8_t*)src + len;
46 for (const uint8_t* ptr = (const uint8_t*)src; ptr < end; ++ptr) {
47 uint8_t v = *ptr;
48 // See Table D.2 (PDFDocEncoding Character Set) in the PDF3200_2008 spec.
49 if ((v > 23 && v < 32) || v > 126) {
50 return false;
51 }
52 }
53 return true;
54}
55
56void write_utf16be(char** ptr, uint16_t value) {
57 *(*ptr)++ = (value >> 8);
58 *(*ptr)++ = (value & 0xFF);
59}
60
61// Please Note: This "abuses" the SkString, which "should" only hold UTF8.
62// But the SkString is written as if it is really just a ref-counted array of
63// chars, so this works, as long as we handle endiness and conversions ourselves.
64//
65// Input: UTF-8
66// Output UTF-16-BE
67static SkString to_utf16be(const char* src, size_t len) {
68 SkString ret;
69 const char* const end = src + len;
70 size_t n = 1; // BOM
71 for (const char* ptr = src; ptr < end;) {
72 SkUnichar u = SkUTF::NextUTF8(&ptr, end);
73 if (u < 0) {
74 break;
75 }
76 n += SkUTF::ToUTF16(u);
77 }
78 ret.resize(2 * n);
79 char* out = ret.writable_str();
80 write_utf16be(&out, 0xFEFF); // BOM
81 for (const char* ptr = src; ptr < end;) {
82 SkUnichar u = SkUTF::NextUTF8(&ptr, end);
83 if (u < 0) {
84 break;
85 }
86 uint16_t utf16[2];
87 size_t l = SkUTF::ToUTF16(u, utf16);
88 write_utf16be(&out, utf16[0]);
89 if (l == 2) {
90 write_utf16be(&out, utf16[1]);
91 }
92 }
93 SkASSERT(out == ret.writable_str() + 2 * n);
94 return ret;
95}
96
97// Input: UTF-8
98// Output UTF-16-BE OR PDFDocEncoding (if that encoding is identical to ASCII encoding).
99//
100// See sections 14.3.3 (Document Information Dictionary) and 7.9.2.2 (Text String Type)
101// of the PDF32000_2008 spec.
102static SkString convert(const SkString& s) {
103 return utf8_is_pdfdocencoding(s.c_str(), s.size()) ? s : to_utf16be(s.c_str(), s.size());
104}
105
106namespace {
107static const struct {
108 const char* const key;
109 SkString SkPDF::Metadata::*const valuePtr;
110} gMetadataKeys[] = {
111 {"Title", &SkPDF::Metadata::fTitle},
112 {"Author", &SkPDF::Metadata::fAuthor},
113 {"Subject", &SkPDF::Metadata::fSubject},
114 {"Keywords", &SkPDF::Metadata::fKeywords},
115 {"Creator", &SkPDF::Metadata::fCreator},
116 {"Producer", &SkPDF::Metadata::fProducer},
117};
118} // namespace
119
120std::unique_ptr<SkPDFObject> SkPDFMetadata::MakeDocumentInformationDict(
121 const SkPDF::Metadata& metadata) {
122 auto dict = SkPDFMakeDict();
123 for (const auto keyValuePtr : gMetadataKeys) {
124 const SkString& value = metadata.*(keyValuePtr.valuePtr);
125 if (value.size() > 0) {
126 dict->insertString(keyValuePtr.key, convert(value));
127 }
128 }
129 if (metadata.fCreation != kZeroTime) {
130 dict->insertString("CreationDate", pdf_date(metadata.fCreation));
131 }
132 if (metadata.fModified != kZeroTime) {
133 dict->insertString("ModDate", pdf_date(metadata.fModified));
134 }
135 return std::move(dict);
136}
137
138SkUUID SkPDFMetadata::CreateUUID(const SkPDF::Metadata& metadata) {
139 // The main requirement is for the UUID to be unique; the exact
140 // format of the data that will be hashed is not important.
141 SkMD5 md5;
142 const char uuidNamespace[] = "org.skia.pdf\n";
143 md5.writeText(uuidNamespace);
144 double msec = SkTime::GetMSecs();
145 md5.write(&msec, sizeof(msec));
146 SkTime::DateTime dateTime;
147 SkTime::GetDateTime(&dateTime);
148 md5.write(&dateTime, sizeof(dateTime));
149 md5.write(&metadata.fCreation, sizeof(metadata.fCreation));
150 md5.write(&metadata.fModified, sizeof(metadata.fModified));
151
152 for (const auto keyValuePtr : gMetadataKeys) {
153 md5.writeText(keyValuePtr.key);
154 md5.write("\037", 1);
155 const SkString& value = metadata.*(keyValuePtr.valuePtr);
156 md5.write(value.c_str(), value.size());
157 md5.write("\036", 1);
158 }
159 SkMD5::Digest digest = md5.finish();
160 // See RFC 4122, page 6-7.
161 digest.data[6] = (digest.data[6] & 0x0F) | 0x30;
162 digest.data[8] = (digest.data[6] & 0x3F) | 0x80;
163 static_assert(sizeof(digest) == sizeof(SkUUID), "uuid_size");
164 SkUUID uuid;
165 memcpy((void*)&uuid, &digest, sizeof(digest));
166 return uuid;
167}
168
169std::unique_ptr<SkPDFObject> SkPDFMetadata::MakePdfId(const SkUUID& doc,
170 const SkUUID& instance) {
171 // /ID [ <81b14aafa313db63dbd6f981e49f94f4>
172 // <81b14aafa313db63dbd6f981e49f94f4> ]
173 auto array = SkPDFMakeArray();
174 static_assert(sizeof(SkUUID) == 16, "uuid_size");
175 array->appendString(
176 SkString(reinterpret_cast<const char*>(&doc), sizeof(SkUUID)));
177 array->appendString(
178 SkString(reinterpret_cast<const char*>(&instance), sizeof(SkUUID)));
179 return std::move(array);
180}
181
182// Convert a block of memory to hexadecimal. Input and output pointers will be
183// moved to end of the range.
184static void hexify(const uint8_t** inputPtr, char** outputPtr, int count) {
185 SkASSERT(inputPtr && *inputPtr);
186 SkASSERT(outputPtr && *outputPtr);
187 while (count-- > 0) {
188 uint8_t value = *(*inputPtr)++;
189 *(*outputPtr)++ = SkHexadecimalDigits::gLower[value >> 4];
190 *(*outputPtr)++ = SkHexadecimalDigits::gLower[value & 0xF];
191 }
192}
193
194static SkString uuid_to_string(const SkUUID& uuid) {
195 // 8-4-4-4-12
196 char buffer[36]; // [32 + 4]
197 char* ptr = buffer;
198 const uint8_t* data = uuid.fData;
199 hexify(&data, &ptr, 4);
200 *ptr++ = '-';
201 hexify(&data, &ptr, 2);
202 *ptr++ = '-';
203 hexify(&data, &ptr, 2);
204 *ptr++ = '-';
205 hexify(&data, &ptr, 2);
206 *ptr++ = '-';
207 hexify(&data, &ptr, 6);
208 SkASSERT(ptr == buffer + 36);
209 SkASSERT(data == uuid.fData + 16);
210 return SkString(buffer, 36);
211}
212
213namespace {
214class PDFXMLObject final : public SkPDFObject {
215public:
216 PDFXMLObject(SkString xml) : fXML(std::move(xml)) {}
217 void emitObject(SkWStream* stream) const override {
218 SkPDFDict dict("Metadata");
219 dict.insertName("Subtype", "XML");
220 dict.insertInt("Length", fXML.size());
221 dict.emitObject(stream);
222 static const char streamBegin[] = " stream\n";
223 stream->writeText(streamBegin);
224 // Do not compress this. The standard requires that a
225 // program that does not understand PDF can grep for
226 // "<?xpacket" and extract the entire XML.
227 stream->write(fXML.c_str(), fXML.size());
228 static const char streamEnd[] = "\nendstream";
229 stream->writeText(streamEnd);
230 }
231
232private:
233 const SkString fXML;
234};
235} // namespace
236
237static int count_xml_escape_size(const SkString& input) {
238 int extra = 0;
239 for (size_t i = 0; i < input.size(); ++i) {
240 if (input[i] == '&') {
241 extra += 4; // strlen("&amp;") - strlen("&")
242 } else if (input[i] == '<') {
243 extra += 3; // strlen("&lt;") - strlen("<")
244 }
245 }
246 return extra;
247}
248
249const SkString escape_xml(const SkString& input,
250 const char* before = nullptr,
251 const char* after = nullptr) {
252 if (input.size() == 0) {
253 return input;
254 }
255 // "&" --> "&amp;" and "<" --> "&lt;"
256 // text is assumed to be in UTF-8
257 // all strings are xml content, not attribute values.
258 size_t beforeLen = before ? strlen(before) : 0;
259 size_t afterLen = after ? strlen(after) : 0;
260 int extra = count_xml_escape_size(input);
261 SkString output(input.size() + extra + beforeLen + afterLen);
262 char* out = output.writable_str();
263 if (before) {
264 strncpy(out, before, beforeLen);
265 out += beforeLen;
266 }
267 static const char kAmp[] = "&amp;";
268 static const char kLt[] = "&lt;";
269 for (size_t i = 0; i < input.size(); ++i) {
270 if (input[i] == '&') {
271 memcpy(out, kAmp, strlen(kAmp));
272 out += strlen(kAmp);
273 } else if (input[i] == '<') {
274 memcpy(out, kLt, strlen(kLt));
275 out += strlen(kLt);
276 } else {
277 *out++ = input[i];
278 }
279 }
280 if (after) {
281 strncpy(out, after, afterLen);
282 out += afterLen;
283 }
284 // Validate that we haven't written outside of our string.
285 SkASSERT(out == &output.writable_str()[output.size()]);
286 *out = '\0';
287 return output;
288}
289
290SkPDFIndirectReference SkPDFMetadata::MakeXMPObject(
291 const SkPDF::Metadata& metadata,
292 const SkUUID& doc,
293 const SkUUID& instance,
294 SkPDFDocument* docPtr) {
295 static const char templateString[] =
296 "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
297 "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"\n"
298 " x:xmptk=\"Adobe XMP Core 5.4-c005 78.147326, "
299 "2012/08/23-13:03:03\">\n"
300 "<rdf:RDF "
301 "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
302 "<rdf:Description rdf:about=\"\"\n"
303 " xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n"
304 " xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n"
305 " xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n"
306 " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n"
307 " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
308 "<pdfaid:part>2</pdfaid:part>\n"
309 "<pdfaid:conformance>B</pdfaid:conformance>\n"
310 "%s" // ModifyDate
311 "%s" // CreateDate
312 "%s" // xmp:CreatorTool
313 "<dc:format>application/pdf</dc:format>\n"
314 "%s" // dc:title
315 "%s" // dc:description
316 "%s" // author
317 "%s" // keywords
318 "<xmpMM:DocumentID>uuid:%s</xmpMM:DocumentID>\n"
319 "<xmpMM:InstanceID>uuid:%s</xmpMM:InstanceID>\n"
320 "%s" // pdf:Producer
321 "%s" // pdf:Keywords
322 "</rdf:Description>\n"
323 "</rdf:RDF>\n"
324 "</x:xmpmeta>\n" // Note: the standard suggests 4k of padding.
325 "<?xpacket end=\"w\"?>\n";
326
327 SkString creationDate;
328 SkString modificationDate;
329 if (metadata.fCreation != kZeroTime) {
330 SkString tmp;
331 metadata.fCreation.toISO8601(&tmp);
332 SkASSERT(0 == count_xml_escape_size(tmp));
333 // YYYY-mm-ddTHH:MM:SS[+|-]ZZ:ZZ; no need to escape
334 creationDate = SkStringPrintf("<xmp:CreateDate>%s</xmp:CreateDate>\n",
335 tmp.c_str());
336 }
337 if (metadata.fModified != kZeroTime) {
338 SkString tmp;
339 metadata.fModified.toISO8601(&tmp);
340 SkASSERT(0 == count_xml_escape_size(tmp));
341 modificationDate = SkStringPrintf(
342 "<xmp:ModifyDate>%s</xmp:ModifyDate>\n", tmp.c_str());
343 }
344 SkString title =
345 escape_xml(metadata.fTitle,
346 "<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">",
347 "</rdf:li></rdf:Alt></dc:title>\n");
348 SkString author =
349 escape_xml(metadata.fAuthor, "<dc:creator><rdf:Bag><rdf:li>",
350 "</rdf:li></rdf:Bag></dc:creator>\n");
351 // TODO: in theory, XMP can support multiple authors. Split on a delimiter?
352 SkString subject = escape_xml(
353 metadata.fSubject,
354 "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">",
355 "</rdf:li></rdf:Alt></dc:description>\n");
356 SkString keywords1 =
357 escape_xml(metadata.fKeywords, "<dc:subject><rdf:Bag><rdf:li>",
358 "</rdf:li></rdf:Bag></dc:subject>\n");
359 SkString keywords2 = escape_xml(metadata.fKeywords, "<pdf:Keywords>",
360 "</pdf:Keywords>\n");
361 // TODO: in theory, keywords can be a list too.
362
363 SkString producer = escape_xml(metadata.fProducer, "<pdf:Producer>", "</pdf:Producer>\n");
364
365 SkString creator = escape_xml(metadata.fCreator, "<xmp:CreatorTool>",
366 "</xmp:CreatorTool>\n");
367 SkString documentID = uuid_to_string(doc); // no need to escape
368 SkASSERT(0 == count_xml_escape_size(documentID));
369 SkString instanceID = uuid_to_string(instance);
370 SkASSERT(0 == count_xml_escape_size(instanceID));
371
372
373 auto value = SkStringPrintf(
374 templateString, modificationDate.c_str(), creationDate.c_str(),
375 creator.c_str(), title.c_str(), subject.c_str(), author.c_str(),
376 keywords1.c_str(), documentID.c_str(), instanceID.c_str(),
377 producer.c_str(), keywords2.c_str());
378
379 std::unique_ptr<SkPDFDict> dict = SkPDFMakeDict("Metadata");
380 dict->insertName("Subtype", "XML");
381 return SkPDFStreamOut(std::move(dict),
382 SkMemoryStream::MakeCopy(value.c_str(), value.size()),
383 docPtr, false);
384}
385
386#undef SKPDF_CUSTOM_PRODUCER_KEY
387#undef SKPDF_PRODUCER
388#undef SKPDF_STRING
389#undef SKPDF_STRING_IMPL
390