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/package/Catalog.hxx>
28 #include <simgear/package/Package.hxx>
29 #include <simgear/package/Root.hxx>
30 #include <simgear/io/HTTPRequest.hxx>
31 #include <simgear/io/HTTPClient.hxx>
32 #include <simgear/misc/sg_dir.hxx>
35 void fill_memory_filefunc (zlib_filefunc_def*);
42 class Install::PackageArchiveDownloader : public HTTP::Request
45 PackageArchiveDownloader(Install* aOwner) :
46 HTTP::Request("" /* dummy URL */),
49 m_urls = m_owner->package()->downloadUrls();
51 throw sg_exception("no package download URLs");
54 // TODO randomise order of m_urls
56 m_extractPath = aOwner->path().dir();
57 m_extractPath.append("_DOWNLOAD"); // add some temporary value
62 virtual std::string url() const
64 return m_urls.front();
67 virtual void responseHeadersComplete()
72 memset(&m_md5, 0, sizeof(SG_MD5_CTX));
76 virtual void gotBodyData(const char* s, int n)
78 m_buffer += std::string(s, n);
79 SG_MD5Update(&m_md5, (unsigned char*) s, n);
81 m_owner->installProgress(m_buffer.size(), responseLength());
84 virtual void responseComplete()
86 if (responseCode() != 200) {
87 SG_LOG(SG_GENERAL, SG_ALERT, "download failure");
88 doFailure(Delegate::FAIL_DOWNLOAD);
93 // convert final sum to hex
94 const char hexChar[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
95 std::stringstream hexMd5;
96 for (int i=0; i<16;++i) {
97 hexMd5 << hexChar[m_md5.digest[i] >> 4];
98 hexMd5 << hexChar[m_md5.digest[i] & 0x0f];
101 if (hexMd5.str() != m_owner->package()->md5()) {
102 SG_LOG(SG_GENERAL, SG_ALERT, "md5 verification failed:\n"
103 << "\t" << hexMd5.str() << "\n\t"
104 << m_owner->package()->md5() << "\n\t"
105 << "downloading from:" << url());
106 doFailure(Delegate::FAIL_CHECKSUM);
110 if (!extractUnzip()) {
111 SG_LOG(SG_GENERAL, SG_WARN, "zip extraction failed");
112 doFailure(Delegate::FAIL_EXTRACT);
116 if (m_owner->path().exists()) {
117 //std::cout << "removing existing path" << std::endl;
118 Dir destDir(m_owner->path());
119 destDir.remove(true /* recursive */);
122 m_extractPath.append(m_owner->package()->id());
123 bool ok = m_extractPath.rename(m_owner->path());
125 doFailure(Delegate::FAIL_FILESYSTEM);
129 m_owner->m_revision = m_owner->package()->revision();
130 m_owner->writeRevisionFile();
131 m_owner->installResult(Delegate::FAIL_SUCCESS);
136 void extractCurrentFile(unzFile zip, char* buffer, size_t bufferSize)
138 unz_file_info fileInfo;
139 unzGetCurrentFileInfo(zip, &fileInfo,
141 NULL, 0, /* extra field */
142 NULL, 0 /* comment field */);
144 std::string name(buffer);
145 // no absolute paths, no 'up' traversals
146 // we could also look for suspicious file extensions here (forbid .dll, .exe, .so)
147 if ((name[0] == '/') || (name.find("../") != std::string::npos) || (name.find("..\\") != std::string::npos)) {
148 throw sg_format_exception("Bad zip path", name);
151 if (fileInfo.uncompressed_size == 0) {
152 // assume it's a directory for now
153 // since we create parent directories when extracting
154 // a path, we're done here
158 int result = unzOpenCurrentFile(zip);
159 if (result != UNZ_OK) {
160 throw sg_io_exception("opening current zip file failed", sg_location(name));
163 std::ofstream outFile;
165 SGPath path(m_extractPath);
168 // create enclosing directory heirarchy as required
169 Dir parentDir(path.dir());
170 if (!parentDir.exists()) {
171 bool ok = parentDir.create(0755);
173 throw sg_io_exception("failed to create directory heirarchy for extraction", path.c_str());
177 outFile.open(path.c_str(), std::ios::binary | std::ios::trunc | std::ios::out);
178 if (outFile.fail()) {
179 throw sg_io_exception("failed to open output file for writing", path.c_str());
183 int bytes = unzReadCurrentFile(zip, buffer, bufferSize);
185 throw sg_io_exception("unzip failure reading curent archive", sg_location(name));
186 } else if (bytes == 0) {
189 outFile.write(buffer, bytes);
194 unzCloseCurrentFile(zip);
200 zlib_filefunc_def memoryAccessFuncs;
201 fill_memory_filefunc(&memoryAccessFuncs);
203 char bufferName[128];
204 snprintf(bufferName, 128, "%p+%lx", m_buffer.data(), m_buffer.size());
205 unzFile zip = unzOpen2(bufferName, &memoryAccessFuncs);
207 const size_t BUFFER_SIZE = 32 * 1024;
208 void* buf = malloc(BUFFER_SIZE);
211 int result = unzGoToFirstFile(zip);
212 if (result != UNZ_OK) {
213 throw sg_exception("failed to go to first file in archive");
217 extractCurrentFile(zip, (char*) buf, BUFFER_SIZE);
218 result = unzGoToNextFile(zip);
219 if (result == UNZ_END_OF_LIST_OF_FILE) {
221 } else if (result != UNZ_OK) {
222 throw sg_io_exception("failed to go to next file in the archive");
225 } catch (sg_exception& e) {
234 void doFailure(Delegate::FailureCode aReason)
236 Dir dir(m_extractPath);
237 dir.remove(true /* recursive */);
239 if (m_urls.size() == 1) {
240 std::cout << "failure:" << aReason << std::endl;
241 m_owner->installResult(aReason);
245 std::cout << "retrying download" << std::endl;
246 m_urls.erase(m_urls.begin()); // pop first URL
252 std::string m_buffer;
253 SGPath m_extractPath;
256 ////////////////////////////////////////////////////////////////////
258 Install::Install(Package* aPkg, const SGPath& aPath) :
266 Install* Install::createFromPath(const SGPath& aPath, Catalog* aCat)
268 std::string id = aPath.file();
269 Package* pkg = aCat->getPackageById(id);
271 throw sg_exception("no package with id:" + id);
273 return new Install(pkg, aPath);
276 void Install::parseRevision()
278 SGPath revisionFile = m_path;
279 revisionFile.append(".revision");
280 if (!revisionFile.exists()) {
285 std::ifstream f(revisionFile.c_str(), std::ios::in);
289 void Install::writeRevisionFile()
291 SGPath revisionFile = m_path;
292 revisionFile.append(".revision");
293 std::ofstream f(revisionFile.c_str(), std::ios::out | std::ios::trunc);
294 f << m_revision << std::endl;
297 bool Install::hasUpdate() const
299 return m_package->revision() > m_revision;
302 void Install::startUpdate()
305 return; // already active
308 m_download = new PackageArchiveDownloader(this);
309 m_package->catalog()->root()->makeHTTPRequest(m_download);
310 m_package->catalog()->root()->startInstall(this);
313 void Install::uninstall()
320 void Install::installResult(Delegate::FailureCode aReason)
322 if (aReason == Delegate::FAIL_SUCCESS) {
323 m_package->catalog()->root()->finishInstall(this);
325 m_package->catalog()->root()->failedInstall(this, aReason);
329 void Install::installProgress(unsigned int aBytes, unsigned int aTotal)
331 m_package->catalog()->root()->installProgress(this, aBytes, aTotal);
335 } // of namespace pkg
337 } // of namespace simgear