|
| 1 | +require 'json' |
| 2 | +require 'typhoeus' |
| 3 | +require 'fileutils' |
| 4 | + |
| 5 | +module Wpxf |
| 6 | + # A self updater that uses the latest release from GitHub as the target. |
| 7 | + class GitHubUpdater |
| 8 | + def latest_release_url |
| 9 | + 'https://api.github.com/repos/rastating/wordpress-exploit-framework/releases/latest' |
| 10 | + end |
| 11 | + |
| 12 | + # Get information about the latest update available on GitHub. |
| 13 | + # @param current_version [String] the current version number in use. |
| 14 | + # @return [Hash, nil] a hash containing the :release_notes, :zip_url and :release_name, or nil if there is no update. |
| 15 | + def get_update(current_version) |
| 16 | + res = Typhoeus.get(latest_release_url) |
| 17 | + return nil unless res && res.code == 200 |
| 18 | + |
| 19 | + begin |
| 20 | + update = JSON.parse(res.body) |
| 21 | + rescue JSON::ParserError |
| 22 | + return nil |
| 23 | + end |
| 24 | + |
| 25 | + begin |
| 26 | + return nil if Gem::Version.new(current_version) >= Gem::Version.new(update['tag_name'].sub(/^v/, '')) |
| 27 | + rescue |
| 28 | + return nil |
| 29 | + end |
| 30 | + |
| 31 | + { release_notes: update['body'], zip_url: update['zipball_url'], release_name: update['name'] } |
| 32 | + end |
| 33 | + |
| 34 | + # Download and apply an update from the specified URL. |
| 35 | + # @param zip_url [String] the URL to fetch the update from. |
| 36 | + def download_and_apply_update(zip_url) |
| 37 | + tmp = create_tmp_directory |
| 38 | + zip_filename = File.join(tmp, 'update.zip') |
| 39 | + |
| 40 | + download_update_zip(zip_url, zip_filename) |
| 41 | + |
| 42 | + Zip::File.open(zip_filename) do |zip_file| |
| 43 | + zip_file.each do |entry| |
| 44 | + entry.extract File.join(tmp, entry.name) |
| 45 | + end |
| 46 | + end |
| 47 | + |
| 48 | + Dir.glob(File.join(tmp, 'rastating-wordpress-exploit-framework*/*')) do |f| |
| 49 | + FileUtils.cp_r(f, Wpxf.app_path) |
| 50 | + end |
| 51 | + |
| 52 | + FileUtils.rm_rf(tmp) |
| 53 | + end |
| 54 | + |
| 55 | + private |
| 56 | + |
| 57 | + def create_tmp_directory |
| 58 | + tmp = File.join(Dir.tmpdir, "wpxf_update_#{object_id}") |
| 59 | + FileUtils.mkdir_p(tmp) |
| 60 | + tmp |
| 61 | + end |
| 62 | + |
| 63 | + def download_update_zip(zip_url, local_filename) |
| 64 | + zip = File.open(local_filename, 'wb') |
| 65 | + request = Typhoeus::Request.new(zip_url, followlocation: true) |
| 66 | + request.on_headers do |response| |
| 67 | + raise 'Request failed' if response.code != 200 |
| 68 | + end |
| 69 | + |
| 70 | + request.on_body do |chunk| |
| 71 | + zip.write(chunk) |
| 72 | + end |
| 73 | + |
| 74 | + request.on_complete do |
| 75 | + zip.close |
| 76 | + end |
| 77 | + |
| 78 | + request.run |
| 79 | + end |
| 80 | + end |
| 81 | +end |
0 commit comments