1 // Copyright (C) 2013 James Turner - zakalawe@mac.com
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Library General Public
5 // License as published by the Free Software Foundation; either
6 // version 2 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Library General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 #include <simgear/package/Install.hxx>
20 #include <boost/foreach.hpp>
23 #include <simgear/package/unzip.h>
24 #include <simgear/package/md5.h>
26 #include <simgear/structure/exception.hxx>
27 #include <simgear/props/props_io.hxx>
28 #include <simgear/package/Catalog.hxx>
29 #include <simgear/package/Package.hxx>
30 #include <simgear/package/Root.hxx>
31 #include <simgear/io/HTTPRequest.hxx>
32 #include <simgear/io/HTTPClient.hxx>
33 #include <simgear/misc/sg_dir.hxx>
34 #include <simgear/misc/strutils.hxx>
37 void fill_memory_filefunc (zlib_filefunc_def*);
44 class Install::PackageArchiveDownloader : public HTTP::Request
47 PackageArchiveDownloader(InstallRef aOwner) :
48 HTTP::Request("" /* dummy URL */),
52 m_urls = m_owner->package()->downloadUrls();
54 throw sg_exception("no package download URLs");
57 // TODO randomise order of m_urls
59 m_extractPath = aOwner->path().dir();
60 m_extractPath.append("_extract_" + aOwner->package()->md5());
62 // clean up any existing files
65 d.remove(true /* recursive */);
69 ~PackageArchiveDownloader()
71 // always clean up our extraction dir: if we successfully downloaded
72 // and installed it will be an empty dir, if we failed it might contain
73 // (some) of the package files.
76 d.remove(true /* recursive */);
80 size_t downloadedBytes() const
85 int percentDownloaded() const
87 if (responseLength() <= 0) {
91 return (m_downloaded * 100) / responseLength();
94 virtual std::string url() const
96 return m_urls.front();
99 virtual void responseHeadersComplete()
101 Request::responseHeadersComplete();
103 Dir d(m_extractPath);
106 memset(&m_md5, 0, sizeof(SG_MD5_CTX));
110 virtual void gotBodyData(const char* s, int n)
112 m_buffer += std::string(s, n);
113 SG_MD5Update(&m_md5, (unsigned char*) s, n);
115 m_downloaded = m_buffer.size();
116 m_owner->installProgress(m_buffer.size(), responseLength());
119 virtual void onDone()
121 if (responseCode() != 200) {
122 SG_LOG(SG_GENERAL, SG_ALERT, "download failure:" << responseCode() <<
124 Delegate::StatusCode code = Delegate::FAIL_DOWNLOAD;
125 if (responseCode() == 404) {
126 code = Delegate::FAIL_NOT_FOUND;
133 unsigned char digest[MD5_DIGEST_LENGTH];
134 SG_MD5Final(digest, &m_md5);
135 std::string const hex_md5 =
136 strutils::encodeHex(digest, MD5_DIGEST_LENGTH);
138 if (hex_md5 != m_owner->package()->md5()) {
139 SG_LOG(SG_GENERAL, SG_ALERT, "md5 verification failed:\n"
140 << "\t" << hex_md5 << "\n\t"
141 << m_owner->package()->md5() << "\n\t"
142 << "downloading from:" << url());
143 doFailure(Delegate::FAIL_CHECKSUM);
147 if (!extractUnzip()) {
148 SG_LOG(SG_GENERAL, SG_WARN, "zip extraction failed");
149 doFailure(Delegate::FAIL_EXTRACT);
153 if (m_owner->path().exists()) {
154 Dir destDir(m_owner->path());
155 destDir.remove(true /* recursive */);
158 // build a path like /path/to/packages/org.some.catalog/Aircraft/extract_xxxx/MyAircraftDir
159 SGPath extractedPath = m_extractPath;
160 extractedPath.append(m_owner->package()->dirName());
162 // rename it to path/to/packages/org.some.catalog/Aircraft/MyAircraftDir
163 bool ok = extractedPath.rename(m_owner->path());
165 doFailure(Delegate::FAIL_FILESYSTEM);
169 m_owner->m_revision = m_owner->package()->revision();
170 m_owner->writeRevisionFile();
171 m_owner->m_download.reset(); // so isDownloading reports false
173 m_owner->installResult(Delegate::STATUS_SUCCESS);
176 virtual void onFail()
178 if (responseCode() == -1) {
179 doFailure(Delegate::USER_CANCELLED);
181 doFailure(Delegate::FAIL_DOWNLOAD);
187 void extractCurrentFile(unzFile zip, char* buffer, size_t bufferSize)
189 unz_file_info fileInfo;
190 unzGetCurrentFileInfo(zip, &fileInfo,
192 NULL, 0, /* extra field */
193 NULL, 0 /* comment field */);
195 std::string name(buffer);
196 // no absolute paths, no 'up' traversals
197 // we could also look for suspicious file extensions here (forbid .dll, .exe, .so)
198 if ((name[0] == '/') || (name.find("../") != std::string::npos) || (name.find("..\\") != std::string::npos)) {
199 throw sg_format_exception("Bad zip path", name);
202 if (fileInfo.uncompressed_size == 0) {
203 // assume it's a directory for now
204 // since we create parent directories when extracting
205 // a path, we're done here
209 int result = unzOpenCurrentFile(zip);
210 if (result != UNZ_OK) {
211 throw sg_io_exception("opening current zip file failed", sg_location(name));
214 std::ofstream outFile;
216 SGPath path(m_extractPath);
219 // create enclosing directory heirarchy as required
220 Dir parentDir(path.dir());
221 if (!parentDir.exists()) {
222 bool ok = parentDir.create(0755);
224 throw sg_io_exception("failed to create directory heirarchy for extraction", path.c_str());
228 outFile.open(path.c_str(), std::ios::binary | std::ios::trunc | std::ios::out);
229 if (outFile.fail()) {
230 throw sg_io_exception("failed to open output file for writing", path.c_str());
234 int bytes = unzReadCurrentFile(zip, buffer, bufferSize);
236 throw sg_io_exception("unzip failure reading curent archive", sg_location(name));
237 } else if (bytes == 0) {
240 outFile.write(buffer, bytes);
245 unzCloseCurrentFile(zip);
251 zlib_filefunc_def memoryAccessFuncs;
252 fill_memory_filefunc(&memoryAccessFuncs);
254 char bufferName[128];
255 snprintf(bufferName, 128, "%p+%lx", m_buffer.data(), m_buffer.size());
256 unzFile zip = unzOpen2(bufferName, &memoryAccessFuncs);
258 const size_t BUFFER_SIZE = 32 * 1024;
259 void* buf = malloc(BUFFER_SIZE);
262 int result = unzGoToFirstFile(zip);
263 if (result != UNZ_OK) {
264 throw sg_exception("failed to go to first file in archive");
268 extractCurrentFile(zip, (char*) buf, BUFFER_SIZE);
269 result = unzGoToNextFile(zip);
270 if (result == UNZ_END_OF_LIST_OF_FILE) {
272 } else if (result != UNZ_OK) {
273 throw sg_io_exception("failed to go to next file in the archive");
276 } catch (sg_exception& e) {
285 void doFailure(Delegate::StatusCode aReason)
287 Dir dir(m_extractPath);
289 dir.remove(true /* recursive */);
292 // TODO - try other mirrors
293 m_owner->m_download.reset(); // ensure we get cleaned up
294 m_owner->installResult(aReason);
300 std::string m_buffer;
301 SGPath m_extractPath;
305 ////////////////////////////////////////////////////////////////////
306 Install::Install(PackageRef aPkg, const SGPath& aPath) :
309 m_status(Delegate::STATUS_IN_PROGRESS)
312 m_package->catalog()->root()->registerInstall(this);
319 InstallRef Install::createFromPath(const SGPath& aPath, CatalogRef aCat)
321 std::string path = aPath.file();
322 PackageRef pkg = aCat->getPackageByPath(path);
324 throw sg_exception("no package with path:" + path);
326 return new Install(pkg, aPath);
329 void Install::parseRevision()
331 SGPath revisionFile = m_path;
332 revisionFile.append(".revision");
333 if (!revisionFile.exists()) {
338 std::ifstream f(revisionFile.c_str(), std::ios::in);
342 void Install::writeRevisionFile()
344 SGPath revisionFile = m_path;
345 revisionFile.append(".revision");
346 std::ofstream f(revisionFile.c_str(), std::ios::out | std::ios::trunc);
347 f << m_revision << std::endl;
350 bool Install::hasUpdate() const
352 return m_package->revision() > m_revision;
355 void Install::startUpdate()
358 return; // already active
361 m_download = new PackageArchiveDownloader(this);
362 m_package->catalog()->root()->makeHTTPRequest(m_download);
363 m_package->catalog()->root()->startInstall(this);
366 bool Install::uninstall()
369 if (!d.remove(true)) {
370 SG_LOG(SG_GENERAL, SG_ALERT, "package uninstall failed: couldn't remove path " << m_path);
374 m_package->catalog()->root()->unregisterInstall(this);
378 bool Install::isDownloading() const
380 return (m_download.valid());
383 bool Install::isQueued() const
385 return m_package->catalog()->root()->isInstallQueued(const_cast<Install*>(this));
388 int Install::downloadedPercent() const
390 if (!m_download.valid()) {
394 PackageArchiveDownloader* dl = static_cast<PackageArchiveDownloader*>(m_download.get());
395 return dl->percentDownloaded();
398 size_t Install::downloadedBytes() const
400 if (!m_download.valid()) {
404 PackageArchiveDownloader* dl = static_cast<PackageArchiveDownloader*>(m_download.get());
405 return dl->downloadedBytes();
409 void Install::cancelDownload()
411 if (m_download.valid()) {
412 m_package->catalog()->root()->cancelHTTPRequest(m_download, "User cancelled download");
415 if (m_revision == 0) {
416 SG_LOG(SG_GENERAL, SG_INFO, "cancel install of package, will unregister");
417 m_package->catalog()->root()->unregisterInstall(this);
420 m_package->catalog()->root()->cancelDownload(this);
425 PathAppender(const SGPath& p) : m_path(p) {}
427 SGPath operator()(const std::string& s) const
437 PathList Install::thumbnailPaths() const
439 const string_list& thumbs(m_package->thumbnails());
444 std::transform(thumbs.begin(), thumbs.end(),
445 std::back_inserter(result),
446 PathAppender(m_path));
450 SGPath Install::primarySetPath() const
452 SGPath setPath(m_path);
453 std::string ps(m_package->id());
454 setPath.append(ps + "-set.xml");
458 //------------------------------------------------------------------------------
459 Install* Install::done(const Callback& cb)
461 if( m_status == Delegate::STATUS_SUCCESS )
464 _cb_done.push_back(cb);
469 //------------------------------------------------------------------------------
470 Install* Install::fail(const Callback& cb)
472 if( m_status != Delegate::STATUS_SUCCESS
473 && m_status != Delegate::STATUS_IN_PROGRESS )
476 _cb_fail.push_back(cb);
481 //------------------------------------------------------------------------------
482 Install* Install::always(const Callback& cb)
484 if( m_status != Delegate::STATUS_IN_PROGRESS )
487 _cb_always.push_back(cb);
492 //------------------------------------------------------------------------------
493 Install* Install::progress(const ProgressCallback& cb)
495 _cb_progress.push_back(cb);
499 //------------------------------------------------------------------------------
500 void Install::installResult(Delegate::StatusCode aReason)
502 m_package->catalog()->root()->finishInstall(this, aReason);
503 if (aReason == Delegate::STATUS_SUCCESS) {
512 //------------------------------------------------------------------------------
513 void Install::installProgress(unsigned int aBytes, unsigned int aTotal)
515 m_package->catalog()->root()->installProgress(this, aBytes, aTotal);
516 _cb_progress(this, aBytes, aTotal);
520 } // of namespace pkg
522 } // of namespace simgear