]> git.mxchange.org Git - simgear.git/blob - simgear/package/Install.cxx
Tweak HTTP code to always sleep.
[simgear.git] / simgear / package / Install.cxx
1 // Copyright (C) 2013  James Turner - zakalawe@mac.com
2 //
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.
7 //
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.
12 //
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.
16 //
17
18 #include <simgear/package/Install.hxx>
19
20 #include <boost/foreach.hpp>
21 #include <fstream>
22
23 #include <simgear/package/unzip.h>
24 #include <simgear/package/md5.h>
25
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>
33
34 extern "C" {
35     void fill_memory_filefunc (zlib_filefunc_def*);
36 }
37
38 namespace simgear {
39     
40 namespace pkg {
41
42 class Install::PackageArchiveDownloader : public HTTP::Request
43 {
44 public:
45     PackageArchiveDownloader(Install* aOwner) :
46         HTTP::Request("" /* dummy URL */),
47         m_owner(aOwner)
48     {
49         m_urls = m_owner->package()->downloadUrls();
50         if (m_urls.empty()) {
51             throw sg_exception("no package download URLs");
52         }
53         
54         // TODO randomise order of m_urls
55         
56         m_extractPath = aOwner->path().dir();
57         m_extractPath.append("_DOWNLOAD"); // add some temporary value
58         
59     }
60     
61 protected:
62     virtual std::string url() const
63     {
64         return m_urls.front();
65     }
66     
67     virtual void responseHeadersComplete()
68     {
69         Dir d(m_extractPath);
70         d.create(0755);        
71         
72         memset(&m_md5, 0, sizeof(SG_MD5_CTX));
73         SG_MD5Init(&m_md5);
74     }
75     
76     virtual void gotBodyData(const char* s, int n)
77     {
78         m_buffer += std::string(s, n);
79         SG_MD5Update(&m_md5, (unsigned char*) s, n);
80         
81         m_owner->installProgress(m_buffer.size(), responseLength());
82     }
83     
84     virtual void onDone()
85     {
86         if (responseCode() != 200) {
87             SG_LOG(SG_GENERAL, SG_ALERT, "download failure");
88             doFailure(Delegate::FAIL_DOWNLOAD);
89             return;
90         }
91
92         SG_MD5Final(&m_md5);
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];
99         }
100         
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);
107             return;
108         }
109         
110         if (!extractUnzip()) {
111             SG_LOG(SG_GENERAL, SG_WARN, "zip extraction failed");
112             doFailure(Delegate::FAIL_EXTRACT);
113             return;
114         }
115                   
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 */);
120         }
121         
122         m_extractPath.append(m_owner->package()->id());
123         bool ok = m_extractPath.rename(m_owner->path());
124         if (!ok) {
125             doFailure(Delegate::FAIL_FILESYSTEM);
126             return;
127         }
128         
129         m_owner->m_revision = m_owner->package()->revision();
130         m_owner->writeRevisionFile();
131         m_owner->installResult(Delegate::FAIL_SUCCESS);
132     }
133     
134 private:
135
136     void extractCurrentFile(unzFile zip, char* buffer, size_t bufferSize)
137     {
138         unz_file_info fileInfo;
139         unzGetCurrentFileInfo(zip, &fileInfo, 
140             buffer, bufferSize, 
141             NULL, 0,  /* extra field */
142             NULL, 0 /* comment field */);
143             
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);
149         }
150         
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
155             return;
156         }
157         
158         int result = unzOpenCurrentFile(zip);
159         if (result != UNZ_OK) {
160             throw sg_io_exception("opening current zip file failed", sg_location(name));
161         }
162             
163         std::ofstream outFile;
164         bool eof = false;
165         SGPath path(m_extractPath);
166         path.append(name);
167                         
168     // create enclosing directory heirarchy as required
169         Dir parentDir(path.dir());
170         if (!parentDir.exists()) {
171             bool ok = parentDir.create(0755);
172             if (!ok) {
173                 throw sg_io_exception("failed to create directory heirarchy for extraction", path.c_str());
174             }
175         }
176             
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());
180         }
181             
182         while (!eof) {
183             int bytes = unzReadCurrentFile(zip, buffer, bufferSize);
184             if (bytes < 0) {
185                 throw sg_io_exception("unzip failure reading curent archive", sg_location(name));
186             } else if (bytes == 0) {
187                 eof = true;
188             } else {
189                 outFile.write(buffer, bytes);
190             }
191         }
192             
193         outFile.close();
194         unzCloseCurrentFile(zip);
195     }
196     
197     bool extractUnzip()
198     {
199         bool result = true;
200         zlib_filefunc_def memoryAccessFuncs;
201         fill_memory_filefunc(&memoryAccessFuncs);
202            
203         char bufferName[128];
204         snprintf(bufferName, 128, "%p+%lx", m_buffer.data(), m_buffer.size());
205         unzFile zip = unzOpen2(bufferName, &memoryAccessFuncs);
206         
207         const size_t BUFFER_SIZE = 32 * 1024;
208         void* buf = malloc(BUFFER_SIZE);
209         
210         try {
211             int result = unzGoToFirstFile(zip);
212             if (result != UNZ_OK) {
213                 throw sg_exception("failed to go to first file in archive");
214             }
215             
216             while (true) {
217                 extractCurrentFile(zip, (char*) buf, BUFFER_SIZE);
218                 result = unzGoToNextFile(zip);
219                 if (result == UNZ_END_OF_LIST_OF_FILE) {
220                     break;
221                 } else if (result != UNZ_OK) {
222                     throw sg_io_exception("failed to go to next file in the archive");
223                 }
224             }
225         } catch (sg_exception& e) {
226             result = false;
227         }
228         
229         free(buf);
230         unzClose(zip);
231         return result;
232     }
233         
234     void doFailure(Delegate::FailureCode aReason)
235     {
236         Dir dir(m_extractPath);
237         dir.remove(true /* recursive */);
238
239         if (m_urls.size() == 1) {
240             std::cout << "failure:" << aReason << std::endl;
241             m_owner->installResult(aReason);
242             return;
243         }
244         
245         std::cout << "retrying download" << std::endl;
246         m_urls.erase(m_urls.begin()); // pop first URL
247     }
248     
249     Install* m_owner;
250     string_list m_urls;
251     SG_MD5_CTX m_md5;
252     std::string m_buffer;
253     SGPath m_extractPath;
254 };
255
256 ////////////////////////////////////////////////////////////////////
257     
258 Install::Install(Package* aPkg, const SGPath& aPath) :
259     m_package(aPkg),
260     m_path(aPath),
261     m_download(NULL)
262 {
263     parseRevision();
264 }
265
266 Install* Install::createFromPath(const SGPath& aPath, Catalog* aCat)
267 {
268     std::string id = aPath.file();
269     Package* pkg = aCat->getPackageById(id);
270     if (!pkg)
271         throw sg_exception("no package with id:" + id);
272     
273     return new Install(pkg, aPath);
274 }
275
276 void Install::parseRevision()
277 {
278     SGPath revisionFile = m_path;
279     revisionFile.append(".revision");
280     if (!revisionFile.exists()) {
281         m_revision = 0;
282         return;
283     }
284     
285     std::ifstream f(revisionFile.c_str(), std::ios::in);
286     f >> m_revision;
287 }
288
289 void Install::writeRevisionFile()
290 {
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;
295 }
296
297 bool Install::hasUpdate() const
298 {
299     return m_package->revision() > m_revision;
300 }
301
302 void Install::startUpdate()
303 {
304     if (m_download) {
305         return; // already active
306     }
307     
308     m_download = new PackageArchiveDownloader(this);
309     m_package->catalog()->root()->makeHTTPRequest(m_download);
310     m_package->catalog()->root()->startInstall(this);
311 }
312
313 void Install::uninstall()
314 {
315     Dir d(m_path);
316     d.remove(true);
317     delete this;
318 }
319
320 void Install::installResult(Delegate::FailureCode aReason)
321 {
322     if (aReason == Delegate::FAIL_SUCCESS) {
323         m_package->catalog()->root()->finishInstall(this);
324     } else {
325         m_package->catalog()->root()->failedInstall(this, aReason);
326     }
327 }
328     
329 void Install::installProgress(unsigned int aBytes, unsigned int aTotal)
330 {
331     m_package->catalog()->root()->installProgress(this, aBytes, aTotal);
332 }
333
334     
335 } // of namespace pkg
336
337 } // of namespace simgear