• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "public/fpdf_attachment.h"
6 
7 #include <memory>
8 #include <utility>
9 
10 #include "constants/stream_dict_common.h"
11 #include "core/fdrm/fx_crypt.h"
12 #include "core/fpdfapi/parser/cpdf_array.h"
13 #include "core/fpdfapi/parser/cpdf_dictionary.h"
14 #include "core/fpdfapi/parser/cpdf_document.h"
15 #include "core/fpdfapi/parser/cpdf_name.h"
16 #include "core/fpdfapi/parser/cpdf_number.h"
17 #include "core/fpdfapi/parser/cpdf_reference.h"
18 #include "core/fpdfapi/parser/cpdf_stream.h"
19 #include "core/fpdfapi/parser/cpdf_string.h"
20 #include "core/fpdfapi/parser/fpdf_parser_decode.h"
21 #include "core/fpdfdoc/cpdf_filespec.h"
22 #include "core/fpdfdoc/cpdf_nametree.h"
23 #include "core/fxcrt/cfx_datetime.h"
24 #include "core/fxcrt/fx_extension.h"
25 #include "core/fxcrt/fx_memory_wrappers.h"
26 #include "fpdfsdk/cpdfsdk_helpers.h"
27 #include "third_party/base/ptr_util.h"
28 
29 namespace {
30 
31 constexpr char kChecksumKey[] = "CheckSum";
32 
CFXByteStringHexDecode(const ByteString & bsHex)33 ByteString CFXByteStringHexDecode(const ByteString& bsHex) {
34   std::unique_ptr<uint8_t, FxFreeDeleter> result;
35   uint32_t size = 0;
36   HexDecode(bsHex.raw_span(), &result, &size);
37   return ByteString(result.get(), size);
38 }
39 
GenerateMD5Base16(const void * contents,const unsigned long len)40 ByteString GenerateMD5Base16(const void* contents, const unsigned long len) {
41   uint8_t digest[16];
42   CRYPT_MD5Generate({static_cast<const uint8_t*>(contents), len}, digest);
43   char buf[32];
44   for (int i = 0; i < 16; ++i)
45     FXSYS_IntToTwoHexChars(digest[i], &buf[i * 2]);
46 
47   return ByteString(buf, 32);
48 }
49 
50 }  // namespace
51 
52 FPDF_EXPORT int FPDF_CALLCONV
FPDFDoc_GetAttachmentCount(FPDF_DOCUMENT document)53 FPDFDoc_GetAttachmentCount(FPDF_DOCUMENT document) {
54   CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
55   if (!pDoc)
56     return 0;
57 
58   return CPDF_NameTree(pDoc, "EmbeddedFiles").GetCount();
59 }
60 
61 FPDF_EXPORT FPDF_ATTACHMENT FPDF_CALLCONV
FPDFDoc_AddAttachment(FPDF_DOCUMENT document,FPDF_WIDESTRING name)62 FPDFDoc_AddAttachment(FPDF_DOCUMENT document, FPDF_WIDESTRING name) {
63   CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
64   if (!pDoc)
65     return nullptr;
66 
67   CPDF_Dictionary* pRoot = pDoc->GetRoot();
68   if (!pRoot)
69     return nullptr;
70 
71   WideString wsName = WideStringFromFPDFWideString(name);
72   if (wsName.IsEmpty())
73     return nullptr;
74 
75   // Retrieve the document's Names dictionary; create it if missing.
76   CPDF_Dictionary* pNames = pRoot->GetDictFor("Names");
77   if (!pNames) {
78     pNames = pDoc->NewIndirect<CPDF_Dictionary>();
79     pRoot->SetNewFor<CPDF_Reference>("Names", pDoc, pNames->GetObjNum());
80   }
81 
82   // Create the EmbeddedFiles dictionary if missing.
83   if (!pNames->GetDictFor("EmbeddedFiles")) {
84     CPDF_Dictionary* pFiles = pDoc->NewIndirect<CPDF_Dictionary>();
85     pFiles->SetNewFor<CPDF_Array>("Names");
86     pNames->SetNewFor<CPDF_Reference>("EmbeddedFiles", pDoc,
87                                       pFiles->GetObjNum());
88   }
89 
90   // Set up the basic entries in the filespec dictionary.
91   CPDF_Dictionary* pFile = pDoc->NewIndirect<CPDF_Dictionary>();
92   pFile->SetNewFor<CPDF_Name>("Type", "Filespec");
93   pFile->SetNewFor<CPDF_String>("UF", wsName);
94   pFile->SetNewFor<CPDF_String>(pdfium::stream::kF, wsName);
95 
96   // Add the new attachment name and filespec into the document's EmbeddedFiles.
97   CPDF_NameTree nameTree(pDoc, "EmbeddedFiles");
98   if (!nameTree.AddValueAndName(pFile->MakeReference(pDoc), wsName)) {
99     return nullptr;
100   }
101 
102   return FPDFAttachmentFromCPDFObject(pFile);
103 }
104 
105 FPDF_EXPORT FPDF_ATTACHMENT FPDF_CALLCONV
FPDFDoc_GetAttachment(FPDF_DOCUMENT document,int index)106 FPDFDoc_GetAttachment(FPDF_DOCUMENT document, int index) {
107   CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
108   if (!pDoc || index < 0)
109     return nullptr;
110 
111   CPDF_NameTree nameTree(pDoc, "EmbeddedFiles");
112   if (static_cast<size_t>(index) >= nameTree.GetCount())
113     return nullptr;
114 
115   WideString csName;
116   return FPDFAttachmentFromCPDFObject(
117       nameTree.LookupValueAndName(index, &csName));
118 }
119 
120 FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV
FPDFDoc_DeleteAttachment(FPDF_DOCUMENT document,int index)121 FPDFDoc_DeleteAttachment(FPDF_DOCUMENT document, int index) {
122   CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
123   if (!pDoc || index < 0)
124     return false;
125 
126   CPDF_NameTree nameTree(pDoc, "EmbeddedFiles");
127   if (static_cast<size_t>(index) >= nameTree.GetCount())
128     return false;
129 
130   return nameTree.DeleteValueAndName(index);
131 }
132 
133 FPDF_EXPORT unsigned long FPDF_CALLCONV
FPDFAttachment_GetName(FPDF_ATTACHMENT attachment,FPDF_WCHAR * buffer,unsigned long buflen)134 FPDFAttachment_GetName(FPDF_ATTACHMENT attachment,
135                        FPDF_WCHAR* buffer,
136                        unsigned long buflen) {
137   CPDF_Object* pFile = CPDFObjectFromFPDFAttachment(attachment);
138   if (!pFile)
139     return 0;
140 
141   return Utf16EncodeMaybeCopyAndReturnLength(CPDF_FileSpec(pFile).GetFileName(),
142                                              buffer, buflen);
143 }
144 
145 FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV
FPDFAttachment_HasKey(FPDF_ATTACHMENT attachment,FPDF_BYTESTRING key)146 FPDFAttachment_HasKey(FPDF_ATTACHMENT attachment, FPDF_BYTESTRING key) {
147   CPDF_Object* pFile = CPDFObjectFromFPDFAttachment(attachment);
148   if (!pFile)
149     return 0;
150 
151   CPDF_Dictionary* pParamsDict = CPDF_FileSpec(pFile).GetParamsDict();
152   return pParamsDict ? pParamsDict->KeyExist(key) : 0;
153 }
154 
155 FPDF_EXPORT FPDF_OBJECT_TYPE FPDF_CALLCONV
FPDFAttachment_GetValueType(FPDF_ATTACHMENT attachment,FPDF_BYTESTRING key)156 FPDFAttachment_GetValueType(FPDF_ATTACHMENT attachment, FPDF_BYTESTRING key) {
157   if (!FPDFAttachment_HasKey(attachment, key))
158     return FPDF_OBJECT_UNKNOWN;
159 
160   CPDF_FileSpec spec(CPDFObjectFromFPDFAttachment(attachment));
161   CPDF_Object* pObj = spec.GetParamsDict()->GetObjectFor(key);
162   return pObj ? pObj->GetType() : FPDF_OBJECT_UNKNOWN;
163 }
164 
165 FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV
FPDFAttachment_SetStringValue(FPDF_ATTACHMENT attachment,FPDF_BYTESTRING key,FPDF_WIDESTRING value)166 FPDFAttachment_SetStringValue(FPDF_ATTACHMENT attachment,
167                               FPDF_BYTESTRING key,
168                               FPDF_WIDESTRING value) {
169   CPDF_Object* pFile = CPDFObjectFromFPDFAttachment(attachment);
170   if (!pFile)
171     return false;
172 
173   CPDF_Dictionary* pParamsDict = CPDF_FileSpec(pFile).GetParamsDict();
174   if (!pParamsDict)
175     return false;
176 
177   ByteString bsKey = key;
178   ByteString bsValue = ByteStringFromFPDFWideString(value);
179   bool bEncodedAsHex = bsKey == kChecksumKey;
180   if (bEncodedAsHex)
181     bsValue = CFXByteStringHexDecode(bsValue);
182 
183   pParamsDict->SetNewFor<CPDF_String>(bsKey, bsValue, bEncodedAsHex);
184   return true;
185 }
186 
187 FPDF_EXPORT unsigned long FPDF_CALLCONV
FPDFAttachment_GetStringValue(FPDF_ATTACHMENT attachment,FPDF_BYTESTRING key,FPDF_WCHAR * buffer,unsigned long buflen)188 FPDFAttachment_GetStringValue(FPDF_ATTACHMENT attachment,
189                               FPDF_BYTESTRING key,
190                               FPDF_WCHAR* buffer,
191                               unsigned long buflen) {
192   CPDF_Object* pFile = CPDFObjectFromFPDFAttachment(attachment);
193   if (!pFile)
194     return 0;
195 
196   CPDF_Dictionary* pParamsDict = CPDF_FileSpec(pFile).GetParamsDict();
197   if (!pParamsDict)
198     return 0;
199 
200   ByteString bsKey = key;
201   WideString value = pParamsDict->GetUnicodeTextFor(bsKey);
202   if (bsKey == kChecksumKey && !value.IsEmpty()) {
203     CPDF_String* stringValue = pParamsDict->GetObjectFor(bsKey)->AsString();
204     if (stringValue->IsHex()) {
205       ByteString encoded = PDF_EncodeString(stringValue->GetString(), true);
206       value = pdfium::MakeRetain<CPDF_String>(nullptr, encoded, false)
207                   ->GetUnicodeText();
208     }
209   }
210 
211   return Utf16EncodeMaybeCopyAndReturnLength(value, buffer, buflen);
212 }
213 
214 FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV
FPDFAttachment_SetFile(FPDF_ATTACHMENT attachment,FPDF_DOCUMENT document,const void * contents,const unsigned long len)215 FPDFAttachment_SetFile(FPDF_ATTACHMENT attachment,
216                        FPDF_DOCUMENT document,
217                        const void* contents,
218                        const unsigned long len) {
219   CPDF_Object* pFile = CPDFObjectFromFPDFAttachment(attachment);
220   CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
221   if (!pFile || !pFile->IsDictionary() || !pDoc || len > INT_MAX)
222     return false;
223 
224   // An empty content must have a zero length.
225   if (!contents && len != 0)
226     return false;
227 
228   // Create a dictionary for the new embedded file stream.
229   auto pFileStreamDict = pdfium::MakeRetain<CPDF_Dictionary>();
230   CPDF_Dictionary* pParamsDict =
231       pFileStreamDict->SetNewFor<CPDF_Dictionary>("Params");
232 
233   // Set the size of the new file in the dictionary.
234   pFileStreamDict->SetNewFor<CPDF_Number>(pdfium::stream::kDL,
235                                           static_cast<int>(len));
236   pParamsDict->SetNewFor<CPDF_Number>("Size", static_cast<int>(len));
237 
238   // Set the creation date of the new attachment in the dictionary.
239   CFX_DateTime dateTime = CFX_DateTime::Now();
240   pParamsDict->SetNewFor<CPDF_String>(
241       "CreationDate",
242       ByteString::Format("D:%d%02d%02d%02d%02d%02d", dateTime.GetYear(),
243                          dateTime.GetMonth(), dateTime.GetDay(),
244                          dateTime.GetHour(), dateTime.GetMinute(),
245                          dateTime.GetSecond()),
246       false);
247 
248   // Set the checksum of the new attachment in the dictionary.
249   pParamsDict->SetNewFor<CPDF_String>(
250       kChecksumKey, CFXByteStringHexDecode(GenerateMD5Base16(contents, len)),
251       true);
252 
253   // Create the file stream and have the filespec dictionary link to it.
254   std::unique_ptr<uint8_t, FxFreeDeleter> stream(FX_Alloc(uint8_t, len));
255   memcpy(stream.get(), contents, len);
256   CPDF_Stream* pFileStream = pDoc->NewIndirect<CPDF_Stream>(
257       std::move(stream), len, std::move(pFileStreamDict));
258   CPDF_Dictionary* pEFDict =
259       pFile->AsDictionary()->SetNewFor<CPDF_Dictionary>("EF");
260   pEFDict->SetNewFor<CPDF_Reference>("F", pDoc, pFileStream->GetObjNum());
261   return true;
262 }
263 
264 FPDF_EXPORT unsigned long FPDF_CALLCONV
FPDFAttachment_GetFile(FPDF_ATTACHMENT attachment,void * buffer,unsigned long buflen)265 FPDFAttachment_GetFile(FPDF_ATTACHMENT attachment,
266                        void* buffer,
267                        unsigned long buflen) {
268   CPDF_Object* pFile = CPDFObjectFromFPDFAttachment(attachment);
269   if (!pFile)
270     return 0;
271 
272   CPDF_Stream* pFileStream = CPDF_FileSpec(pFile).GetFileStream();
273   if (!pFileStream)
274     return 0;
275 
276   return DecodeStreamMaybeCopyAndReturnLength(pFileStream, buffer, buflen);
277 }
278