333 lines
14 KiB
Lua
333 lines
14 KiB
Lua
--[[--
|
|
BookSprite's stable-channel updater.
|
|
|
|
Only downloads and verifies an archive. The stable NickelMenu launcher,
|
|
outside koreader/, installs ../pending.tar.gz on the next launch. Never use
|
|
KOReader's installer or restart into the upstream launcher.
|
|
]]
|
|
|
|
local ConfirmBox = require("ui/widget/confirmbox")
|
|
local Device = require("device")
|
|
local InfoMessage = require("ui/widget/infomessage")
|
|
local NetworkMgr = require("ui/network/manager")
|
|
local UIManager = require("ui/uimanager")
|
|
local lfs = require("libs/libkoreader-lfs")
|
|
local logger = require("logger")
|
|
local util = require("util")
|
|
local _ = require("gettext")
|
|
local T = require("ffi/util").template
|
|
|
|
local MANIFEST_URL = "https://gitea.jameshall.xyz/exe.dev/booksprite/raw/branch/releases/stable.json"
|
|
local RELEASE_PREFIX = "https://gitea.jameshall.xyz/exe.dev/booksprite/releases/download/"
|
|
local UPDATE_HOST = "gitea.jameshall.xyz"
|
|
local MAX_ARCHIVE_SIZE = 250 * 1024 * 1024
|
|
local MAX_MANIFEST_SIZE = 16 * 1024
|
|
local PENDING_FILE = "../pending.tar.gz"
|
|
local DOWNLOAD_FILE = "../pending.tar.gz.part"
|
|
|
|
local OTAManager = {}
|
|
|
|
local function parseVersion(version)
|
|
if type(version) ~= "string" or #version > 32 then return end
|
|
local major, minor, patch = version:match("^(%d+)%.(%d+)%.(%d+)$")
|
|
if not major or #major > 9 or #minor > 9 or #patch > 9 then return end
|
|
for _, part in ipairs{ major, minor, patch } do
|
|
if #part > 1 and part:sub(1, 1) == "0" then return end
|
|
end
|
|
return { tonumber(major), tonumber(minor), tonumber(patch) }
|
|
end
|
|
|
|
local function isNewer(available, installed)
|
|
local a, b = parseVersion(available), parseVersion(installed)
|
|
if not a or not b then return false end
|
|
for i = 1, 3 do
|
|
if a[i] ~= b[i] then return a[i] > b[i] end
|
|
end
|
|
return false
|
|
end
|
|
|
|
function OTAManager:getCurrentVersion()
|
|
local file = io.open("booksprite-version", "rb")
|
|
if not file then return end
|
|
local version = file:read(64)
|
|
file:close()
|
|
version = version and version:match("^%s*(.-)%s*$")
|
|
if parseVersion(version) then return version end
|
|
end
|
|
|
|
function OTAManager:validateManifest(manifest)
|
|
if type(manifest) ~= "table" or manifest.target ~= "kobo" or manifest.target ~= Device:otaModel()
|
|
or not parseVersion(manifest.version)
|
|
or type(manifest.size) ~= "number" or manifest.size ~= manifest.size
|
|
or manifest.size <= 0 or manifest.size > MAX_ARCHIVE_SIZE
|
|
or manifest.size % 1 ~= 0
|
|
or type(manifest.sha256) ~= "string" or #manifest.sha256 ~= 64
|
|
or not manifest.sha256:match("^%x+$")
|
|
or type(manifest.url) ~= "string" or #manifest.url > 2048
|
|
or manifest.url:sub(1, #RELEASE_PREFIX) ~= RELEASE_PREFIX then
|
|
return nil, _("Invalid BookSprite update manifest.")
|
|
end
|
|
-- A release tag and a tar.gz filename only: no redirects, queries,
|
|
-- URL escapes, credentials, alternative ports, or traversal components.
|
|
local tag, filename = manifest.url:sub(#RELEASE_PREFIX + 1):match("^([%w._%-]+)/([%w._%-]+%.tar%.gz)$")
|
|
if not tag or tag == "." or tag == ".." or not filename then
|
|
return nil, _("Invalid BookSprite release URL.")
|
|
end
|
|
return {
|
|
version = manifest.version,
|
|
target = manifest.target,
|
|
size = manifest.size,
|
|
sha256 = manifest.sha256:lower(),
|
|
url = manifest.url,
|
|
}
|
|
end
|
|
|
|
-- LuaSec's default HTTPS configuration does not authenticate the peer. Use
|
|
-- the shipped CA bundle AND check the SAN hostname before sending HTTP data.
|
|
-- The fixed hostname makes wildcard matching deliberately restrictive.
|
|
function OTAManager:certificateMatchesHost(certificate)
|
|
if not certificate then return false end
|
|
local extensions = certificate:extensions()
|
|
local san = extensions and extensions["2.5.29.17"]
|
|
for _, name in ipairs(san and san.dNSName or {}) do
|
|
name = name:lower()
|
|
if name == UPDATE_HOST or name == "*.jameshall.xyz" then return true end
|
|
end
|
|
return false
|
|
end
|
|
|
|
function OTAManager:createTLSConnection()
|
|
local socket = require("socket")
|
|
local ssl = require("ssl")
|
|
local sock, err = socket.tcp()
|
|
if not sock then return nil, err end
|
|
local connection = { sock = sock }
|
|
local manager = self
|
|
function connection:settimeout()
|
|
return self.sock:settimeout(15)
|
|
end
|
|
function connection:close()
|
|
return self.sock:close()
|
|
end
|
|
function connection:connect(host, port)
|
|
if host ~= UPDATE_HOST or tonumber(port) ~= 443 then
|
|
return nil, "BookSprite update host is not allowed"
|
|
end
|
|
local ok, connect_err = self.sock:connect(host, port)
|
|
if not ok then return nil, connect_err end
|
|
local wrapped, wrap_err = ssl.wrap(self.sock, {
|
|
mode = "client",
|
|
protocol = "any",
|
|
options = { "all", "no_sslv2", "no_sslv3", "no_tlsv1", "no_tlsv1_1" },
|
|
verify = "peer",
|
|
cafile = "data/ca-bundle.crt",
|
|
})
|
|
if not wrapped then return nil, wrap_err end
|
|
self.sock = wrapped
|
|
self.sock:settimeout(15)
|
|
self.sock:sni(host)
|
|
local handshake_ok, handshake_err = self.sock:dohandshake()
|
|
if not handshake_ok then return nil, handshake_err end
|
|
if not manager:certificateMatchesHost(self.sock:getpeercertificate()) then
|
|
return nil, "BookSprite update certificate hostname mismatch"
|
|
end
|
|
return 1
|
|
end
|
|
for _, method in ipairs{ "send", "receive", "getfd", "dirty" } do
|
|
connection[method] = function(this, ...)
|
|
return this.sock[method](this.sock, ...)
|
|
end
|
|
end
|
|
return connection
|
|
end
|
|
|
|
function OTAManager:requestHTTPS(url, sink, limit, timeout)
|
|
if url ~= MANIFEST_URL and url:sub(1, #RELEASE_PREFIX) ~= RELEASE_PREFIX then
|
|
return nil, _("BookSprite update host is not allowed.")
|
|
end
|
|
local http = require("socket.http")
|
|
local socket = require("socket")
|
|
if http.PROXY then return nil, _("Disable the HTTP proxy before updating BookSprite.") end
|
|
local started, bytes = socket.gettime(), 0
|
|
local connection
|
|
local ok, result, code = pcall(http.request, {
|
|
url = url,
|
|
redirect = false,
|
|
headers = { ["accept-encoding"] = "identity" },
|
|
create = function()
|
|
local err
|
|
connection, err = self:createTLSConnection()
|
|
return connection, err
|
|
end,
|
|
sink = function(chunk, err)
|
|
if socket.gettime() - started > timeout then
|
|
return nil, "BookSprite update download timed out"
|
|
end
|
|
if err then return nil, err end
|
|
if chunk then
|
|
bytes = bytes + #chunk
|
|
if bytes > limit then return nil, "BookSprite update exceeds size limit" end
|
|
return sink(chunk)
|
|
end
|
|
return 1
|
|
end,
|
|
})
|
|
-- Also close on exceptions, e.g. a sink write failure or TLS API error.
|
|
if connection then pcall(connection.close, connection) end
|
|
if not ok or not result or tonumber(code) ~= 200 then
|
|
logger.warn("BookSprite update request failed:", ok and code or result)
|
|
return nil, _("Unable to download the BookSprite update. Check Wi-Fi, free space, and the device clock, then try again.")
|
|
end
|
|
return bytes
|
|
end
|
|
|
|
function OTAManager:getInstallationError()
|
|
if not Device:isKobo() or not lfs.currentdir():match("/%.adds/booksprite/koreader$") then
|
|
return _("BookSprite updates require the separate .adds/booksprite installation.")
|
|
end
|
|
if Device:otaModel() ~= "kobo" then
|
|
return _("This BookSprite update channel supports standard Kobo devices only, not Kobo firmware 5 devices.")
|
|
end
|
|
end
|
|
|
|
function OTAManager:checkUpdate()
|
|
local installation_err = self:getInstallationError()
|
|
if installation_err then return nil, nil, installation_err end
|
|
local installed = self:getCurrentVersion()
|
|
if not installed then
|
|
return nil, nil, _("Cannot read booksprite-version. Reinstall the BookSprite package.")
|
|
end
|
|
local chunks = {}
|
|
local bytes, err = self:requestHTTPS(MANIFEST_URL, function(chunk)
|
|
chunks[#chunks + 1] = chunk
|
|
return 1
|
|
end, MAX_MANIFEST_SIZE, 30)
|
|
if not bytes then return nil, nil, err end
|
|
local ok, decoded = pcall(require("json").decode, table.concat(chunks))
|
|
if not ok then return nil, nil, _("Invalid BookSprite update manifest.") end
|
|
local manifest, validation_err = self:validateManifest(decoded)
|
|
if not manifest then return nil, nil, validation_err end
|
|
if not isNewer(manifest.version, installed) then return false, installed end
|
|
return manifest, installed
|
|
end
|
|
|
|
function OTAManager:downloadUpdate(manifest)
|
|
local installation_err = self:getInstallationError()
|
|
if installation_err then return nil, installation_err end
|
|
-- Validate again at the point of use; no untrusted values reach a shell.
|
|
local validated, err = self:validateManifest(manifest)
|
|
if not validated then return nil, err end
|
|
manifest = validated
|
|
if lfs.symlinkattributes(PENDING_FILE) then
|
|
return nil, _("A BookSprite update is already ready. Exit and relaunch BookSprite from NickelMenu.")
|
|
end
|
|
local disk = util.diskUsage("..")
|
|
-- Reserve room for the archive and extraction. The launcher must also
|
|
-- check actual unpacked size before swapping the application directories.
|
|
if not disk.available or disk.available < math.max(1024 * 1024 * 1024, manifest.size * 4 + 32 * 1024 * 1024) then
|
|
return nil, _("Not enough free space to safely download and unpack BookSprite.")
|
|
end
|
|
os.remove(DOWNLOAD_FILE)
|
|
local file, open_err = io.open(DOWNLOAD_FILE, "wb")
|
|
if not file then
|
|
logger.warn("BookSprite update staging failed:", open_err)
|
|
return nil, _("Cannot create the BookSprite update download.")
|
|
end
|
|
local ok, bytes, download_err = pcall(function()
|
|
local hash = require("ffi/sha2").sha256()
|
|
local count, request_err = self:requestHTTPS(manifest.url, function(chunk)
|
|
local written, write_err = file:write(chunk)
|
|
if not written then return nil, write_err end
|
|
hash(chunk)
|
|
return 1
|
|
end, manifest.size, 30 * 60)
|
|
if not count then return nil, request_err end
|
|
if count ~= manifest.size or hash() ~= manifest.sha256 then
|
|
return nil, _("BookSprite update verification failed (size or SHA-256 mismatch). Please try again.")
|
|
end
|
|
return count
|
|
end)
|
|
local closed = file:close()
|
|
if not ok or not bytes or not closed then
|
|
os.remove(DOWNLOAD_FILE)
|
|
return nil, (ok and download_err) or _("Unable to verify or save the BookSprite update.")
|
|
end
|
|
-- Publish the verified, complete archive in one same-filesystem rename.
|
|
-- It contains ONLY koreader/; it never updates launch.sh itself.
|
|
local renamed, rename_err = os.rename(DOWNLOAD_FILE, PENDING_FILE)
|
|
if not renamed then
|
|
os.remove(DOWNLOAD_FILE)
|
|
logger.warn("BookSprite update rename failed:", rename_err)
|
|
return nil, _("Cannot stage the verified BookSprite update.")
|
|
end
|
|
return true
|
|
end
|
|
|
|
function OTAManager:showStatus(text)
|
|
UIManager:show(InfoMessage:new{ text = text })
|
|
end
|
|
|
|
function OTAManager:runWithProgress(text, callback)
|
|
if self.busy then return end
|
|
self.busy = true
|
|
local message = InfoMessage:new{ text = text }
|
|
UIManager:show(message)
|
|
UIManager:forceRePaint()
|
|
UIManager:scheduleIn(0.1, function()
|
|
local ok, err = pcall(callback)
|
|
self.busy = false
|
|
UIManager:close(message)
|
|
if not ok then
|
|
logger.warn("BookSprite updater failed:", err)
|
|
self:showStatus(_("BookSprite update failed. Please try again."))
|
|
end
|
|
end)
|
|
end
|
|
|
|
function OTAManager:fetchAndProcessUpdate()
|
|
if lfs.symlinkattributes(PENDING_FILE) then
|
|
self:showStatus(_("A BookSprite update is ready.\n\nExit BookSprite, then launch BookSprite again from NickelMenu to install it. Do not use KOReader's restart command."))
|
|
return
|
|
end
|
|
self:runWithProgress(_("Checking for BookSprite updates…"), function()
|
|
local manifest, installed, err = self:checkUpdate()
|
|
if manifest == false then
|
|
self:showStatus(T(_("BookSprite is up to date.\nInstalled version: %1"), installed))
|
|
elseif not manifest then
|
|
self:showStatus(err)
|
|
else
|
|
UIManager:show(ConfirmBox:new{
|
|
text = T(_("Download BookSprite update?\n\nInstalled version: %1\nAvailable version: %2\n\nThe update will be installed when you exit and relaunch BookSprite from NickelMenu."),
|
|
installed, manifest.version),
|
|
ok_text = _("Download"),
|
|
ok_callback = function()
|
|
NetworkMgr:runWhenOnline(function()
|
|
self:runWithProgress(_("Downloading and verifying BookSprite…\n\nThis may take several minutes."), function()
|
|
local downloaded, download_err = self:downloadUpdate(manifest)
|
|
self:showStatus(downloaded
|
|
and _("BookSprite update verified and ready.\n\nExit BookSprite, then launch BookSprite again from NickelMenu to install it. Your previous version will be kept for rollback. Do not use KOReader's restart command.")
|
|
or download_err)
|
|
end)
|
|
end)
|
|
end,
|
|
})
|
|
end
|
|
end)
|
|
end
|
|
|
|
function OTAManager:getOTAMenuTable()
|
|
local check = function()
|
|
NetworkMgr:runWhenOnline(function() self:fetchAndProcessUpdate() end)
|
|
end
|
|
return {
|
|
text = _("BookSprite update"),
|
|
hold_callback = check,
|
|
sub_item_table = {
|
|
{ text = _("Check for BookSprite updates"), callback = check },
|
|
{ text = _("Channel: BookSprite stable"), enabled = false },
|
|
},
|
|
}
|
|
end
|
|
|
|
return OTAManager
|