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()
69 std::cout << "starting download of " << m_owner->package()->id() << " from "
70 << url() << std::endl;
74 memset(&m_md5, 0, sizeof(MD5_CTX));
78 virtual void gotBodyData(const char* s, int n)
80 m_buffer += std::string(s, n);
81 MD5Update(&m_md5, (unsigned char*) s, n);
84 virtual void responseComplete()
86 if (responseCode() != 200) {
87 SG_LOG(SG_GENERAL, SG_ALERT, "download failure");
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());
109 std::cout << "MD5 checksum is ok" << std::endl;
112 if (!extractUnzip()) {
113 SG_LOG(SG_GENERAL, SG_WARN, "zip extraction failed");
118 if (m_owner->path().exists()) {
119 //std::cout << "removing existing path" << std::endl;
120 Dir destDir(m_owner->path());
121 destDir.remove(true /* recursive */);
124 m_extractPath.append(m_owner->package()->id());
125 m_extractPath.rename(m_owner->path());
126 m_owner->m_revision = m_owner->package()->revision();
127 m_owner->writeRevisionFile();
132 void extractCurrentFile(unzFile zip, char* buffer, size_t bufferSize)
134 unz_file_info fileInfo;
135 unzGetCurrentFileInfo(zip, &fileInfo,
137 NULL, 0, /* extra field */
138 NULL, 0 /* comment field */);
140 std::string name(buffer);
141 // no absolute paths, no 'up' traversals
142 // we could also look for suspicious file extensions here (forbid .dll, .exe, .so)
143 if ((name[0] == '/') || (name.find("../") != std::string::npos) || (name.find("..\\") != std::string::npos)) {
144 throw sg_format_exception("Bad zip path", name);
147 if (fileInfo.uncompressed_size == 0) {
148 // assume it's a directory for now
149 // since we create parent directories when extracting
150 // a path, we're done here
154 int result = unzOpenCurrentFile(zip);
155 if (result != UNZ_OK) {
156 throw sg_io_exception("opening current zip file failed", sg_location(name));
159 std::ofstream outFile;
161 SGPath path(m_extractPath);
164 // create enclosing directory heirarchy as required
165 Dir parentDir(path.dir());
166 if (!parentDir.exists()) {
167 bool ok = parentDir.create(0755);
169 throw sg_io_exception("failed to create directory heirarchy for extraction", path.c_str());
173 outFile.open(path.c_str(), std::ios::binary | std::ios::trunc | std::ios::out);
174 if (outFile.fail()) {
175 throw sg_io_exception("failed to open output file for writing", path.c_str());
179 int bytes = unzReadCurrentFile(zip, buffer, bufferSize);
181 throw sg_io_exception("unzip failure reading curent archive", sg_location(name));
182 } else if (bytes == 0) {
185 outFile.write(buffer, bytes);
190 unzCloseCurrentFile(zip);
196 zlib_filefunc_def memoryAccessFuncs;
197 fill_memory_filefunc(&memoryAccessFuncs);
199 char bufferName[128];
200 snprintf(bufferName, 128, "%p+%lx", m_buffer.data(), m_buffer.size());
201 unzFile zip = unzOpen2(bufferName, &memoryAccessFuncs);
203 const size_t BUFFER_SIZE = 32 * 1024;
204 void* buf = malloc(BUFFER_SIZE);
207 int result = unzGoToFirstFile(zip);
208 if (result != UNZ_OK) {
209 throw sg_exception("failed to go to first file in archive");
213 extractCurrentFile(zip, (char*) buf, BUFFER_SIZE);
214 result = unzGoToNextFile(zip);
215 if (result == UNZ_END_OF_LIST_OF_FILE) {
217 } else if (result != UNZ_OK) {
218 throw sg_io_exception("failed to go to next file in the archive");
221 } catch (sg_exception& e) {
232 Dir dir(m_extractPath);
233 dir.remove(true /* recursive */);
234 if (m_urls.size() == 1) {
239 m_urls.erase(m_urls.begin()); // pop first URL
245 std::string m_buffer;
246 SGPath m_extractPath;
249 ////////////////////////////////////////////////////////////////////
251 Install::Install(Package* aPkg, const SGPath& aPath) :
259 Install* Install::createFromPath(const SGPath& aPath, Catalog* aCat)
261 std::string id = aPath.file();
262 Package* pkg = aCat->getPackageById(id);
264 throw sg_exception("no package with id:" + id);
266 return new Install(pkg, aPath);
269 void Install::parseRevision()
271 SGPath revisionFile = m_path;
272 revisionFile.append(".revision");
273 if (!revisionFile.exists()) {
278 std::ifstream f(revisionFile.c_str(), std::ios::in);
282 void Install::writeRevisionFile()
284 SGPath revisionFile = m_path;
285 revisionFile.append(".revision");
286 std::ofstream f(revisionFile.c_str(), std::ios::out | std::ios::trunc);
287 f << m_revision << std::endl;
290 bool Install::hasUpdate() const
292 return m_package->revision() > m_revision;
295 void Install::startUpdate()
298 return; // already active
301 m_download = new PackageArchiveDownloader(this);
302 m_package->catalog()->root()->getHTTPClient()->makeRequest(m_download);
305 void Install::uninstall()
312 } // of namespace pkg
314 } // of namespace simgear