Replaced more lisp::Lisp/lisp::Writer with Reader/Writer
[supertux.git] / src / addon / addon_manager.cpp
1 //  SuperTux - Add-on Manager
2 //  Copyright (C) 2007 Christoph Sommer <christoph.sommer@2007.expires.deltadevelopment.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include "addon/addon_manager.hpp"
18
19 #include <config.h>
20 #include <version.h>
21
22 #include <algorithm>
23 #include <physfs.h>
24 #include <sstream>
25 #include <stdexcept>
26 #include <sys/stat.h>
27
28 #ifdef HAVE_LIBCURL
29 #  include <curl/curl.h>
30 #  include <curl/easy.h>
31 #  include <curl/types.h>
32 #endif
33
34 #include "addon/addon.hpp"
35 #include "lisp/list_iterator.hpp"
36 #include "lisp/parser.hpp"
37 #include "util/reader.hpp"
38 #include "util/writer.hpp"
39 #include "util/log.hpp"
40
41 #ifdef HAVE_LIBCURL
42 namespace {
43
44 size_t my_curl_string_append(void *ptr, size_t size, size_t nmemb, void *string_ptr)
45 {
46   std::string& s = *static_cast<std::string*>(string_ptr);
47   std::string buf(static_cast<char*>(ptr), size * nmemb);
48   s += buf;
49   log_debug << "read " << size * nmemb << " bytes of data..." << std::endl;
50   return size * nmemb;
51 }
52
53 size_t my_curl_physfs_write(void *ptr, size_t size, size_t nmemb, void *f_p)
54 {
55   PHYSFS_file* f = static_cast<PHYSFS_file*>(f_p);
56   PHYSFS_sint64 written = PHYSFS_write(f, ptr, size, nmemb);
57   log_debug << "read " << size * nmemb << " bytes of data..." << std::endl;
58   return size * written;
59 }
60
61 }
62 #endif
63
64 AddonManager&
65 AddonManager::get_instance()
66 {
67   static AddonManager instance;
68   return instance;
69 }
70
71 AddonManager::AddonManager() :
72   addons(),
73   ignored_addon_filenames()
74 {
75 #ifdef HAVE_LIBCURL
76   curl_global_init(CURL_GLOBAL_ALL);
77 #endif
78 }
79
80 AddonManager::~AddonManager()
81 {
82 #ifdef HAVE_LIBCURL
83   curl_global_cleanup();
84 #endif
85
86   for (std::vector<Addon*>::iterator i = addons.begin(); i != addons.end(); i++) delete *i;
87 }
88
89 std::vector<Addon*>
90 AddonManager::get_addons()
91 {
92   /*
93     for (std::vector<Addon>::iterator it = installed_addons.begin(); it != installed_addons.end(); ++it) {
94     Addon& addon = *it;
95     if (addon.md5 == "") addon.md5 = calculate_md5(addon);
96     }
97   */
98   return addons;
99 }
100
101 void
102 AddonManager::check_online()
103 {
104 #ifdef HAVE_LIBCURL
105   char error_buffer[CURL_ERROR_SIZE+1];
106
107   const char* baseUrl = "http://supertux.berlios.de/addons/index.nfo";
108   std::string addoninfos = "";
109
110   CURL *curl_handle;
111   curl_handle = curl_easy_init();
112   curl_easy_setopt(curl_handle, CURLOPT_URL, baseUrl);
113   curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "SuperTux/" PACKAGE_VERSION " libcURL");
114   curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, my_curl_string_append);
115   curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &addoninfos);
116   curl_easy_setopt(curl_handle, CURLOPT_ERRORBUFFER, error_buffer);
117   curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1);
118   curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
119   curl_easy_setopt(curl_handle, CURLOPT_FAILONERROR, 1);
120   curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1);
121   CURLcode result = curl_easy_perform(curl_handle);
122   curl_easy_cleanup(curl_handle);
123
124   if (result != CURLE_OK) {
125     std::string why = error_buffer[0] ? error_buffer : "unhandled error";
126     throw std::runtime_error("Downloading Add-on list failed: " + why);
127   }
128
129   try {
130     lisp::Parser parser;
131     std::stringstream addoninfos_stream(addoninfos);
132     const lisp::Lisp* root = parser.parse(addoninfos_stream, "supertux-addons");
133
134     const lisp::Lisp* addons_lisp = root->get_lisp("supertux-addons");
135     if(!addons_lisp) throw std::runtime_error("Downloaded file is not an Add-on list");
136
137     lisp::ListIterator iter(addons_lisp);
138     while(iter.next()) {
139       const std::string& token = iter.item();
140       if(token != "supertux-addoninfo") {
141         log_warning << "Unknown token '" << token << "' in Add-on list" << std::endl;
142         continue;
143       }
144       Addon* addon_ptr = new Addon();
145       Addon& addon = *addon_ptr;
146       addon.parse(*(iter.lisp()));
147       addon.installed = false;
148       addon.loaded = false;
149
150       // make sure the list of known Add-ons does not already contain this one 
151       bool exists = false;
152       for (std::vector<Addon*>::const_iterator i = addons.begin(); i != addons.end(); i++) {
153         if (**i == addon) {
154           exists = true; 
155           break; 
156         }
157       } 
158       if (exists) {
159         delete addon_ptr;
160         continue;
161       }
162
163       // make sure the Add-on's file name does not contain weird characters
164       if (addon.suggested_filename.find_first_not_of("match.quiz-proxy_gwenblvdjfks0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != std::string::npos) {
165         log_warning << "Add-on \"" << addon.title << "\" contains unsafe file name. Skipping." << std::endl;
166         delete addon_ptr;
167         continue;
168       }
169
170       addons.push_back(addon_ptr);
171     }
172   } catch(std::exception& e) {
173     std::stringstream msg;
174     msg << "Problem when reading Add-on list: " << e.what();
175     throw std::runtime_error(msg.str());
176   }
177
178 #endif
179 }
180
181 void
182 AddonManager::install(Addon* addon)
183 {
184 #ifdef HAVE_LIBCURL
185
186   if (addon->installed) throw std::runtime_error("Tried installing installed Add-on");
187
188   // make sure the Add-on's file name does not contain weird characters
189   if (addon->suggested_filename.find_first_not_of("match.quiz-proxy_gwenblvdjfks0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != std::string::npos) {
190     throw std::runtime_error("Add-on has unsafe file name (\""+addon->suggested_filename+"\")");
191   }
192
193   std::string fileName = addon->suggested_filename;
194
195   // make sure its file doesn't already exist
196   if (PHYSFS_exists(fileName.c_str())) {
197     fileName = addon->stored_md5 + "_" + addon->suggested_filename;
198     if (PHYSFS_exists(fileName.c_str())) {
199       throw std::runtime_error("Add-on of suggested filename already exists (\""+addon->suggested_filename+"\", \""+fileName+"\")");
200     }
201   }
202
203   char error_buffer[CURL_ERROR_SIZE+1];
204
205   char* url = (char*)malloc(addon->http_url.length() + 1);
206   strncpy(url, addon->http_url.c_str(), addon->http_url.length() + 1);
207
208   PHYSFS_file* f = PHYSFS_openWrite(fileName.c_str());
209
210   log_debug << "Downloading \"" << url << "\"" << std::endl;
211
212   CURL *curl_handle;
213   curl_handle = curl_easy_init();
214   curl_easy_setopt(curl_handle, CURLOPT_URL, url);
215   curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "SuperTux/" PACKAGE_VERSION " libcURL");
216   curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, my_curl_physfs_write);
217   curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, f);
218   curl_easy_setopt(curl_handle, CURLOPT_ERRORBUFFER, error_buffer);
219   curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1);
220   curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
221   curl_easy_setopt(curl_handle, CURLOPT_FAILONERROR, 1);
222   CURLcode result = curl_easy_perform(curl_handle);
223   curl_easy_cleanup(curl_handle);
224
225   PHYSFS_close(f);
226
227   free(url);
228
229   if (result != CURLE_OK) {
230     PHYSFS_delete(fileName.c_str());
231     std::string why = error_buffer[0] ? error_buffer : "unhandled error";
232     throw std::runtime_error("Downloading Add-on failed: " + why);
233   }
234
235   addon->installed = true;
236   addon->installed_physfs_filename = fileName;
237   static const std::string writeDir = PHYSFS_getWriteDir();
238   static const std::string dirSep = PHYSFS_getDirSeparator();
239   addon->installed_absolute_filename = writeDir + dirSep + fileName;
240   addon->loaded = false;
241
242   if (addon->get_md5() != addon->stored_md5) {
243     addon->installed = false;
244     PHYSFS_delete(fileName.c_str());
245     std::string why = "MD5 checksums differ"; 
246     throw std::runtime_error("Downloading Add-on failed: " + why);
247   }
248
249   log_debug << "Finished downloading \"" << addon->installed_absolute_filename << "\". Enabling Add-on." << std::endl;
250
251   enable(addon);
252
253 #else
254   (void) addon;
255 #endif
256
257 }
258
259 void
260 AddonManager::remove(Addon* addon)
261 {
262   if (!addon->installed) throw std::runtime_error("Tried removing non-installed Add-on");
263
264   //FIXME: more checks
265
266   // make sure the Add-on's file name does not contain weird characters
267   if (addon->installed_physfs_filename.find_first_not_of("match.quiz-proxy_gwenblvdjfks0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != std::string::npos) {
268     throw std::runtime_error("Add-on has unsafe file name (\""+addon->installed_physfs_filename+"\")");
269   }
270
271   unload(addon);
272
273   log_debug << "deleting file \"" << addon->installed_absolute_filename << "\"" << std::endl;
274   PHYSFS_delete(addon->installed_absolute_filename.c_str());
275   addon->installed = false;
276
277   // FIXME: As we don't know anything more about it (e.g. where to get it), remove it from list of known Add-ons
278 }
279
280 void
281 AddonManager::disable(Addon* addon)
282 {
283   unload(addon);
284
285   std::string fileName = addon->installed_physfs_filename;
286   if (std::find(ignored_addon_filenames.begin(), ignored_addon_filenames.end(), fileName) == ignored_addon_filenames.end()) {
287     ignored_addon_filenames.push_back(fileName);
288   }
289 }
290
291 void
292 AddonManager::enable(Addon* addon)
293 {
294   load(addon);
295
296   std::string fileName = addon->installed_physfs_filename;
297   std::vector<std::string>::iterator i = std::find(ignored_addon_filenames.begin(), ignored_addon_filenames.end(), fileName);
298   if (i != ignored_addon_filenames.end()) {
299     ignored_addon_filenames.erase(i);
300   }
301 }
302
303 void
304 AddonManager::unload(Addon* addon)
305 {
306   if (!addon->installed) throw std::runtime_error("Tried unloading non-installed Add-on");
307   if (!addon->loaded) return;
308
309   log_debug << "Removing archive \"" << addon->installed_absolute_filename << "\" from search path" << std::endl;
310   if (PHYSFS_removeFromSearchPath(addon->installed_absolute_filename.c_str()) == 0) {
311     log_warning << "Could not remove " << addon->installed_absolute_filename << " from search path. Ignoring." << std::endl;
312     return;
313   }
314
315   addon->loaded = false;
316 }
317
318 void
319 AddonManager::load(Addon* addon)
320 {
321   if (!addon->installed) throw std::runtime_error("Tried loading non-installed Add-on");
322   if (addon->loaded) return;
323
324   log_debug << "Adding archive \"" << addon->installed_absolute_filename << "\" to search path" << std::endl;
325   if (PHYSFS_addToSearchPath(addon->installed_absolute_filename.c_str(), 0) == 0) {
326     log_warning << "Could not add " << addon->installed_absolute_filename << " to search path. Ignoring." << std::endl;
327     return;
328   }
329
330   addon->loaded = true;
331 }
332
333 void
334 AddonManager::load_addons()
335 {
336   // unload all Addons and forget about them
337   for (std::vector<Addon*>::iterator i = addons.begin(); i != addons.end(); i++) {
338     if ((*i)->installed && (*i)->loaded) unload(*i);
339     delete *i;
340   }
341   addons.clear();
342
343   // Search for archives and add them to the search path
344   char** rc = PHYSFS_enumerateFiles("/");
345
346   for(char** i = rc; *i != 0; ++i) {
347
348     // get filename of potential archive
349     std::string fileName = *i;
350
351     const std::string archiveDir = PHYSFS_getRealDir(fileName.c_str());
352     static const std::string dirSep = PHYSFS_getDirSeparator();
353     std::string fullFilename = archiveDir + dirSep + fileName;
354
355     /*
356     // make sure it's in the writeDir
357     static const std::string writeDir = PHYSFS_getWriteDir();
358     if (fileName.compare(0, writeDir.length(), writeDir) != 0) continue;
359     */
360
361     // make sure it looks like an archive
362     static const std::string archiveExt = ".zip";
363     if (fullFilename.compare(fullFilename.length()-archiveExt.length(), archiveExt.length(), archiveExt) != 0) continue;
364
365     // make sure it exists
366     struct stat stats;
367     if (stat(fullFilename.c_str(), &stats) != 0) continue;
368
369     // make sure it's an actual file
370     if (!S_ISREG(stats.st_mode)) continue;
371
372     log_debug << "Found archive \"" << fullFilename << "\"" << std::endl;
373
374     // add archive to search path
375     PHYSFS_addToSearchPath(fullFilename.c_str(), 0);
376
377     // Search for infoFiles
378     std::string infoFileName = "";
379     char** rc2 = PHYSFS_enumerateFiles("/");
380     for(char** i = rc2; *i != 0; ++i) {
381
382       // get filename of potential infoFile
383       std::string potentialInfoFileName = *i;
384
385       // make sure it looks like an infoFile
386       static const std::string infoExt = ".nfo";
387       if (potentialInfoFileName.length() <= infoExt.length())
388         continue;
389
390       if (potentialInfoFileName.compare(potentialInfoFileName.length()-infoExt.length(), infoExt.length(), infoExt) != 0)
391         continue;
392
393       // make sure it's in the current archive
394       std::string infoFileDir = PHYSFS_getRealDir(potentialInfoFileName.c_str());
395       if (infoFileDir != fullFilename) continue;
396
397       // found infoFileName
398       infoFileName = potentialInfoFileName;
399       break;
400     }
401     PHYSFS_freeList(rc2);
402
403     // if we have an infoFile, it's an Addon
404     if (infoFileName != "") {
405       try {
406         Addon* addon = new Addon();
407         addon->parse(infoFileName);
408         addon->installed = true;
409         addon->installed_physfs_filename = fileName;
410         addon->installed_absolute_filename = fullFilename;
411         addon->loaded = true;
412         addons.push_back(addon);
413
414         // check if the Addon is disabled 
415         if (std::find(ignored_addon_filenames.begin(), ignored_addon_filenames.end(), fileName) != ignored_addon_filenames.end()) {
416           unload(addon);
417         }
418
419       } catch (const std::runtime_error& e) {
420         log_warning << "Could not load add-on info for " << fullFilename << ", loading as unmanaged:" << e.what() << std::endl;
421       }
422     }
423
424   }
425
426   PHYSFS_freeList(rc);
427 }
428
429 void
430 AddonManager::read(const Reader& lisp)
431 {
432   lisp.get("disabled-addons", ignored_addon_filenames); 
433 }
434
435 void
436 AddonManager::write(lisp::Writer& writer)
437 {
438   writer.write("disabled-addons", ignored_addon_filenames); 
439 }
440
441 /* EOF */