Debian Codegraph @

src/App/PropertyFile.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2008 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <Base/Console.h>
25 #include <Base/PyObjectBase.h>
26 #include <Base/Reader.h>
27 #include <Base/Stream.h>
28 #include <Base/Writer.h>
29 #include <Base/Uuid.h>
30 #include <Base/Tools.h>
31
32 #include "PropertyFile.h"
33 #include "Document.h"
34 #include "DocumentObject.h"
35 #include "PropertyContainer.h"
36
37
38 using namespace App;
39 using namespace Base;
40 using namespace std;
41
42
43 namespace
44 {
45 /**
46 * @brief Check that an embedded file name from a restored document is a plain basename.
47 *
48 * PropertyFileIncluded::Save() always stores basenames (via FileInfo::fileName()), so a
49 * document that carries a name with any directory component, an absolute path, or a
50 * <tt>.</tt>/<tt>..</tt> reference is malicious.
51 *
52 * @param[in] name The file name taken from the document XML.
53 * @return @c true if @p name is a safe basename, @c false if it must be rejected.
54 */
55 bool isPlainFileName(const std::string& name)
56 {
57 if (name == "." || name == "..") {
58 return false;
59 }
60 return Base::FileInfo(name).fileName() == name;
61 }
62 } // namespace
63
64 //**************************************************************************
65 // PropertyFileIncluded
66 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
67
68 TYPESYSTEM_SOURCE(App::PropertyFileIncluded, App::Property)
69
70
71 PropertyFileIncluded::PropertyFileIncluded() = default;
72
73 PropertyFileIncluded::~PropertyFileIncluded()
74 {
75 // clean up
76 if (!_cValue.empty()) {
77 Base::FileInfo file(_cValue.c_str());
78 file.setPermissions(Base::FileInfo::ReadWrite);
79 file.deleteFile();
80 }
81 }
82
83 void PropertyFileIncluded::aboutToSetValue()
84 {
85 // This is a trick to check in Copy() if it is called
86 // directly from outside or by the Undo/Redo mechanism.
87 // In the latter case it is sufficient to rename the file
88 // because another file will be assigned afterwards.
89 // If Copy() is directly called (e.g. to copy the file to
90 // another document) a copy of the file needs to be created.
91 // This copy will be deleted again in the class destructor.
92 this->StatusBits.set(10);
93 Property::aboutToSetValue();
94 this->StatusBits.reset(10);
95 }
96
97 std::string PropertyFileIncluded::getDocTransientPath() const
98 {
99 std::string path;
100 PropertyContainer* co = getContainer();
101 if (co->isDerivedFrom<DocumentObject>()) {
102 path = static_cast<DocumentObject*>(co)->getDocument()->TransientDir.getValue();
103 std::replace(path.begin(), path.end(), '\\', '/');
104 }
105 return path;
106 }
107
108 std::string PropertyFileIncluded::getUniqueFileName(const std::string& path,
109 const std::string& filename) const
110 {
111 Base::Uuid uuid;
112 Base::FileInfo fi(path + "/" + filename);
113 while (fi.exists()) {
114 fi.setFile(path + "/" + filename + "." + uuid.getValue());
115 }
116
117 return fi.filePath();
118 }
119
120 std::string PropertyFileIncluded::getExchangeTempFile() const
121 {
122 return Base::FileInfo::getTempFileName(Base::FileInfo(getValue()).fileName().c_str(),
123 getDocTransientPath().c_str());
124 }
125
126 std::string PropertyFileIncluded::getOriginalFileName() const
127 {
128 return _OriginalName;
129 }
130
131 void PropertyFileIncluded::setValue(const char* sFile, const char* sName)
132 {
133 if (!Base::Tools::isNullOrEmpty(sFile)) {
134 if (_cValue == sFile) {
135 throw Base::FileSystemError("Not possible to set the same file!");
136 }
137
138 // keep the path to the original file
139 _OriginalName = sFile;
140
141 std::string pathTrans = getDocTransientPath();
142 Base::FileInfo file(sFile);
143 std::string path = file.dirPath();
144 if (!file.exists()) {
145 std::stringstream str;
146 str << "File " << file.filePath() << " does not exist.";
147 throw Base::FileSystemError(str.str());
148 }
149
150 aboutToSetValue(); // undo/redo by moving the file away with temp name
151
152 // remove old file (if not moved by undo)
153 Base::FileInfo value(_cValue);
154 std::string pathAct = value.dirPath();
155 if (value.exists()) {
156 value.setPermissions(Base::FileInfo::ReadWrite);
157 value.deleteFile();
158 }
159
160 // if a special name given, use this instead
161 if (sName) {
162 Base::FileInfo fi(pathTrans + "/" + sName);
163 if (fi.exists()) {
164 // if a file with this name already exists search for a new one
165 std::string dir = pathTrans;
166 std::string fnp = fi.fileNamePure();
167 std::string ext = fi.extension();
168 int i = 0;
169 do {
170 i++;
171 std::stringstream str;
172 str << dir << "/" << fnp << i;
173 if (!ext.empty()) {
174 str << "." << ext;
175 }
176 fi.setFile(str.str());
177 } while (fi.exists());
178
179 _cValue = fi.filePath();
180 _BaseFileName = fi.fileName();
181 }
182 else {
183 _cValue = pathTrans + "/" + sName;
184 _BaseFileName = sName;
185 }
186 }
187 else if (value.fileName().empty()) {
188 _cValue = pathTrans + "/" + file.fileName();
189 _BaseFileName = file.fileName();
190 }
191
192 // The following applies only on files that are inside the transient
193 // directory:
194 // When a file is read-only it is supposed to be assigned to a
195 // PropertyFileIncluded instance. In this case we must copy the
196 // file because otherwise the above instance loses its data.
197 // If the file is writable it is supposed to be of free use and
198 // it can be simply renamed.
199
200 // if the file is already in transient dir of the document, just use it
201 if (path == pathTrans && file.isWritable()) {
202 bool done = file.renameFile(_cValue.c_str());
203 if (!done) {
204 std::stringstream str;
205 str << "Cannot rename file " << file.filePath() << " to " << _cValue;
206 throw Base::FileSystemError(str.str());
207 }
208
209 // make the file read-only
210 Base::FileInfo dst(_cValue);
211 dst.setPermissions(Base::FileInfo::ReadOnly);
212 }
213 // otherwise copy from origin location
214 else {
215 // if file already exists in transient dir make a new unique name
216 Base::FileInfo fi(_cValue);
217 if (fi.exists()) {
218 // if a file with this name already exists search for a new one
219 std::string dir = fi.dirPath();
220 std::string fnp = fi.fileNamePure();
221 std::string ext = fi.extension();
222 int i = 0;
223 do {
224 i++;
225 std::stringstream str;
226 str << dir << "/" << fnp << i;
227 if (!ext.empty()) {
228 str << "." << ext;
229 }
230 fi.setFile(str.str());
231 } while (fi.exists());
232
233 _cValue = fi.filePath();
234 _BaseFileName = fi.fileName();
235 }
236
237 bool done = file.copyTo(_cValue.c_str());
238 if (!done) {
239 std::stringstream str;
240 str << "Cannot copy file from " << file.filePath() << " to " << _cValue;
241 throw Base::FileSystemError(str.str());
242 }
243
244 // make the file read-only
245 Base::FileInfo dst(_cValue);
246 dst.setPermissions(Base::FileInfo::ReadOnly);
247 }
248
249 hasSetValue();
250 }
251 }
252
253 const char* PropertyFileIncluded::getValue() const
254 {
255 return _cValue.c_str();
256 }
257
258 PyObject* PropertyFileIncluded::getPyObject()
259 {
260 PyObject* p = PyUnicode_DecodeUTF8(_cValue.c_str(), _cValue.size(), nullptr);
261 if (!p) {
262 throw Base::UnicodeError("PropertyFileIncluded: UTF-8 conversion failure");
263 }
264 return p;
265 }
266
267 namespace App
268 {
269 const char* getNameFromFile(PyObject* value)
270 {
271 const char* string = nullptr;
272 PyObject* oname = PyObject_GetAttrString(value, "name");
273 if (oname) {
274 if (PyUnicode_Check(oname)) {
275 string = PyUnicode_AsUTF8(oname);
276 }
277 else if (PyBytes_Check(oname)) {
278 string = PyBytes_AsString(oname);
279 }
280 Py_DECREF(oname);
281 }
282
283 if (!string) {
284 throw Base::TypeError("Unable to get filename");
285 }
286 return string;
287 }
288
289
290 bool isIOFile(PyObject* file)
291 {
292 PyObject* io = PyImport_ImportModule("io");
293 PyObject* IOBase_Class = PyObject_GetAttrString(io, "IOBase");
294 bool isFile = PyObject_IsInstance(file, IOBase_Class);
295 Py_DECREF(IOBase_Class);
296 Py_DECREF(io);
297 return isFile;
298 }
299 } // namespace App
300
301 void PropertyFileIncluded::setPyObject(PyObject* value)
302 {
303 if (PyUnicode_Check(value)) {
304 std::string string = PyUnicode_AsUTF8(value);
305 setValue(string.c_str());
306 }
307 else if (PyBytes_Check(value)) {
308 std::string string = PyBytes_AsString(value);
309 setValue(string.c_str());
310 }
311 else if (isIOFile(value)) {
312 std::string string = getNameFromFile(value);
313 setValue(string.c_str());
314 }
315 else if (PyTuple_Check(value)) {
316 if (PyTuple_Size(value) != 2) {
317 throw Base::TypeError("Tuple needs size of (filePath,newFileName)");
318 }
319 PyObject* file = PyTuple_GetItem(value, 0);
320 PyObject* name = PyTuple_GetItem(value, 1);
321
322 // decoding file
323 std::string fileStr;
324 if (PyUnicode_Check(file)) {
325 fileStr = PyUnicode_AsUTF8(file);
326 }
327 else if (PyBytes_Check(file)) {
328 fileStr = PyBytes_AsString(file);
329 }
330 else if (isIOFile(value)) {
331 fileStr = getNameFromFile(file);
332 }
333 else {
334 std::string error = std::string("First item in tuple must be a file or string, not ");
335 error += file->ob_type->tp_name;
336 throw Base::TypeError(error);
337 }
338
339 // decoding name
340 std::string nameStr;
341 if (PyUnicode_Check(name)) {
342 nameStr = PyUnicode_AsUTF8(name);
343 }
344 else if (PyBytes_Check(name)) {
345 nameStr = PyBytes_AsString(name);
346 }
347 else if (isIOFile(value)) {
348 nameStr = getNameFromFile(name);
349 }
350 else {
351 std::string error = std::string("Second item in tuple must be a string, not ");
352 error += name->ob_type->tp_name;
353 throw Base::TypeError(error);
354 }
355
356 setValue(fileStr.c_str(), nameStr.c_str());
357 }
358 else if (PyDict_Check(value)) {
359 Py::Dict dict(value);
360 if (dict.hasKey("filter")) {
361 setFilter(Py::String(dict.getItem("filter")));
362 }
363 if (dict.hasKey("filename")) {
364 std::string string = static_cast<std::string>(Py::String(dict.getItem("filename")));
365 setValue(string.c_str());
366 }
367 }
368 else {
369 std::string error = std::string("Type must be string or file, not ");
370 error += value->ob_type->tp_name;
371 throw Base::TypeError(error);
372 }
373 }
374
375 void PropertyFileIncluded::Save(Base::Writer& writer) const
376 {
377 // when saving a document under a new file name the transient directory
378 // name changes and thus the stored file name doesn't work any more.
379 if (!_cValue.empty() && !Base::FileInfo(_cValue).exists()) {
380 Base::FileInfo fi(getDocTransientPath() + "/" + _BaseFileName);
381 if (fi.exists()) {
382 _cValue = fi.filePath();
383 }
384 }
385
386 if (writer.isForceXML()) {
387 if (!_cValue.empty()) {
388 Base::FileInfo file(_cValue.c_str());
389 writer.Stream() << writer.ind() << "<FileIncluded data=\"" << file.fileName() << "\">"
390 << std::endl;
391 // write the file in the XML stream
392 writer.incInd();
393 writer.insertBinFile(_cValue.c_str());
394 writer.decInd();
395 writer.Stream() << writer.ind() << "</FileIncluded>" << endl;
396 }
397 else {
398 writer.Stream() << writer.ind() << "<FileIncluded data=\"\"/>" << std::endl;
399 }
400 }
401 else {
402 // instead initiate an extra file
403 if (!_cValue.empty()) {
404 Base::FileInfo file(_cValue.c_str());
405 std::string filename = writer.addFile(file.fileName().c_str(), this);
406 filename = encodeAttribute(filename);
407 writer.Stream() << writer.ind() << "<FileIncluded file=\"" << filename << "\"/>"
408 << std::endl;
409 }
410 else {
411 writer.Stream() << writer.ind() << "<FileIncluded file=\"\"/>" << std::endl;
412 }
413 }
414 }
415
416 void PropertyFileIncluded::Restore(Base::XMLReader& reader)
417 {
418 reader.readElement("FileIncluded");
419 if (reader.hasAttribute("file")) {
420 string file(reader.getAttribute<const char*>("file"));
421 if (!file.empty()) {
422 if (!isPlainFileName(file)) {
423 throw Base::FileException(
424 "PropertyFileIncluded::Restore(): rejected unsafe embedded file name");
425 }
426 // initiate a file read
427 reader.addFile(file.c_str(), this);
428 // is in the document transient path
429 aboutToSetValue();
430 _cValue = getDocTransientPath() + "/" + file;
431 _BaseFileName = file;
432 hasSetValue();
433 }
434 }
435 // section is XML stream
436 else if (reader.hasAttribute("data")) {
437 string file(reader.getAttribute<const char*>("data"));
438 if (!file.empty()) {
439 if (!isPlainFileName(file)) {
440 throw Base::FileException(
441 "PropertyFileIncluded::Restore(): rejected unsafe embedded file name");
442 }
443 // is in the document transient path
444 aboutToSetValue();
445 _cValue = getDocTransientPath() + "/" + file;
446 reader.readBinFile(_cValue.c_str());
447 reader.readEndElement("FileIncluded");
448 _BaseFileName = file;
449 // set read-only after restoring the file
450 Base::FileInfo fi(_cValue.c_str());
451 fi.setPermissions(Base::FileInfo::ReadOnly);
452 hasSetValue();
453 }
454 }
455 }
456
457 void PropertyFileIncluded::SaveDocFile(Base::Writer& writer) const
458 {
459 Base::ifstream from(Base::FileInfo(_cValue.c_str()), std::ios::in | std::ios::binary);
460 if (!from) {
461 std::stringstream str;
462 str << "PropertyFileIncluded::SaveDocFile(): "
463 << "File '" << _cValue << "' in transient directory doesn't exist.";
464 throw Base::FileSystemError(str.str());
465 }
466
467 // copy plain data
468 unsigned char c;
469 std::ostream& to = writer.Stream();
470 while (from.get((char&)c)) {
471 to.put((char)c);
472 }
473 }
474
475 void PropertyFileIncluded::RestoreDocFile(Base::Reader& reader)
476 {
477 Base::FileInfo fi(_cValue.c_str());
478 if (fi.exists() && !fi.isWritable()) {
479 // This happens when an object is being restored and tries to reference the
480 // same file of another object (e.g. for copy&paste of objects inside the same document).
481 return;
482 }
483 Base::ofstream to(fi, std::ios::out | std::ios::binary);
484 if (!to) {
485 std::stringstream str;
486 str << "PropertyFileIncluded::RestoreDocFile(): "
487 << "File '" << _cValue << "' in transient directory cannot be created.";
488 throw Base::FileSystemError(str.str());
489 }
490
491 // copy plain data
492 aboutToSetValue();
493 unsigned char c;
494 while (reader.get((char&)c)) {
495 to.put((char)c);
496 }
497 to.close();
498
499 // set read-only after restoring the file
500 fi.setPermissions(Base::FileInfo::ReadOnly);
501 hasSetValue();
502 }
503
504 Property* PropertyFileIncluded::Copy() const
505 {
506 std::unique_ptr<PropertyFileIncluded> prop(new PropertyFileIncluded());
507
508 // remember the base name
509 prop->_BaseFileName = _BaseFileName;
510
511 Base::FileInfo file(_cValue);
512 if (file.exists()) {
513 // create a new name in the document transient directory
514 Base::FileInfo newName(getUniqueFileName(file.dirPath(), file.fileName()));
515 if (this->StatusBits.test(10)) {
516 // rename the file
517 bool done = file.renameFile(newName.filePath().c_str());
518 if (!done) {
519 std::stringstream str;
520 str << "PropertyFileIncluded::Copy(): "
521 << "Renaming the file '" << file.filePath() << "' to '" << newName.filePath()
522 << "' failed.";
523 throw Base::FileSystemError(str.str());
524 }
525 }
526 else {
527 // copy the file
528 bool done = file.copyTo(newName.filePath().c_str());
529 if (!done) {
530 std::stringstream str;
531 str << "PropertyFileIncluded::Copy(): "
532 << "Copying the file '" << file.filePath() << "' to '" << newName.filePath()
533 << "' failed.";
534 throw Base::FileSystemError(str.str());
535 }
536 }
537
538 // remember the new name for the Undo
539 Base::Console().log("Copy '%s' to '%s'\n", _cValue.c_str(), newName.filePath().c_str());
540 prop->_cValue = newName.filePath().c_str();
541
542 // make backup files writable to avoid copying them again on undo/redo
543 newName.setPermissions(Base::FileInfo::ReadWrite);
544 }
545
546 return prop.release();
547 }
548
549 void PropertyFileIncluded::Paste(const Property& from)
550 {
551 aboutToSetValue();
552 const PropertyFileIncluded& prop = dynamic_cast<const PropertyFileIncluded&>(from);
553 // make sure that source and destination file are different
554 if (_cValue != prop._cValue) {
555 // delete old file (if still there)
556 Base::FileInfo fi(_cValue);
557 fi.setPermissions(Base::FileInfo::ReadWrite);
558 fi.deleteFile();
559
560 // get path to destination which can be the transient directory
561 // of another document
562 std::string pathTrans = getDocTransientPath();
563 Base::FileInfo fiSrc(prop._cValue);
564 Base::FileInfo fiDst(pathTrans + "/" + prop._BaseFileName);
565 std::string path = fiSrc.dirPath();
566
567 if (fiSrc.exists()) {
568 fiDst.setFile(getUniqueFileName(fiDst.dirPath(), fiDst.fileName()));
569
570 // if the file is already in transient dir of the document, just use it
571 if (path == pathTrans) {
572 if (!fiSrc.renameFile(fiDst.filePath().c_str())) {
573 std::stringstream str;
574 str << "PropertyFileIncluded::Paste(): "
575 << "Renaming the file '" << fiSrc.filePath() << "' to '" << fiDst.filePath()
576 << "' failed.";
577 throw Base::FileSystemError(str.str());
578 }
579 }
580 else {
581 if (!fiSrc.copyTo(fiDst.filePath().c_str())) {
582 std::stringstream str;
583 str << "PropertyFileIncluded::Paste(): "
584 << "Copying the file '" << fiSrc.filePath() << "' to '" << fiDst.filePath()
585 << "' failed.";
586 throw Base::FileSystemError(str.str());
587 }
588 }
589
590 // set the file again read-only
591 fiDst.setPermissions(Base::FileInfo::ReadOnly);
592 _cValue = fiDst.filePath();
593 }
594 else {
595 _cValue.clear();
596 }
597
598 // set the base name
599 _BaseFileName = prop._BaseFileName;
600 }
601 hasSetValue();
602 }
603
604 unsigned int PropertyFileIncluded::getMemSize() const
605 {
606 unsigned int mem = Property::getMemSize();
607 mem += _cValue.size();
608 mem += _BaseFileName.size();
609 return mem;
610 }
611
612 void PropertyFileIncluded::setFilter(std::string filter)
613 {
614 m_filter = std::move(filter);
615 }
616
617 std::string PropertyFileIncluded::getFilter() const
618 {
619 return m_filter;
620 }
621
622 //**************************************************************************
623 // PropertyFile
624 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
625
626 TYPESYSTEM_SOURCE(App::PropertyFile, App::PropertyString)
627
628 PropertyFile::PropertyFile()
629 {
630 m_filter = "";
631 }
632
633 PropertyFile::~PropertyFile() = default;
634
635 void PropertyFile::setFilter(const std::string f)
636 {
637 m_filter = f;
638 }
639
640 std::string PropertyFile::getFilter() const
641 {
642 return m_filter;
643 }
644
645 void PropertyFile::setPyObject(PyObject* value)
646 {
647 if (PyDict_Check(value)) {
648 Py::Dict dict(value);
649 if (dict.hasKey("filter")) {
650 setFilter(Py::String(dict.getItem("filter")));
651 }
652 if (dict.hasKey("filename")) {
653 std::string string = static_cast<std::string>(Py::String(dict.getItem("filename")));
654 setValue(string.c_str());
655 }
656 }
657 else {
658 PropertyString::setPyObject(value);
659 }
660 }