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/base/SkTo.h"
11 #include "src/base/SkUTF.h"
12 #include "src/base/SkUtils.h"
13 #include "src/core/SkMD5.h"
14 #include "src/pdf/SkPDFTypes.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
45 namespace {
46 static const struct {
47 const char* const key;
48 SkString SkPDF::Metadata::*const valuePtr;
49 } gMetadataKeys[] = {
50 {"Title", &SkPDF::Metadata::fTitle},
51 {"Author", &SkPDF::Metadata::fAuthor},
52 {"Subject", &SkPDF::Metadata::fSubject},
53 {"Keywords", &SkPDF::Metadata::fKeywords},
54 {"Creator", &SkPDF::Metadata::fCreator},
55 {"Producer", &SkPDF::Metadata::fProducer},
56 };
57 } // namespace
58
MakeDocumentInformationDict(const SkPDF::Metadata & metadata)59 std::unique_ptr<SkPDFObject> SkPDFMetadata::MakeDocumentInformationDict(
60 const SkPDF::Metadata& metadata) {
61 auto dict = SkPDFMakeDict();
62 for (const auto keyValuePtr : gMetadataKeys) {
63 const SkString& value = metadata.*(keyValuePtr.valuePtr);
64 if (value.size() > 0) {
65 dict->insertTextString(keyValuePtr.key, value);
66 }
67 }
68 if (metadata.fCreation != kZeroTime) {
69 dict->insertTextString("CreationDate", pdf_date(metadata.fCreation));
70 }
71 if (metadata.fModified != kZeroTime) {
72 dict->insertTextString("ModDate", pdf_date(metadata.fModified));
73 }
74 return std::move(dict);
75 }
76
CreateUUID(const SkPDF::Metadata & metadata)77 SkUUID SkPDFMetadata::CreateUUID(const SkPDF::Metadata& metadata) {
78 // The main requirement is for the UUID to be unique; the exact
79 // format of the data that will be hashed is not important.
80 SkMD5 md5;
81 const char uuidNamespace[] = "org.skia.pdf\n";
82 md5.writeText(uuidNamespace);
83 double msec = SkTime::GetMSecs();
84 md5.write(&msec, sizeof(msec));
85 SkTime::DateTime dateTime;
86 SkTime::GetDateTime(&dateTime);
87 md5.write(&dateTime, sizeof(dateTime));
88 md5.write(&metadata.fCreation, sizeof(metadata.fCreation));
89 md5.write(&metadata.fModified, sizeof(metadata.fModified));
90
91 for (const auto keyValuePtr : gMetadataKeys) {
92 md5.writeText(keyValuePtr.key);
93 md5.write("\037", 1);
94 const SkString& value = metadata.*(keyValuePtr.valuePtr);
95 md5.write(value.c_str(), value.size());
96 md5.write("\036", 1);
97 }
98 SkMD5::Digest digest = md5.finish();
99 // See RFC 4122, page 6-7.
100 digest.data[6] = (digest.data[6] & 0x0F) | 0x30;
101 digest.data[8] = (digest.data[6] & 0x3F) | 0x80;
102 static_assert(sizeof(digest) == sizeof(SkUUID), "uuid_size");
103 SkUUID uuid;
104 memcpy((void*)&uuid, &digest, sizeof(digest));
105 return uuid;
106 }
107
MakePdfId(const SkUUID & doc,const SkUUID & instance)108 std::unique_ptr<SkPDFObject> SkPDFMetadata::MakePdfId(const SkUUID& doc, const SkUUID& instance) {
109 // /ID [ <81b14aafa313db63dbd6f981e49f94f4>
110 // <81b14aafa313db63dbd6f981e49f94f4> ]
111 auto array = SkPDFMakeArray();
112 static_assert(sizeof(SkUUID) == 16, "uuid_size");
113 array->appendByteString(SkString(reinterpret_cast<const char*>(&doc ), sizeof(SkUUID)));
114 array->appendByteString(SkString(reinterpret_cast<const char*>(&instance), sizeof(SkUUID)));
115 return std::move(array);
116 }
117
118 // Convert a block of memory to hexadecimal. Input and output pointers will be
119 // moved to end of the range.
hexify(const uint8_t ** inputPtr,char ** outputPtr,int count)120 static void hexify(const uint8_t** inputPtr, char** outputPtr, int count) {
121 SkASSERT(inputPtr && *inputPtr);
122 SkASSERT(outputPtr && *outputPtr);
123 while (count-- > 0) {
124 uint8_t value = *(*inputPtr)++;
125 *(*outputPtr)++ = SkHexadecimalDigits::gLower[value >> 4];
126 *(*outputPtr)++ = SkHexadecimalDigits::gLower[value & 0xF];
127 }
128 }
129
uuid_to_string(const SkUUID & uuid)130 static SkString uuid_to_string(const SkUUID& uuid) {
131 // 8-4-4-4-12
132 char buffer[36]; // [32 + 4]
133 char* ptr = buffer;
134 const uint8_t* data = uuid.fData;
135 hexify(&data, &ptr, 4);
136 *ptr++ = '-';
137 hexify(&data, &ptr, 2);
138 *ptr++ = '-';
139 hexify(&data, &ptr, 2);
140 *ptr++ = '-';
141 hexify(&data, &ptr, 2);
142 *ptr++ = '-';
143 hexify(&data, &ptr, 6);
144 SkASSERT(ptr == buffer + 36);
145 SkASSERT(data == uuid.fData + 16);
146 return SkString(buffer, 36);
147 }
148
149 namespace {
150 class PDFXMLObject final : public SkPDFObject {
151 public:
PDFXMLObject(SkString xml)152 PDFXMLObject(SkString xml) : fXML(std::move(xml)) {}
emitObject(SkWStream * stream) const153 void emitObject(SkWStream* stream) const override {
154 SkPDFDict dict("Metadata");
155 dict.insertName("Subtype", "XML");
156 dict.insertInt("Length", fXML.size());
157 dict.emitObject(stream);
158 static const char streamBegin[] = " stream\n";
159 stream->writeText(streamBegin);
160 // Do not compress this. The standard requires that a
161 // program that does not understand PDF can grep for
162 // "<?xpacket" and extract the entire XML.
163 stream->write(fXML.c_str(), fXML.size());
164 static const char streamEnd[] = "\nendstream";
165 stream->writeText(streamEnd);
166 }
167
168 private:
169 const SkString fXML;
170 };
171 } // namespace
172
count_xml_escape_size(const SkString & input)173 static int count_xml_escape_size(const SkString& input) {
174 int extra = 0;
175 for (size_t i = 0; i < input.size(); ++i) {
176 if (input[i] == '&') {
177 extra += 4; // strlen("&") - strlen("&")
178 } else if (input[i] == '<') {
179 extra += 3; // strlen("<") - strlen("<")
180 }
181 }
182 return extra;
183 }
184
escape_xml(const SkString & input,const char * before=nullptr,const char * after=nullptr)185 SkString escape_xml(const SkString& input,
186 const char* before = nullptr,
187 const char* after = nullptr) {
188 if (input.size() == 0) {
189 return input;
190 }
191 // "&" --> "&" and "<" --> "<"
192 // text is assumed to be in UTF-8
193 // all strings are xml content, not attribute values.
194 size_t beforeLen = before ? strlen(before) : 0;
195 size_t afterLen = after ? strlen(after) : 0;
196 int extra = count_xml_escape_size(input);
197 SkString output(input.size() + extra + beforeLen + afterLen);
198 char* out = output.data();
199 if (before) {
200 strncpy(out, before, beforeLen);
201 out += beforeLen;
202 }
203 static const char kAmp[] = "&";
204 static const char kLt[] = "<";
205 for (size_t i = 0; i < input.size(); ++i) {
206 if (input[i] == '&') {
207 memcpy(out, kAmp, strlen(kAmp));
208 out += strlen(kAmp);
209 } else if (input[i] == '<') {
210 memcpy(out, kLt, strlen(kLt));
211 out += strlen(kLt);
212 } else {
213 *out++ = input[i];
214 }
215 }
216 if (after) {
217 strncpy(out, after, afterLen);
218 out += afterLen;
219 }
220 // Validate that we haven't written outside of our string.
221 SkASSERT(out == &output.data()[output.size()]);
222 *out = '\0';
223 return output;
224 }
225
MakeXMPObject(const SkPDF::Metadata & metadata,const SkUUID & doc,const SkUUID & instance,SkPDFDocument * docPtr)226 SkPDFIndirectReference SkPDFMetadata::MakeXMPObject(
227 const SkPDF::Metadata& metadata,
228 const SkUUID& doc,
229 const SkUUID& instance,
230 SkPDFDocument* docPtr) {
231 static const char templateString[] =
232 "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
233 "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"\n"
234 " x:xmptk=\"Adobe XMP Core 5.4-c005 78.147326, "
235 "2012/08/23-13:03:03\">\n"
236 "<rdf:RDF "
237 "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
238 "<rdf:Description rdf:about=\"\"\n"
239 " xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n"
240 " xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n"
241 " xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n"
242 " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n"
243 " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
244 "<pdfaid:part>2</pdfaid:part>\n"
245 "<pdfaid:conformance>B</pdfaid:conformance>\n"
246 "%s" // ModifyDate
247 "%s" // CreateDate
248 "%s" // xmp:CreatorTool
249 "<dc:format>application/pdf</dc:format>\n"
250 "%s" // dc:title
251 "%s" // dc:description
252 "%s" // author
253 "%s" // keywords
254 "<xmpMM:DocumentID>uuid:%s</xmpMM:DocumentID>\n"
255 "<xmpMM:InstanceID>uuid:%s</xmpMM:InstanceID>\n"
256 "%s" // pdf:Producer
257 "%s" // pdf:Keywords
258 "</rdf:Description>\n"
259 "</rdf:RDF>\n"
260 "</x:xmpmeta>\n" // Note: the standard suggests 4k of padding.
261 "<?xpacket end=\"w\"?>\n";
262
263 SkString creationDate;
264 SkString modificationDate;
265 if (metadata.fCreation != kZeroTime) {
266 SkString tmp;
267 metadata.fCreation.toISO8601(&tmp);
268 SkASSERT(0 == count_xml_escape_size(tmp));
269 // YYYY-mm-ddTHH:MM:SS[+|-]ZZ:ZZ; no need to escape
270 creationDate = SkStringPrintf("<xmp:CreateDate>%s</xmp:CreateDate>\n",
271 tmp.c_str());
272 }
273 if (metadata.fModified != kZeroTime) {
274 SkString tmp;
275 metadata.fModified.toISO8601(&tmp);
276 SkASSERT(0 == count_xml_escape_size(tmp));
277 modificationDate = SkStringPrintf(
278 "<xmp:ModifyDate>%s</xmp:ModifyDate>\n", tmp.c_str());
279 }
280 SkString title =
281 escape_xml(metadata.fTitle,
282 "<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">",
283 "</rdf:li></rdf:Alt></dc:title>\n");
284 SkString author =
285 escape_xml(metadata.fAuthor, "<dc:creator><rdf:Seq><rdf:li>",
286 "</rdf:li></rdf:Seq></dc:creator>\n");
287 // TODO: in theory, XMP can support multiple authors. Split on a delimiter?
288 SkString subject = escape_xml(
289 metadata.fSubject,
290 "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">",
291 "</rdf:li></rdf:Alt></dc:description>\n");
292 SkString keywords1 =
293 escape_xml(metadata.fKeywords, "<dc:subject><rdf:Bag><rdf:li>",
294 "</rdf:li></rdf:Bag></dc:subject>\n");
295 SkString keywords2 = escape_xml(metadata.fKeywords, "<pdf:Keywords>",
296 "</pdf:Keywords>\n");
297 // TODO: in theory, keywords can be a list too.
298
299 SkString producer = escape_xml(metadata.fProducer, "<pdf:Producer>", "</pdf:Producer>\n");
300
301 SkString creator = escape_xml(metadata.fCreator, "<xmp:CreatorTool>",
302 "</xmp:CreatorTool>\n");
303 SkString documentID = uuid_to_string(doc); // no need to escape
304 SkASSERT(0 == count_xml_escape_size(documentID));
305 SkString instanceID = uuid_to_string(instance);
306 SkASSERT(0 == count_xml_escape_size(instanceID));
307
308
309 auto value = SkStringPrintf(
310 templateString, modificationDate.c_str(), creationDate.c_str(),
311 creator.c_str(), title.c_str(), subject.c_str(), author.c_str(),
312 keywords1.c_str(), documentID.c_str(), instanceID.c_str(),
313 producer.c_str(), keywords2.c_str());
314
315 std::unique_ptr<SkPDFDict> dict = SkPDFMakeDict("Metadata");
316 dict->insertName("Subtype", "XML");
317 return SkPDFStreamOut(std::move(dict),
318 SkMemoryStream::MakeCopy(value.c_str(), value.size()),
319 docPtr, SkPDFSteamCompressionEnabled::No);
320 }
321
322 #undef SKPDF_CUSTOM_PRODUCER_KEY
323 #undef SKPDF_PRODUCER
324 #undef SKPDF_STRING
325 #undef SKPDF_STRING_IMPL
326