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