]> git.mxchange.org Git - simgear.git/blob - simgear/package/Install.cxx
LGPL license on package files.
[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         std::cout << "starting download of " << m_owner->package()->id() << " from "
70             << url() << std::endl;
71         Dir d(m_extractPath);
72         d.create(0755);        
73         
74         memset(&m_md5, 0, sizeof(MD5_CTX));
75         MD5Init(&m_md5);
76     }
77     
78     virtual void gotBodyData(const char* s, int n)
79     {
80         m_buffer += std::string(s, n);
81         MD5Update(&m_md5, (unsigned char*) s, n);
82     }
83     
84     virtual void responseComplete()
85     {
86         if (responseCode() != 200) {
87             SG_LOG(SG_GENERAL, SG_ALERT, "download failure");
88             doFailure();
89             return;
90         }
91
92         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();
107             return;
108         } else {
109             std::cout << "MD5 checksum is ok" << std::endl;
110         }
111         
112         if (!extractUnzip()) {
113             SG_LOG(SG_GENERAL, SG_WARN, "zip extraction failed");
114             doFailure();
115             return;
116         }
117                   
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 */);
122         }
123         
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();
128     }
129     
130 private:
131
132     void extractCurrentFile(unzFile zip, char* buffer, size_t bufferSize)
133     {
134         unz_file_info fileInfo;
135         unzGetCurrentFileInfo(zip, &fileInfo, 
136             buffer, bufferSize, 
137             NULL, 0,  /* extra field */
138             NULL, 0 /* comment field */);
139             
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);
145         }
146         
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
151             return;
152         }
153         
154         int result = unzOpenCurrentFile(zip);
155         if (result != UNZ_OK) {
156             throw sg_io_exception("opening current zip file failed", sg_location(name));
157         }
158             
159         std::ofstream outFile;
160         bool eof = false;
161         SGPath path(m_extractPath);
162         path.append(name);
163                         
164     // create enclosing directory heirarchy as required
165         Dir parentDir(path.dir());
166         if (!parentDir.exists()) {
167             bool ok = parentDir.create(0755);
168             if (!ok) {
169                 throw sg_io_exception("failed to create directory heirarchy for extraction", path.c_str());
170             }
171         }
172             
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());
176         }
177             
178         while (!eof) {
179             int bytes = unzReadCurrentFile(zip, buffer, bufferSize);
180             if (bytes < 0) {
181                 throw sg_io_exception("unzip failure reading curent archive", sg_location(name));
182             } else if (bytes == 0) {
183                 eof = true;
184             } else {
185                 outFile.write(buffer, bytes);
186             }
187         }
188             
189         outFile.close();
190         unzCloseCurrentFile(zip);
191     }
192     
193     bool extractUnzip()
194     {
195         bool result = true;
196         zlib_filefunc_def memoryAccessFuncs;
197         fill_memory_filefunc(&memoryAccessFuncs);
198            
199         char bufferName[128];
200         snprintf(bufferName, 128, "%p+%lx", m_buffer.data(), m_buffer.size());
201         unzFile zip = unzOpen2(bufferName, &memoryAccessFuncs);
202         
203         const size_t BUFFER_SIZE = 32 * 1024;
204         void* buf = malloc(BUFFER_SIZE);
205         
206         try {
207             int result = unzGoToFirstFile(zip);
208             if (result != UNZ_OK) {
209                 throw sg_exception("failed to go to first file in archive");
210             }
211             
212             while (true) {
213                 extractCurrentFile(zip, (char*) buf, BUFFER_SIZE);
214                 result = unzGoToNextFile(zip);
215                 if (result == UNZ_END_OF_LIST_OF_FILE) {
216                     break;
217                 } else if (result != UNZ_OK) {
218                     throw sg_io_exception("failed to go to next file in the archive");
219                 }
220             }
221         } catch (sg_exception& e) {
222             result = false;
223         }
224         
225         free(buf);
226         unzClose(zip);
227         return result;
228     }
229         
230     void doFailure()
231     {
232         Dir dir(m_extractPath);
233         dir.remove(true /* recursive */);
234         if (m_urls.size() == 1) {
235             
236             return;
237         }
238         
239         m_urls.erase(m_urls.begin()); // pop first URL
240     }
241     
242     Install* m_owner;
243     string_list m_urls;
244     MD5_CTX m_md5;
245     std::string m_buffer;
246     SGPath m_extractPath;
247 };
248
249 ////////////////////////////////////////////////////////////////////
250     
251 Install::Install(Package* aPkg, const SGPath& aPath) :
252     m_package(aPkg),
253     m_path(aPath),
254     m_download(NULL)
255 {
256     parseRevision();
257 }
258
259 Install* Install::createFromPath(const SGPath& aPath, Catalog* aCat)
260 {
261     std::string id = aPath.file();
262     Package* pkg = aCat->getPackageById(id);
263     if (!pkg)
264         throw sg_exception("no package with id:" + id);
265     
266     return new Install(pkg, aPath);
267 }
268
269 void Install::parseRevision()
270 {
271     SGPath revisionFile = m_path;
272     revisionFile.append(".revision");
273     if (!revisionFile.exists()) {
274         m_revision = 0;
275         return;
276     }
277     
278     std::ifstream f(revisionFile.c_str(), std::ios::in);
279     f >> m_revision;
280 }
281
282 void Install::writeRevisionFile()
283 {
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;
288 }
289
290 bool Install::hasUpdate() const
291 {
292     return m_package->revision() > m_revision;
293 }
294
295 void Install::startUpdate()
296 {
297     if (m_download) {
298         return; // already active
299     }
300     
301     m_download = new PackageArchiveDownloader(this);
302     m_package->catalog()->root()->getHTTPClient()->makeRequest(m_download);
303 }
304
305 void Install::uninstall()
306 {
307     Dir d(m_path);
308     d.remove(true);
309     delete this;
310 }
311
312 } // of namespace pkg
313
314 } // of namespace simgear