archive.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "platform.h"
  15. #include "jlib.hpp"
  16. #include "jio.hpp"
  17. #include "jmutex.hpp"
  18. #include "jfile.hpp"
  19. #include "jlog.hpp"
  20. #include "jregexp.hpp"
  21. #include "archive.hpp"
  22. #include <sys/stat.h>
  23. #include <archive.h>
  24. #include <archive_entry.h>
  25. /*
  26. * Direct access to files in zip archives (and other libarchive-supported formats), without needing to extract them first
  27. * Installs hooks into createIFile, spotting filenames of the form /my/directory/myfile.zip/{password}/path/within/archive
  28. */
  29. #define ARCHIVE_SIGNATURE "[.]{zip|tar|tar[.]gz|tgz}{$|"PATHSEPSTR"}"
  30. static RegExpr *signature;
  31. static SpinLock *lock;
  32. static const char *splitName(const char *fileName)
  33. {
  34. if (!fileName)
  35. return NULL;
  36. SpinBlock b(*lock);
  37. const char *sig = signature->find(fileName);
  38. if (sig)
  39. return sig+signature->findlen();
  40. else
  41. return NULL;
  42. }
  43. static void splitArchivedFileName(const char *fullName, StringAttr &container, StringAttr &option, StringAttr &relPath)
  44. {
  45. const char *tail = splitName(fullName);
  46. assertex(tail);
  47. size_t containerLen = tail-fullName;
  48. if (fullName[containerLen-1]==PATHSEPCHAR)
  49. containerLen--;
  50. container.set(fullName, containerLen);
  51. if (*tail=='{')
  52. {
  53. tail++;
  54. const char *end = strchr(tail, '}');
  55. if (!end)
  56. throw MakeStringException(0, "Invalid archive-embedded filename - no matching } found");
  57. option.set(tail, end - tail);
  58. tail = end+1;
  59. if (*tail==PATHSEPCHAR)
  60. tail++;
  61. else if (*tail != 0)
  62. throw MakeStringException(0, "Invalid archive-embedded filename - " PATHSEPSTR " expected after }");
  63. }
  64. else
  65. option.clear();
  66. if (tail && *tail)
  67. {
  68. StringBuffer s(tail);
  69. s.replace(PATHSEPCHAR, '/');
  70. relPath.set(s);
  71. }
  72. else
  73. relPath.clear();
  74. }
  75. static StringBuffer & buildArchivedFileName(StringBuffer &fullname, const char *archiveFile, const char *option, const char *relPath)
  76. {
  77. fullname.append(archiveFile);
  78. if (option && *option)
  79. fullname.append(PATHSEPCHAR).append('{').append(option).append('}');
  80. if (relPath && *relPath)
  81. fullname.append(PATHSEPCHAR).append(relPath);
  82. return fullname;
  83. }
  84. IDirectoryIterator *createArchiveDirectoryIterator(const char *gitFileName, const char *mask, bool sub, bool includeDirs);
  85. // Wrapper around libarchive's archive_entry struct to ensure we free them at right time
  86. // Because not clear whether safe to use a struct archive_entry object after the archive has been closed,
  87. // we copy the info we need out of them into something we CAN be sure of the lifespan of
  88. class ArchiveEntry : public CInterface, implements IInterface
  89. {
  90. public:
  91. IMPLEMENT_IINTERFACE;
  92. ArchiveEntry(struct archive_entry *entry)
  93. {
  94. mode = archive_entry_filetype(entry);
  95. filesize = archive_entry_size(entry);
  96. path.set(archive_entry_pathname(entry));
  97. }
  98. bool isDir() const
  99. {
  100. return S_ISDIR(mode);
  101. }
  102. inline offset_t size()
  103. {
  104. return filesize;
  105. }
  106. const char *pathname()
  107. {
  108. return path.get();
  109. }
  110. private:
  111. unsigned mode;
  112. offset_t filesize;
  113. StringAttr path;
  114. };
  115. // IFileIO implementation for reading out of libarchive-supported archives
  116. // Because of the nature of the libarchive this may not be efficient for some archive formats
  117. // Have to read through the entire archive directory to find the bit you want, it seems
  118. // It's possible that we could add some seek support to at least avoid having to do so twice?
  119. class ArchiveFileIO : public CInterface, implements IFileIO
  120. {
  121. public:
  122. IMPLEMENT_IINTERFACE;
  123. ArchiveFileIO(const char *_fullName) : fullName(_fullName)
  124. {
  125. // Sadly it seems we can't use a saved entry to read data from an archive. We have to open a new archive
  126. // object and scan through until we find the matching file, in order to extract it.
  127. StringAttr container, option, relpath;
  128. splitArchivedFileName(_fullName, container, option, relpath);
  129. curPos = 0;
  130. lastPos = 0;
  131. curBuffSize = 0;
  132. curBuff = NULL;
  133. archive = archive_read_new();
  134. archive_read_support_format_all(archive);
  135. archive_read_support_compression_all(archive);
  136. int retcode = archive_read_open_filename(archive, container, 10240);
  137. if (retcode == ARCHIVE_OK)
  138. {
  139. struct archive_entry *entry = archive_entry_new();
  140. while (archive_read_next_header2(archive, entry) == ARCHIVE_OK)
  141. {
  142. const char *filename = archive_entry_pathname(entry);
  143. if (strcmp(filename, relpath.get())==0)
  144. {
  145. fileSize = archive_entry_size(entry);
  146. break;
  147. }
  148. }
  149. archive_entry_free(entry);
  150. }
  151. }
  152. ~ArchiveFileIO()
  153. {
  154. archive_read_finish(archive);
  155. }
  156. virtual size32_t read(offset_t pos, size32_t len, void * _data)
  157. {
  158. // NOTE - we don't support multithreaded access (the sequential-only restriction would make that tricky anyway)
  159. if (pos < lastPos)
  160. throw MakeStringException(0, "Only sequential access to contained file %s supported", fullName.get());
  161. byte *data = (byte *) _data;
  162. size32_t lenRequested = len;
  163. while (len > 0 & pos < fileSize)
  164. {
  165. if (pos >= curPos+curBuffSize)
  166. {
  167. int ret = archive_read_data_block(archive, &curBuff, &curBuffSize, &curPos);
  168. if (ret != ARCHIVE_OK)
  169. {
  170. if (ret == ARCHIVE_EOF)
  171. break; // This shouldn't happen if the quoted fileSize was accurate...
  172. else
  173. throw MakeStringException(0, "Read error reading contained file %s", fullName.get());
  174. }
  175. }
  176. else
  177. {
  178. // Copy as much of the current request as we can fulfil from this block
  179. offset_t buffOffset = (pos - curPos);
  180. size_t copyLen = (curBuffSize - buffOffset) > len ? len : curBuffSize - buffOffset; // careful for overflows, we are mixing 64/32bit values
  181. if (curBuff)
  182. memcpy(data, ((const byte *) curBuff) + buffOffset, copyLen);
  183. else
  184. memset(data, 0, copyLen); // Sparse areas of compressed files may be represented with NULL buffers
  185. data += copyLen;
  186. len -= copyLen;
  187. pos += copyLen;
  188. }
  189. }
  190. lastPos = pos;
  191. return lenRequested - len;
  192. }
  193. virtual offset_t size()
  194. {
  195. return fileSize;
  196. }
  197. virtual void close()
  198. {
  199. }
  200. // Write methods not implemented - this is a read-only file
  201. virtual size32_t write(offset_t pos, size32_t len, const void * data)
  202. {
  203. throwUnexpected();
  204. }
  205. virtual offset_t appendFile(IFile *file,offset_t pos=0,offset_t len=(offset_t)-1)
  206. {
  207. throwUnexpected();
  208. }
  209. virtual void setSize(offset_t size)
  210. {
  211. throwUnexpected();
  212. }
  213. virtual void flush()
  214. {
  215. throwUnexpected();
  216. }
  217. protected:
  218. struct archive *archive;
  219. offset_t fileSize;
  220. #if ARCHIVE_VERSION_NUMBER < 3000000
  221. off_t curPos;
  222. #else
  223. int64_t curPos;
  224. #endif
  225. offset_t lastPos;
  226. size_t curBuffSize;
  227. const void *curBuff;
  228. StringAttr fullName;
  229. };
  230. // IFile implementation for reading out of libarchive-supported archives
  231. // These use the struct_archive_entry objects allocated in the directory iterator
  232. // in the hope they might be useful for directly seeking to the file to be extracted
  233. // at some point.
  234. class ArchiveFile : public CInterface, implements IFile
  235. {
  236. public:
  237. IMPLEMENT_IINTERFACE;
  238. ArchiveFile(const char *_fileName, ArchiveEntry *_entry)
  239. : fullName(_fileName),entry(_entry)
  240. {
  241. }
  242. virtual bool exists()
  243. {
  244. return entry != NULL;
  245. }
  246. virtual bool getTime(CDateTime * createTime, CDateTime * modifiedTime, CDateTime * accessedTime)
  247. {
  248. UNIMPLEMENTED; // MORE - maybe could implement if required
  249. }
  250. virtual fileBool isDirectory()
  251. {
  252. if (!entry)
  253. return notFound;
  254. return entry->isDir() ? foundYes : foundNo;
  255. }
  256. virtual fileBool isFile()
  257. {
  258. if (!entry)
  259. return notFound;
  260. return entry->isDir() ? foundNo : foundYes;
  261. }
  262. virtual fileBool isReadOnly()
  263. {
  264. if (!entry)
  265. return notFound;
  266. return foundYes;
  267. }
  268. virtual IFileIO * open(IFOmode mode)
  269. {
  270. assertex(mode==IFOread && entry != NULL);
  271. return new ArchiveFileIO(fullName.str());
  272. }
  273. virtual IFileAsyncIO * openAsync(IFOmode mode)
  274. {
  275. UNIMPLEMENTED;
  276. }
  277. virtual IFileIO * openShared(IFOmode mode, IFSHmode shmode)
  278. {
  279. assertex(mode==IFOread && entry != NULL);
  280. return new ArchiveFileIO(fullName.str());
  281. }
  282. virtual const char * queryFilename()
  283. {
  284. return fullName.str();
  285. }
  286. virtual offset_t size()
  287. {
  288. if (!entry)
  289. return 0;
  290. return entry->size();
  291. }
  292. // Directory functions
  293. virtual IDirectoryIterator *directoryFiles(const char *mask, bool sub, bool includeDirs)
  294. {
  295. if (isDirectory() != foundYes || (mask && !*mask)) // Empty mask string means matches nothing - NULL means matches everything
  296. return createNullDirectoryIterator();
  297. else
  298. {
  299. StringBuffer dirName(fullName);
  300. dirName.append(PATHSEPCHAR);
  301. return createArchiveDirectoryIterator(dirName, mask, sub, includeDirs);
  302. }
  303. }
  304. virtual bool getInfo(bool &_isdir,offset_t &_size,CDateTime &_modtime)
  305. {
  306. _isdir = isDirectory()==foundYes;
  307. _size = size();
  308. _modtime.clear(); // MORE could probably do better
  309. return true; // MORE should this be false if not existing?
  310. }
  311. // Not going to be implemented - this IFile interface is too big..
  312. virtual bool setTime(const CDateTime * createTime, const CDateTime * modifiedTime, const CDateTime * accessedTime) { UNIMPLEMENTED; }
  313. virtual bool remove() { UNIMPLEMENTED; }
  314. virtual void rename(const char *newTail) { UNIMPLEMENTED; }
  315. virtual void move(const char *newName) { UNIMPLEMENTED; }
  316. virtual void setReadOnly(bool ro) { UNIMPLEMENTED; }
  317. virtual bool setCompression(bool set) { UNIMPLEMENTED; }
  318. virtual offset_t compressedSize() { UNIMPLEMENTED; }
  319. virtual unsigned getCRC() { UNIMPLEMENTED; }
  320. virtual void setCreateFlags(unsigned cflags) { UNIMPLEMENTED; }
  321. virtual void setShareMode(IFSHmode shmode) { UNIMPLEMENTED; }
  322. virtual bool createDirectory() { UNIMPLEMENTED; }
  323. virtual IDirectoryDifferenceIterator *monitorDirectory(
  324. IDirectoryIterator *prev=NULL, // in (NULL means use current as baseline)
  325. const char *mask=NULL,
  326. bool sub=false,
  327. bool includedirs=false,
  328. unsigned checkinterval=60*1000,
  329. unsigned timeout=(unsigned)-1,
  330. Semaphore *abortsem=NULL) { UNIMPLEMENTED; }
  331. virtual void copySection(const RemoteFilename &dest, offset_t toOfs=(offset_t)-1, offset_t fromOfs=0, offset_t size=(offset_t)-1, ICopyFileProgress *progress=NULL) { UNIMPLEMENTED; }
  332. virtual void copyTo(IFile *dest, size32_t buffersize=0x100000, ICopyFileProgress *progress=NULL, bool usetmp=false) { UNIMPLEMENTED; }
  333. virtual IMemoryMappedFile *openMemoryMapped(offset_t ofs=0, memsize_t len=(memsize_t)-1, bool write=false) { UNIMPLEMENTED; }
  334. virtual void treeCopyTo(IFile *dest,IpSubNet &subnet,IpAddress &resfrom,bool usetmp=false) { UNIMPLEMENTED; }
  335. protected:
  336. StringBuffer fullName;
  337. Linked<ArchiveEntry> entry;
  338. };
  339. static IFile *createIFileInArchive(const char *containedFileName)
  340. {
  341. StringBuffer fname(containedFileName);
  342. assertex(fname.length());
  343. removeTrailingPathSepChar(fname);
  344. StringAttr container, option, relpath;
  345. splitArchivedFileName(fname.str(), container, option, relpath);
  346. if (relpath.length())
  347. {
  348. StringBuffer dirPath, dirTail;
  349. dirPath.append(container).append(option);
  350. splitFilename(relpath, &dirPath, &dirPath, &dirTail, &dirTail);
  351. Owned<IDirectoryIterator> dir = createArchiveDirectoryIterator(dirPath.str(), dirTail.str(), false, true);
  352. if (dir->first())
  353. {
  354. Linked<IFile> file = &dir->query();
  355. assertex(!dir->next());
  356. return file.getClear();
  357. }
  358. else
  359. return new ArchiveFile(containedFileName, NULL);
  360. }
  361. else
  362. {
  363. // Create an IFile representing the root of the archive as a directory
  364. struct archive_entry *rootEntry = archive_entry_new();
  365. archive_entry_set_pathname(rootEntry, ".");
  366. archive_entry_set_mode(rootEntry, __S_IFDIR);
  367. archive_entry_set_size(rootEntry, 0);
  368. return new ArchiveFile(containedFileName, new ArchiveEntry(rootEntry));
  369. }
  370. }
  371. class ArchiveDirectoryIterator : public CInterface, implements IDirectoryIterator
  372. {
  373. public:
  374. IMPLEMENT_IINTERFACE;
  375. ArchiveDirectoryIterator(const char *_containedFileName, const char *_mask, bool _sub, bool _includeDirs)
  376. : mask(_mask), sub(_sub), includeDirs(_includeDirs)
  377. {
  378. splitArchivedFileName(_containedFileName, container, option, relDir);
  379. curIndex = 0;
  380. }
  381. virtual StringBuffer &getName(StringBuffer &buf)
  382. {
  383. assertex(curFile);
  384. return buf.append(curFile->queryFilename());
  385. }
  386. virtual bool isDir()
  387. {
  388. assertex(curFile);
  389. return curFile->isDirectory();
  390. }
  391. virtual __int64 getFileSize()
  392. {
  393. assertex(curFile);
  394. return curFile->size();
  395. }
  396. virtual bool getModifiedTime(CDateTime &ret)
  397. {
  398. UNIMPLEMENTED;
  399. }
  400. virtual bool first()
  401. {
  402. curFile.clear();
  403. entries.kill();
  404. curIndex = 0;
  405. struct archive *archive = archive_read_new();
  406. archive_read_support_format_all(archive);
  407. archive_read_support_compression_all(archive);
  408. int retcode = archive_read_open_filename(archive, container, 10240);
  409. if (retcode == ARCHIVE_OK)
  410. {
  411. struct archive_entry *entry = archive_entry_new();
  412. while (archive_read_next_header2(archive, entry) == ARCHIVE_OK)
  413. {
  414. unsigned mode = archive_entry_filetype(entry);
  415. bool isDir = S_ISDIR(mode);
  416. if (includeDirs || !isDir)
  417. {
  418. const char *filename = archive_entry_pathname(entry);
  419. if (memcmp(filename, relDir.get(), relDir.length())==0)
  420. {
  421. StringBuffer tail(filename + relDir.length());
  422. if (tail.length())
  423. {
  424. if (tail.charAt(tail.length()-1)=='/' || tail.charAt(tail.length()-1)==PATHSEPCHAR)
  425. tail.remove(tail.length()-1, 1);
  426. }
  427. else
  428. {
  429. assert(isDir);
  430. tail.append(".");
  431. }
  432. // Strip off a trailing /, then check that there is no / in the tail
  433. if (strchr(tail, PATHSEPCHAR) == NULL && (!mask.length() || WildMatch(tail, mask, false)))
  434. {
  435. entries.append(*new ArchiveEntry(entry));
  436. }
  437. }
  438. }
  439. }
  440. archive_entry_free(entry);
  441. }
  442. archive_read_finish(archive);
  443. return next();
  444. }
  445. virtual bool next()
  446. {
  447. if (entries.isItem(curIndex))
  448. {
  449. ArchiveEntry &entry = entries.item(curIndex);
  450. curIndex++;
  451. const char *filename = entry.pathname();
  452. StringBuffer containedFileName;
  453. buildArchivedFileName(containedFileName, container, option, filename);
  454. removeTrailingPathSepChar(containedFileName);
  455. curFile.setown(new ArchiveFile(containedFileName, &entry));
  456. return true;
  457. }
  458. else
  459. {
  460. curFile.clear();
  461. return false;
  462. }
  463. }
  464. virtual bool isValid() { return curFile != NULL; }
  465. virtual IFile & query() { return *curFile; }
  466. protected:
  467. StringAttr container;
  468. StringAttr option;
  469. StringAttr relDir;
  470. StringAttr mask;
  471. Owned<IFile> curFile;
  472. unsigned curIndex;
  473. IArrayOf<ArchiveEntry> entries; // The entries that matched
  474. bool includeDirs;
  475. bool sub;
  476. };
  477. IDirectoryIterator *createArchiveDirectoryIterator(const char *gitFileName, const char *mask, bool sub, bool includeDirs)
  478. {
  479. assertex(sub==false); // I don't know what it means!
  480. return new ArchiveDirectoryIterator(gitFileName, mask, sub, includeDirs);
  481. }
  482. class CArchiveFileHook : public CInterface, implements IContainedFileHook
  483. {
  484. public:
  485. IMPLEMENT_IINTERFACE;
  486. virtual IFile * createIFile(const char *fileName)
  487. {
  488. if (isArchiveFileName(fileName))
  489. return createIFileInArchive(fileName);
  490. else
  491. return NULL;
  492. }
  493. protected:
  494. static bool isArchiveFileName(const char *fileName)
  495. {
  496. if (fileName)
  497. return splitName(fileName) != NULL;
  498. return false;
  499. }
  500. } *archiveFileHook;
  501. extern ARCHIVEFILE_API void installFileHook()
  502. {
  503. SpinBlock b(*lock); // Probably overkill!
  504. if (!archiveFileHook)
  505. {
  506. archiveFileHook = new CArchiveFileHook;
  507. addContainedFileHook(archiveFileHook);
  508. }
  509. }
  510. extern ARCHIVEFILE_API void removeFileHook()
  511. {
  512. SpinBlock b(*lock); // Probably overkill!
  513. if (archiveFileHook)
  514. {
  515. removeContainedFileHook(archiveFileHook);
  516. archiveFileHook = NULL;
  517. }
  518. }
  519. MODULE_INIT(INIT_PRIORITY_STANDARD)
  520. {
  521. lock = new SpinLock;
  522. signature = new RegExpr(ARCHIVE_SIGNATURE);
  523. archiveFileHook = NULL;
  524. return true;
  525. }
  526. MODULE_EXIT()
  527. {
  528. if (archiveFileHook)
  529. {
  530. removeContainedFileHook(archiveFileHook);
  531. archiveFileHook = NULL;
  532. }
  533. delete signature;
  534. delete lock;
  535. ::Release(archiveFileHook);
  536. }