diff --git a/CrownClient/CrownClient.cpp b/CrownClient/CrownClient.cpp index 2448088..6cd6322 100644 --- a/CrownClient/CrownClient.cpp +++ b/CrownClient/CrownClient.cpp @@ -195,7 +195,8 @@ CrownClient::CrownClient(QWidget *parent) }); // 显示账号和到期时间 - ui.endtimeLabel->setText("

软件登录账号: " + g_verify->Username() + QString(" 软件到期时间: ") + g_verify->GetDueTime().toString("yyyy-MM-dd hh:MM:ss") + "

"); + // 到期文案由 Verify 统一拼:永久授权 / 剩余点数 / 到期日期,三种计费各显示各的 + ui.endtimeLabel->setText("

软件登录账号: " + g_verify->Username() + QString(" 软件到期时间: ") + g_verify->DueTimeText() + "

"); @@ -2808,8 +2809,9 @@ void CrownClient::heartbeat() qDebug() << "心跳失败:" << result; } - // 检查授权到期时间 - if (g_verify->GetDueTime().msecsTo(QDateTime::currentDateTime()) >= 0) { + // 检查授权到期时间;永久授权和点数计费没有到期日,GetDueTime 是占位日期,不会走到这里 + QDateTime dueTime = g_verify->GetDueTime(); + if (dueTime.isValid() && dueTime.msecsTo(QDateTime::currentDateTime()) >= 0) { QMessageBox::critical(nullptr, "错误", "授权已到期!"); QApplication::quit(); } diff --git a/CrownClient/CrownClient.vcxproj b/CrownClient/CrownClient.vcxproj index b2fe081..3eba667 100644 --- a/CrownClient/CrownClient.vcxproj +++ b/CrownClient/CrownClient.vcxproj @@ -21,16 +21,16 @@ {C339197A-FFBA-4AE7-81FA-325702162EC1} QtVS_v304 - 10.0.17763.0 + 10.0.19041.0 10.0 - 10.0.17763.0 + 10.0.19041.0 10.0 $(MSBuildProjectDirectory)\QtMsBuild Application - v141 + v142 false @@ -39,7 +39,7 @@ Application - v141 + v142 Application @@ -105,10 +105,10 @@ /utf-8 %(AdditionalOptions) - D:\开发工具\VMProtect\Include\C;%(AdditionalIncludeDirectories) + D:\reverse\vmprotect33\Include\C;%(AdditionalIncludeDirectories) - D:\开发工具\VMProtect\Lib\Windows;%(AdditionalLibraryDirectories) + D:\reverse\vmprotect33\Lib\Windows;%(AdditionalLibraryDirectories) @@ -119,10 +119,10 @@ /utf-8 %(AdditionalOptions) - D:\开发工具\VMProtect\Include\C;%(AdditionalIncludeDirectories) + D:\reverse\vmprotect33\Include\C;%(AdditionalIncludeDirectories) - D:\开发工具\VMProtect\Lib\Windows;%(AdditionalLibraryDirectories) + D:\reverse\vmprotect33\Lib\Windows;%(AdditionalLibraryDirectories) diff --git a/CrownClient/Verify.cpp b/CrownClient/Verify.cpp index 3fbabeb..cc55597 100644 --- a/CrownClient/Verify.cpp +++ b/CrownClient/Verify.cpp @@ -1,14 +1,24 @@ #include "Verify.h" #include "Global.h" +#pragma comment(lib, "bcrypt.lib") + +#include +#include +#include +#include +#include + +// 一次网络请求最多等多久,超时就放弃,别把心跳线程卡死 +#define VERIFY_REQUEST_TIMEOUT 15000 /// /// 构造函数 /// -/// -/// -/// -/// +/// verify 站点地址,如 https://gendan.xyz +/// 后台「应用 -> AppKey」 +/// 后台「应用 -> EncryptKey」 +/// 客户端版本 Verify::Verify(QString Url, QString AppId, QString CommKey, QString Verison) { VMProtectBegin("Verify_Init"); @@ -18,13 +28,17 @@ Verify::Verify(QString Url, QString AppId, QString CommKey, QString Verison) m_appId = this->ParamEncrypt(AppId); m_commKey = this->ParamEncrypt(CommKey); - m_webApi = this->ParamEncrypt(Url + "/api_new.php?"); + m_webApi = this->ParamEncrypt(Url); m_machineCode = this->GetCPUID(); m_version = Verison; + // 同一台机器多开时用实例ID区分,服务端拿它做会话粒度 + m_instanceId = QUuid::createUuid().toString(QUuid::WithoutBraces); + + m_permanent = false; + m_balance = 0; //qDebug() << "验证网址:" << Url; - //qDebug() << "软件ID:" << AppId; - //qDebug() << "通信密钥:" << CommKey; + //qDebug() << "应用AppKey:" << AppId; //qDebug() << "软件版本:" << Verison; //qDebug() << "机器码:" << this->GetCPUID(); VMProtectEnd(); @@ -329,223 +343,440 @@ QString Verify::ParamDecrypt(QString Param) VMProtectEnd(); } - -QString ByteArrayToHexString(QByteArray data) { - QString ret(data.toHex().toUpper()); - int len = ret.length() / 2; - //qDebug() << len; - for (int i = 1; i < len; i++) +// 后端 crypto.padKey 的等价实现:不足 32 字节循环补齐,超过 32 字节直接截断 +static QByteArray PadAesKey(const QByteArray& Secret) +{ + QByteArray key(32, '\0'); + if (Secret.isEmpty()) { - //qDebug() << i; - ret.insert(2 * i + i - 1, " "); + return key; } - - return ret; + // 后端只有 16/24/32 三种长度会原样使用,这里统一补到 32,跟它 padKey(32) 的结果一致 + if (Secret.size() != 16 && Secret.size() != 24 && Secret.size() != 32) + { + for (int i = 0; i < key.size(); ++i) + { + key[i] = Secret[i % Secret.size()]; + } + return key; + } + return Secret; } -// 发送网络请求 -bool Verify::Send(QString Option, QString Data, QString& Result,bool async) +// 打开一个 GCM 模式的 AES 算法句柄 +static BCRYPT_ALG_HANDLE OpenAesGcm() +{ + BCRYPT_ALG_HANDLE alg = nullptr; + if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0))) + { + return nullptr; + } + ULONG modeLength = (ULONG)((wcslen(BCRYPT_CHAIN_MODE_GCM) + 1) * sizeof(wchar_t)); + if (!BCRYPT_SUCCESS(BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, + (PUCHAR)BCRYPT_CHAIN_MODE_GCM, modeLength, 0))) + { + BCryptCloseAlgorithmProvider(alg, 0); + return nullptr; + } + return alg; +} + +// AES-256-GCM,输出 nonce(12) || 密文 || tag(16) +QByteArray Verify::AesGcmEncrypt(const QByteArray& Plain, bool& Ok) +{ + VMProtectBegin("Verify_AesEnc"); + Ok = false; + + QByteArray key = PadAesKey(ParamDecrypt(m_commKey).toUtf8()); + BCRYPT_ALG_HANDLE alg = OpenAesGcm(); + if (alg == nullptr) + { + VMProtectEnd(); + return QByteArray(); + } + + BCRYPT_KEY_HANDLE keyHandle = nullptr; + if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(alg, &keyHandle, nullptr, 0, + (PUCHAR)key.data(), (ULONG)key.size(), 0))) + { + BCryptCloseAlgorithmProvider(alg, 0); + VMProtectEnd(); + return QByteArray(); + } + + const int nonceSize = 12; + const int tagSize = 16; + QByteArray nonce(nonceSize, '\0'); + BCryptGenRandom(nullptr, (PUCHAR)nonce.data(), (ULONG)nonce.size(), BCRYPT_USE_SYSTEM_PREFERRED_RNG); + + QByteArray cipher(Plain.size(), '\0'); + QByteArray tag(tagSize, '\0'); + + BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; + BCRYPT_INIT_AUTH_MODE_INFO(info); + info.pbNonce = (PUCHAR)nonce.data(); + info.cbNonce = (ULONG)nonce.size(); + info.pbTag = (PUCHAR)tag.data(); + info.cbTag = (ULONG)tag.size(); + + ULONG written = 0; + NTSTATUS status = BCryptEncrypt(keyHandle, + (PUCHAR)Plain.data(), (ULONG)Plain.size(), + &info, nullptr, 0, + (PUCHAR)cipher.data(), (ULONG)cipher.size(), &written, 0); + + BCryptDestroyKey(keyHandle); + BCryptCloseAlgorithmProvider(alg, 0); + + if (!BCRYPT_SUCCESS(status) || (int)written != Plain.size()) + { + VMProtectEnd(); + return QByteArray(); + } + + Ok = true; + VMProtectEnd(); + return nonce + cipher + tag; +} + +// AES-256-GCM,输入 nonce(12) || 密文 || tag(16),tag 校验不过直接失败 +QByteArray Verify::AesGcmDecrypt(const QByteArray& Cipher, bool& Ok) +{ + VMProtectBegin("Verify_AesDec"); + Ok = false; + + const int nonceSize = 12; + const int tagSize = 16; + if (Cipher.size() < nonceSize + tagSize) + { + VMProtectEnd(); + return QByteArray(); + } + + QByteArray key = PadAesKey(ParamDecrypt(m_commKey).toUtf8()); + BCRYPT_ALG_HANDLE alg = OpenAesGcm(); + if (alg == nullptr) + { + VMProtectEnd(); + return QByteArray(); + } + + BCRYPT_KEY_HANDLE keyHandle = nullptr; + if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(alg, &keyHandle, nullptr, 0, + (PUCHAR)key.data(), (ULONG)key.size(), 0))) + { + BCryptCloseAlgorithmProvider(alg, 0); + VMProtectEnd(); + return QByteArray(); + } + + QByteArray nonce = Cipher.left(nonceSize); + QByteArray tag = Cipher.right(tagSize); + QByteArray body = Cipher.mid(nonceSize, Cipher.size() - nonceSize - tagSize); + + BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; + BCRYPT_INIT_AUTH_MODE_INFO(info); + info.pbNonce = (PUCHAR)nonce.data(); + info.cbNonce = (ULONG)nonce.size(); + info.pbTag = (PUCHAR)tag.data(); + info.cbTag = (ULONG)tag.size(); + + QByteArray plain(body.size(), '\0'); + ULONG written = 0; + NTSTATUS status = BCryptDecrypt(keyHandle, + (PUCHAR)body.data(), (ULONG)body.size(), + &info, nullptr, 0, + (PUCHAR)plain.data(), (ULONG)plain.size(), &written, 0); + + BCryptDestroyKey(keyHandle); + BCryptCloseAlgorithmProvider(alg, 0); + + if (!BCRYPT_SUCCESS(status)) + { + VMProtectEnd(); + return QByteArray(); + } + + Ok = true; + VMProtectEnd(); + return plain; +} + +QString Verify::EncryptBody(const QString& Plain, bool& Ok) +{ + Ok = true; +#if VERIFY_ENCRYPT_TYPE == 2 + QByteArray cipher = AesGcmEncrypt(Plain.toUtf8(), Ok); + return Ok ? QString::fromLatin1(cipher.toBase64()) : QString(); +#elif VERIFY_ENCRYPT_TYPE == 1 + return QString::fromLatin1(RC4(Plain.toUtf8(), ParamDecrypt(m_commKey)).toBase64()); +#else + return Plain; +#endif +} + +QString Verify::DecryptBody(const QString& Cipher, bool& Ok) +{ + Ok = true; +#if VERIFY_ENCRYPT_TYPE == 2 + QByteArray plain = AesGcmDecrypt(QByteArray::fromBase64(Cipher.toLatin1()), Ok); + return Ok ? QString::fromUtf8(plain) : QString(); +#elif VERIFY_ENCRYPT_TYPE == 1 + return QString::fromUtf8(RC4(QByteArray::fromBase64(Cipher.toLatin1()), ParamDecrypt(m_commKey))); +#else + return Cipher; +#endif +} + +// 发一个 /api/v1/app/{appKey} 请求 +// 请求体加密后放进 {"data": "..."},响应是 {"data": "..."},解密出来才是 {code,message,data} +bool Verify::Request(const QString& Path, const QJsonObject& Body, QJsonValue& Data, + QString& Result, bool WithToken, const QString& Method) { VMProtectBegin("Verify_Send"); - QNetworkAccessManager networkAccessManager; - // 获取当前时间戳 - QDateTime timeDate = QDateTime::currentDateTime(); - QString timestamp = QString::number(timeDate.toSecsSinceEpoch()); - //qDebug() << "解密:" << ParamDecrypt(m_commKey); - // 获取签名 - // 转为十六进制文本 - QString PostData; - PostData.append(RC4(Data.toUtf8(), ParamDecrypt(m_commKey)).toHex()); - - //qDebug() << "RC4的结果:" << PostData; - QByteArray PostByte = PostData.toUtf8(); - //qDebug() << "RC4结果:" << PostByte.toHex(); - QByteArray SignData = PostByte + timestamp.toUtf8() + ParamDecrypt(m_commKey).toUtf8(); - // 转换为十六进制字符串 - - QString md5 = this->Md5(SignData); - // a98d0872e603bc63f04767a14617df64 - //qDebug() << "md5:" << md5; - QUrl strUrl = ParamDecrypt(m_webApi) + "&mod=" + Option + "&appId=" + this->ParamDecrypt(m_appId) + "&sign=" + md5 + "×tamp=" + timestamp; - //qDebug() << "访问地址:" << strUrl; - // 网络请求 - QNetworkRequest request; - // 设置请求地址 - request.setUrl(strUrl); - // 设置请求头 - // request.setRawHeader("Content-Type", "charset='utf-8'"); - request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");// "charset='utf-8'" - //request.setRawHeader("Content-Type", "application/json"); - // 网络应答 - - QNetworkReply* reply = networkAccessManager.post(request, PostData.toUtf8()); - QByteArray responseData; - - if (!async) + if (WithToken && m_token.isEmpty()) { - // 事件循环 - QEventLoop eventLoop; - // 连接信号和槽 - connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); - // 开始循环 - eventLoop.exec(); + Result = "未登录"; + VMProtectEnd(); + return false; } + bool ok = false; + QString encrypted = EncryptBody(QString::fromUtf8(QJsonDocument(Body).toJson(QJsonDocument::Compact)), ok); + if (!ok) + { + Result = "请求加密失败"; + VMProtectEnd(); + return false; + } + + QJsonObject envelope; + envelope.insert("data", encrypted); + + QNetworkAccessManager networkAccessManager; + QNetworkRequest request; + request.setUrl(QUrl(ParamDecrypt(m_webApi) + "/api/v1/app/" + ParamDecrypt(m_appId) + Path)); + // 服务端只在 Content-Type 非空时才解密请求体,这个头不能省 + request.setRawHeader("Content-Type", "application/json"); + if (WithToken) + { + request.setRawHeader("Authorization", ("Bearer " + m_token).toUtf8()); + } + + QNetworkReply* reply = (Method == "GET") + ? networkAccessManager.get(request) + : networkAccessManager.post(request, QJsonDocument(envelope).toJson(QJsonDocument::Compact)); + + QTimer timer; + timer.setSingleShot(true); + QEventLoop eventLoop; + connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit())); + connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); + timer.start(VERIFY_REQUEST_TIMEOUT); + eventLoop.exec(); + + if (!reply->isFinished()) + { + reply->abort(); + reply->deleteLater(); + Result = "请求超时"; + VMProtectEnd(); + return false; + } - //错误处理 if (reply->error() != QNetworkReply::NoError) { - qDebug() << "Request protobufHttp handle errors here"; - QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); - // statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档 - qDebug("request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error()); - qDebug(qPrintable(reply->errorString())); + Result = "网络错误: " + reply->errorString(); reply->deleteLater(); - return ""; + VMProtectEnd(); + return false; } - //RC4(QByteArray::fromHex(数据.toUtf8()), ParamDecrypt(m_commKey)); - //QString strReply = reply->readAll(); - QString result = reply->readAll();//RC4(QByteArray::fromHex(reply->readAll()),ParamDecrypt(m_commKey)); - //qDebug() << "访问结果:" << result.toStdString().c_str(); + QByteArray responseData = reply->readAll(); reply->deleteLater(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) + QJsonDocument wrapped = QJsonDocument::fromJson(responseData); + if (!wrapped.isObject()) { - qDebug() << "String NULL";; + Result = "服务器返回格式错误"; + VMProtectEnd(); + return false; } - QJsonObject jsonObject = jsonDocument.object(); - QString jsonCode = jsonObject["code"].toVariant().toString();//QString::number(jsonObject["code"].toInt()); - QString jsonMsg = jsonObject["msg"].toVariant().toString(); - QString jsonData = jsonObject["data"].toVariant().toString(); - QString jsonSign = jsonObject["sign"].toVariant().toString(); - QString jsonTampstamp = jsonObject["timestamp"].toVariant().toString(); - Result = RC4(QByteArray::fromHex(jsonData.toUtf8()), ParamDecrypt(m_commKey)); - if (!jsonSign.isEmpty()) + // 应用不存在 / 应用被禁用这类错误在加密中间件之前就返回了,没有 data 信封,是明文 + QJsonValue payload = wrapped.object().value("data"); + QString plain; + if (payload.isString()) { - QString verifySign = this->Md5(jsonCode.toUtf8() + jsonMsg.toUtf8() + jsonData.toUtf8()); - if (verifySign != jsonSign) + plain = DecryptBody(payload.toString(), ok); + if (!ok) { - Result = "数据校验失败"; + Result = "响应解密失败"; + VMProtectEnd(); return false; } } - //qDebug() << "解密结果" << jsonObject["msg"].toVariant().toString();; - - if (jsonCode == "1") + else { - return true; + plain = QString::fromUtf8(responseData); } - Result = jsonObject["msg"].toVariant().toString(); - return false; + QJsonDocument response = QJsonDocument::fromJson(plain.toUtf8()); + if (!response.isObject()) + { + Result = "响应解密失败"; + VMProtectEnd(); + return false; + } + + QJsonObject jsonObject = response.object(); + int code = jsonObject.value("code").toVariant().toInt(); + Result = jsonObject.value("message").toVariant().toString(); + if (code != 200) + { + if (Result.isEmpty()) + { + Result = QString("请求失败(%1)").arg(code); + } + VMProtectEnd(); + return false; + } + + Data = jsonObject.value("data"); VMProtectEnd(); + return true; } +// 登录和心跳返回同一套计费字段: +// Balance == -1 -> is_permanent +// billing_type 订阅 -> expiry_at + expiry_timestamp +// 其他非免费计费 -> balance +void Verify::ParseBilling(const QJsonObject& Data) +{ + m_permanent = false; + m_balance = 0; + + if (Data.value("is_permanent").toVariant().toBool()) + { + m_billingMode = "permanent"; + m_permanent = true; + m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59)); + return; + } + + if (Data.contains("expiry_at") || Data.contains("expiry_timestamp")) + { + m_billingMode = "subscription"; + // 必须用 expiry_timestamp。服务器按 UTC 格式化 expiry_at,直接拿这个字符串当本地时间 + // 解析会早 8 个小时,用户会被提前踢下线。expiry_at 只在拿不到时间戳时才兜底 + qint64 stamp = Data.value("expiry_timestamp").toVariant().toLongLong(); + if (stamp > 0) + { + m_dueTime = QDateTime::fromSecsSinceEpoch(stamp); + } + else + { + m_dueTime = QDateTime::fromString(Data.value("expiry_at").toVariant().toString(), "yyyy-MM-dd HH:mm:ss"); + } + return; + } + + if (Data.contains("balance")) + { + m_billingMode = "balance"; + m_balance = Data.value("balance").toVariant().toDouble(); + m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59)); + return; + } + + // 免费应用没有计费字段,同样不存在到期一说 + m_billingMode = "free"; + m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59)); +} bool Verify::Login(QString Username, QString Password, QString& result) { VMProtectBegin("Verify_Login"); + QJsonObject JsonObject; JsonObject.insert("username", Username); JsonObject.insert("password", Password); - JsonObject.insert("hardwareCode", m_machineCode); - QJsonDocument jsonDoc = QJsonDocument(JsonObject); - QString post_data = jsonDoc.toJson(QJsonDocument::Compact); - //qDebug() << "参数:" << post_data.toStdString().c_str(); - if (!Send("login", post_data, result)) + // 后台把 device_id 当必填项,用机器码顶上,和旧协议的 hardwareCode 一个作用 + JsonObject.insert("device_id", m_machineCode); + JsonObject.insert("device_name", QSysInfo::machineHostName()); + JsonObject.insert("device_type", "windows"); + JsonObject.insert("instance_id", m_instanceId); + + QJsonValue data; + if (!Request("/login", JsonObject, data, result, false)) { - //qDebug() << "登录失败:" << result.toStdString().c_str(); - //result = "登录失败"; + VMProtectEnd(); return false; } - //qDebug() << "登录成功:" << result.toStdString().c_str(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) + + QJsonObject object = data.toObject(); + m_token = object.value("token").toVariant().toString(); + if (m_token.isEmpty()) { - //qDebug() << "String NULL";; - //result = "登录失败"; + result = "登录失败:服务端没有返回令牌"; + VMProtectEnd(); return false; } - QJsonObject jsonObject = jsonDocument.object(); - QString jsonTime = jsonObject["expireTime"].toVariant().toString(); - m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss"); + m_username = Username; m_password = Password; - return true; + ParseBilling(object); + VMProtectEnd(); + return true; } bool Verify::Heartbeat(QString& result) { VMProtectBegin("Verify_Heartbeat"); - QJsonObject JsonObject; - JsonObject.insert("username", m_username); - JsonObject.insert("password", m_password); - JsonObject.insert("hardwareCode", m_machineCode); - QJsonDocument jsonDoc = QJsonDocument(JsonObject); - QString post_data = jsonDoc.toJson(QJsonDocument::Compact); - //qDebug() << "参数:" << post_data.toStdString().c_str(); - if (!Send("heartbeat", post_data, result)) - { - //qDebug() << "登录失败:" << result.toStdString().c_str(); - return false; - } - //qDebug() << "登录成功:" << result.toStdString().c_str(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) - { - //qDebug() << "String NULL";; - return false; - } - QJsonObject jsonObject = jsonDocument.object(); - QString jsonTime = jsonObject["expireTime"].toVariant().toString(); - m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss"); - return true; + QJsonObject JsonObject; + // 心跳的身份信息全在 JWT 里,请求体只需要实例ID + JsonObject.insert("instance_id", m_instanceId); + + QJsonValue data; + if (!Request("/heartbeat", JsonObject, data, result, true)) + { + VMProtectEnd(); + return false; + } + + ParseBilling(data.toObject()); + VMProtectEnd(); + return true; } bool Verify::checkUpdate() { VMProtectBegin("Verify_Check"); + QString result; - QJsonObject JsonObject; - JsonObject.insert("username", m_username); - JsonObject.insert("password", m_password); - JsonObject.insert("hardwareCode", m_machineCode); - QJsonDocument jsonDoc = QJsonDocument(JsonObject); - QString post_data = jsonDoc.toJson(QJsonDocument::Compact); - //qDebug() << "参数:" << post_data.toStdString().c_str(); - if (!Send("version", post_data, result)) + QJsonValue data; + if (!Request("/check-update?version=" + QUrl::toPercentEncoding(m_version), + QJsonObject(), data, result, false, "GET")) { - //qDebug() << "获取版本失败:" << result.toStdString().c_str(); - return false; + // 拿不到更新信息就当是最新,别拦着主程序启动 + VMProtectEnd(); + return true; } - //qDebug() << "获取版本成功:" << result.toStdString().c_str(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) + + QJsonObject object = data.toObject(); + QString latest = object.value("latest_version").toVariant().toString(); + if (!latest.isEmpty()) { - //qDebug() << "String NULL";; - return false; - } - QJsonObject jsonObject = jsonDocument.object(); - QString version = jsonObject["version"].toVariant().toString(); - //qDebug() << "最新版本:" << version; - if (m_version == version) - { - //qDebug() << "验证结果: 真"; - } - else - { - //qDebug() << "验证结果: 假"; + VMProtectEnd(); + return latest == m_version; } - return version == m_version; VMProtectEnd(); + return !object.value("has_update").toVariant().toBool(); } QString Verify::Username() @@ -558,52 +789,114 @@ QDateTime Verify::GetDueTime() return m_dueTime; } +bool Verify::IsPermanent() +{ + return m_permanent; +} + +double Verify::Balance() +{ + return m_balance; +} + +QString Verify::BillingMode() +{ + return m_billingMode; +} + +QString Verify::DueTimeText() +{ + if (m_billingMode.isEmpty()) + { + return "未获取"; + } + if (m_billingMode == "permanent") + { + return "永久授权"; + } + if (m_billingMode == "balance") + { + return QString("剩余点数: %1").arg(m_balance, 0, 'g', 10); + } + if (m_billingMode == "free") + { + return "无到期限制"; + } + return m_dueTime.toString("yyyy-MM-dd HH:mm:ss"); +} + +bool Verify::ChangePassword(QString OldPassword, QString NewPassword, QString& result) +{ + VMProtectBegin("Verify_ChangePwd"); + + QJsonObject JsonObject; + JsonObject.insert("username", m_username); + JsonObject.insert("old_password", OldPassword); + JsonObject.insert("new_password", NewPassword); + + QJsonValue data; + bool ok = Request("/change-password", JsonObject, data, result, false); + if (ok) + { + m_password = NewPassword; + } + + VMProtectEnd(); + return ok; +} + +bool Verify::Devices(QJsonArray& list, QString& result) +{ + VMProtectBegin("Verify_Devices"); + + QJsonValue data; + if (!Request("/devices", QJsonObject(), data, result, true, "GET")) + { + VMProtectEnd(); + return false; + } + + list = data.toArray(); + + VMProtectEnd(); + return true; +} + +bool Verify::UnbindDevice(QString DeviceId, QString& result) +{ + VMProtectBegin("Verify_Unbind"); + + QJsonObject JsonObject; + JsonObject.insert("device_id", DeviceId); + + QJsonValue data; + bool ok = Request("/unbind-device", JsonObject, data, result, true); + + VMProtectEnd(); + return ok; +} + bool Verify::push_msg(QString type, QString app, QString account, QMap order) { VMProtectBegin("Verify_Push"); - QString result; + QJsonObject JsonObject; - JsonObject.insert("username", m_username); - JsonObject.insert("password", m_password); - JsonObject.insert("account", m_machineCode); JsonObject.insert("type", type); JsonObject.insert("app", app); JsonObject.insert("account", account); + JsonObject.insert("time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")); - // 修复:直接将 QMap 转换为 QJsonObject QJsonObject orderJson; for (auto it = order.begin(); it != order.end(); ++it) { orderJson.insert(it.key(), it.value()); } JsonObject.insert("order", orderJson); - QJsonDocument jsonDoc = QJsonDocument(JsonObject); - QString post_data = jsonDoc.toJson(QJsonDocument::Compact); - //qDebug() << "参数:" << post_data.toStdString().c_str(); - if (!Send("push", post_data, result, false)) - { - //qDebug() << "推送消息失败:" << result.toStdString().c_str(); - return false; - } - //qDebug() << "推送成功:" << result.toStdString().c_str(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) - { - //qDebug() << "String NULL";; - return false; - } - QJsonObject jsonObject = jsonDocument.object(); - QString version = jsonObject["version"].toVariant().toString(); - //qDebug() << "最新版本:" << version; - if (m_version == version) - { - //qDebug() << "验证结果: 真"; - } - else - { - //qDebug() << "验证结果: 假"; - } + // 后台没有专门的推送接口,写进云端变量记录:POST /variables/{key}/records + QString result; + QJsonValue data; + bool ok = Request("/variables/" VERIFY_PUSH_VARIABLE_KEY "/records", JsonObject, data, result, true); - return false; VMProtectEnd(); + return ok; } diff --git a/CrownClient/Verify.h b/CrownClient/Verify.h index 8579790..e038199 100644 --- a/CrownClient/Verify.h +++ b/CrownClient/Verify.h @@ -2,12 +2,29 @@ #include #include #include +#include #include +#include #include #include #include #include +#include +#include #include +#include + +// 服务端「应用 -> 加密方式」,改后台配置时这里要跟着改 +// 0 = 不加密 1 = RC4 2 = AES-256-GCM +#define VERIFY_ENCRYPT_TYPE 2 + +// 订单推送写进哪个云端变量。后台要先建一个 var_type=stream、 +// 写权限包含 app_user 的变量,key 填这里 +#define VERIFY_PUSH_VARIABLE_KEY "order_push" + +// 永久授权 / 点数计费拿不到真实到期日,用这个占位,保证主程序的到期判断永远不触发 +#define VERIFY_NO_EXPIRY_DATE QDate(2999, 12, 31) + class Verify :public QObject { Q_OBJECT @@ -26,17 +43,42 @@ private: private: QString ParamEncrypt(QString Param); QString ParamDecrypt(QString Param); - bool Send(QString Option, QString Data, QString& Result, bool async = false); + // AES-256-GCM,布局与后端 crypto.encryptAES 一致:nonce(12) || 密文 || tag(16) + QByteArray AesGcmEncrypt(const QByteArray& Plain, bool& Ok); + QByteArray AesGcmDecrypt(const QByteArray& Cipher, bool& Ok); + // 按后台配置的加密方式处理请求体 / 响应体,输入输出都是 base64 + QString EncryptBody(const QString& Plain, bool& Ok); + QString DecryptBody(const QString& Cipher, bool& Ok); + // 发一个 /api/v1/app/{appKey} 请求,成功时 Data 是业务 data(可能是对象也可能是数组) + bool Request(const QString& Path, const QJsonObject& Body, QJsonValue& Data, QString& Result, + bool WithToken = true, const QString& Method = "POST"); + // 登录和心跳返回同一套计费字段,统一解析 + void ParseBilling(const QJsonObject& Data); public: // 登录 bool Login(QString Username, QString Password, QString& result); // 心跳 bool Heartbeat(QString& result); - // 检查更新 + // 检查更新(主程序的更新已交给 Update.exe,这里只在需要时做补充判断) bool checkUpdate(); // 软件登录账号 QString Username(); + // 到期时间;永久授权和点数计费没有到期日,返回 2999-12-31 QDateTime GetDueTime(); + // 是否永久授权 + bool IsPermanent(); + // 剩余点数,非点数计费时无意义 + double Balance(); + // 计费模式:permanent / subscription / balance / free,未登录时为空 + QString BillingMode(); + // 界面上的到期文案,把三种计费模式合并成一句话 + QString DueTimeText(); + // 修改密码 + bool ChangePassword(QString OldPassword, QString NewPassword, QString& result); + // 已绑定的设备列表 + bool Devices(QJsonArray& list, QString& result); + // 解绑设备 + bool UnbindDevice(QString DeviceId, QString& result); public slots: // 推送消息 bool push_msg(QString type, QString app, QString account, QMap order); @@ -44,11 +86,11 @@ public slots: private: // 随机密码字符串 非十六进制 QString m_randomeKey; - // 应用密钥 + // 应用密钥(verify 后台的 AppKey) QString m_appId; - // 通信密钥 + // 通信密钥(verify 后台的 EncryptKey) QString m_commKey; - // 网络接口 + // 服务地址 QString m_webApi; // 机器码 QString m_machineCode; @@ -58,11 +100,18 @@ private: QString m_username; // 密码 QString m_password; - + // 登录拿到的 JWT,心跳和云端接口都要带 + QString m_token; + // 实例ID,同一台机器多开时区分进程 + QString m_instanceId; private: // 到期时间 QDateTime m_dueTime; - - -}; \ No newline at end of file + // 是否永久授权 + bool m_permanent; + // 剩余点数 + double m_balance; + // 计费模式 + QString m_billingMode; +}; diff --git a/CrownClient/main.cpp b/CrownClient/main.cpp index 7687438..2fba00d 100644 --- a/CrownClient/main.cpp +++ b/CrownClient/main.cpp @@ -4,16 +4,65 @@ #include "Login.h" #include #include +#include +#include #include "AppInstanceManager.h" #include "Utils.h" -#pragma comment(lib,"D:\\开发工具\\VMProtect\\Lib\\Windows\\VMProtectSDK64.lib") +#pragma comment(lib,"D:\\reverse\\vmprotect33\\Lib\\Windows\\VMProtectSDK64.lib") #include "StyleLoader.h" #include "MessageHandle.h" +namespace { +// 更新服务应用 AppKey,取自 verify 后台 -> 应用 -> AppKey +const char* kUpdaterAppKey = "abab3280114bfe824acfdbc6255538fb"; + +// Update.exe --check-only 的退出码 +const int kUpdaterNoUpdate = 0; // 已是最新版本 +const int kUpdaterHasUpdate = 1; // 有更新 +const int kUpdaterFailed = 2; // 检查失败(网络/解密/解析异常) +const int kUpdaterBadVersion = 3; // 服务端版本表里没有当前版本,只能整包重装 + +// 静默检查更新。返回 true 表示主程序可以继续往下走(进入登录), +// false 表示已经把更新交给 Update.exe,主程序应当退出 +bool CheckAndRunUpdater() +{ + const QString appDir = QCoreApplication::applicationDirPath(); + const QString updater = appDir + "/Update.exe"; + if (!QFileInfo::exists(updater)) { + return true; // 没有更新器就保持原有行为 + } + + const QString exeName = QFileInfo(QCoreApplication::applicationFilePath()).fileName(); + const int code = QProcess::execute(updater, QStringList() + << "--check-only" + << "--app-key" << kUpdaterAppKey + << "--version" << VERSION); + + if (code == kUpdaterNoUpdate || code == kUpdaterFailed) { + // 已经是最新,或者服务器/网络有问题——后者放行,避免把用户挡在门外 + return true; + } + + QStringList args; + if (code == kUpdaterBadVersion) { + // 服务端不认识当前版本,补丁包无从生成,直接整包覆盖安装到程序所在目录 + args << "--app-key" << kUpdaterAppKey << "--dir" << appDir; + } else { + // 常规补丁包更新 + args << "--app-key" << kUpdaterAppKey << "--version" << VERSION + << "--dir" << appDir; + } + args << "--launch" << exeName; + + QProcess::startDetached(updater, args, appDir); + return false; +} + +} int main(int argc, char *argv[]) @@ -76,23 +125,19 @@ int main(int argc, char *argv[]) // 初始化配置类 g_config = new Config(); - // 初始化验证类 - g_verify = new Verify("https://gendan.xyz", "72", "NAO87ZGQXTXR1HLFHGL3NSLXD", VERSION); + // 初始化验证类(AppKey 和 EncryptKey 都取自 verify 后台的应用配置) + g_verify = new Verify("https://gendan.xyz", "abab3280114bfe824acfdbc6255538fb", + "07dab7c3c772a8a8f2dad3f45e2e397806d92f560ac954532ee7562a03c1df14", VERSION); - // 检测更新 - if (g_verify->checkUpdate()) + // 检测更新(由 Update.exe 走 verify 新版接口静默检查) + if (CheckAndRunUpdater()) { Login w; w.show(); return app.exec(); } - else - { - QProcess::execute(QCoreApplication::applicationDirPath() + "/Update.exe"); - QApplication::quit(); - } return 0; } diff --git a/CrownServer/CrownServer.cpp b/CrownServer/CrownServer.cpp index 0591566..8784408 100644 --- a/CrownServer/CrownServer.cpp +++ b/CrownServer/CrownServer.cpp @@ -154,7 +154,7 @@ CrownServer::CrownServer(QWidget* parent) ui.endtimeLabel->setText( QString("

软件登录账号: %1 软件到期时间: %2

") .arg(g_verify->Username()) - .arg(g_verify->GetDueTime().toString("yyyy-MM-dd hh:mm:ss")) + .arg(g_verify->DueTimeText()) ); ///////////////////////////////////////////////////// @@ -1984,8 +1984,9 @@ void CrownServer::heartbeat() qDebug() << "心跳失败:" << result; } - // 检查授权到期时间 - if (g_verify->GetDueTime().msecsTo(QDateTime::currentDateTime()) >= 0) { + // 检查授权到期时间;永久授权和点数计费没有到期日,GetDueTime 是占位日期,不会走到这里 + QDateTime dueTime = g_verify->GetDueTime(); + if (dueTime.isValid() && dueTime.msecsTo(QDateTime::currentDateTime()) >= 0) { QMessageBox::critical(nullptr, "错误", "授权已到期!"); QApplication::quit(); } diff --git a/CrownServer/Verify.cpp b/CrownServer/Verify.cpp index dc5ab78..cc55597 100644 --- a/CrownServer/Verify.cpp +++ b/CrownServer/Verify.cpp @@ -1,30 +1,44 @@ #include "Verify.h" #include "Global.h" + +#pragma comment(lib, "bcrypt.lib") + +#include +#include +#include +#include +#include + +// 一次网络请求最多等多久,超时就放弃,别把心跳线程卡死 +#define VERIFY_REQUEST_TIMEOUT 15000 + /// /// 构造函数 /// -/// -/// -/// -/// +/// verify 站点地址,如 https://gendan.xyz +/// 后台「应用 -> AppKey」 +/// 后台「应用 -> EncryptKey」 +/// 客户端版本 Verify::Verify(QString Url, QString AppId, QString CommKey, QString Verison) { VMProtectBegin("Verify_Init"); - // 初始化网络权限管理类 - // 获取随机Key this->m_randomeKey = this->GetRandom(32); - + m_appId = this->ParamEncrypt(AppId); m_commKey = this->ParamEncrypt(CommKey); - m_webApi = this->ParamEncrypt(Url + "/api_new.php?"); + m_webApi = this->ParamEncrypt(Url); m_machineCode = this->GetCPUID(); m_version = Verison; + // 同一台机器多开时用实例ID区分,服务端拿它做会话粒度 + m_instanceId = QUuid::createUuid().toString(QUuid::WithoutBraces); + + m_permanent = false; + m_balance = 0; //qDebug() << "验证网址:" << Url; - //qDebug() << "软件ID:" << AppId; - //qDebug() << "通信密钥:" << CommKey; + //qDebug() << "应用AppKey:" << AppId; //qDebug() << "软件版本:" << Verison; //qDebug() << "机器码:" << this->GetCPUID(); VMProtectEnd(); @@ -158,7 +172,7 @@ QByteArray Verify::RC4(QByteArray Data, QString Key) m[j] = temp; result[x] = Data[x] ^ m[(m[i] + m[j]) & 255]; } - // qDebug() << "RC4:" << result.toHex(); + //qDebug() << "RC4:" << result.toHex(); return result; } @@ -241,7 +255,7 @@ QString Verify::ParamEncrypt(QString Param) return paramByteArray.toHex(); VMProtectEnd(); - + } QString Verify::ParamDecrypt(QString Param) @@ -329,219 +343,440 @@ QString Verify::ParamDecrypt(QString Param) VMProtectEnd(); } - -QString ByteArrayToHexString(QByteArray data) { - QString ret(data.toHex().toUpper()); - int len = ret.length() / 2; - for (int i = 1; i < len; i++) +// 后端 crypto.padKey 的等价实现:不足 32 字节循环补齐,超过 32 字节直接截断 +static QByteArray PadAesKey(const QByteArray& Secret) +{ + QByteArray key(32, '\0'); + if (Secret.isEmpty()) { - ret.insert(2 * i + i - 1, " "); + return key; } - - return ret; + // 后端只有 16/24/32 三种长度会原样使用,这里统一补到 32,跟它 padKey(32) 的结果一致 + if (Secret.size() != 16 && Secret.size() != 24 && Secret.size() != 32) + { + for (int i = 0; i < key.size(); ++i) + { + key[i] = Secret[i % Secret.size()]; + } + return key; + } + return Secret; } -// 发送网络请求 -bool Verify::Send(QString Option, QString Data, QString& Result, bool async) +// 打开一个 GCM 模式的 AES 算法句柄 +static BCRYPT_ALG_HANDLE OpenAesGcm() +{ + BCRYPT_ALG_HANDLE alg = nullptr; + if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0))) + { + return nullptr; + } + ULONG modeLength = (ULONG)((wcslen(BCRYPT_CHAIN_MODE_GCM) + 1) * sizeof(wchar_t)); + if (!BCRYPT_SUCCESS(BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, + (PUCHAR)BCRYPT_CHAIN_MODE_GCM, modeLength, 0))) + { + BCryptCloseAlgorithmProvider(alg, 0); + return nullptr; + } + return alg; +} + +// AES-256-GCM,输出 nonce(12) || 密文 || tag(16) +QByteArray Verify::AesGcmEncrypt(const QByteArray& Plain, bool& Ok) +{ + VMProtectBegin("Verify_AesEnc"); + Ok = false; + + QByteArray key = PadAesKey(ParamDecrypt(m_commKey).toUtf8()); + BCRYPT_ALG_HANDLE alg = OpenAesGcm(); + if (alg == nullptr) + { + VMProtectEnd(); + return QByteArray(); + } + + BCRYPT_KEY_HANDLE keyHandle = nullptr; + if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(alg, &keyHandle, nullptr, 0, + (PUCHAR)key.data(), (ULONG)key.size(), 0))) + { + BCryptCloseAlgorithmProvider(alg, 0); + VMProtectEnd(); + return QByteArray(); + } + + const int nonceSize = 12; + const int tagSize = 16; + QByteArray nonce(nonceSize, '\0'); + BCryptGenRandom(nullptr, (PUCHAR)nonce.data(), (ULONG)nonce.size(), BCRYPT_USE_SYSTEM_PREFERRED_RNG); + + QByteArray cipher(Plain.size(), '\0'); + QByteArray tag(tagSize, '\0'); + + BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; + BCRYPT_INIT_AUTH_MODE_INFO(info); + info.pbNonce = (PUCHAR)nonce.data(); + info.cbNonce = (ULONG)nonce.size(); + info.pbTag = (PUCHAR)tag.data(); + info.cbTag = (ULONG)tag.size(); + + ULONG written = 0; + NTSTATUS status = BCryptEncrypt(keyHandle, + (PUCHAR)Plain.data(), (ULONG)Plain.size(), + &info, nullptr, 0, + (PUCHAR)cipher.data(), (ULONG)cipher.size(), &written, 0); + + BCryptDestroyKey(keyHandle); + BCryptCloseAlgorithmProvider(alg, 0); + + if (!BCRYPT_SUCCESS(status) || (int)written != Plain.size()) + { + VMProtectEnd(); + return QByteArray(); + } + + Ok = true; + VMProtectEnd(); + return nonce + cipher + tag; +} + +// AES-256-GCM,输入 nonce(12) || 密文 || tag(16),tag 校验不过直接失败 +QByteArray Verify::AesGcmDecrypt(const QByteArray& Cipher, bool& Ok) +{ + VMProtectBegin("Verify_AesDec"); + Ok = false; + + const int nonceSize = 12; + const int tagSize = 16; + if (Cipher.size() < nonceSize + tagSize) + { + VMProtectEnd(); + return QByteArray(); + } + + QByteArray key = PadAesKey(ParamDecrypt(m_commKey).toUtf8()); + BCRYPT_ALG_HANDLE alg = OpenAesGcm(); + if (alg == nullptr) + { + VMProtectEnd(); + return QByteArray(); + } + + BCRYPT_KEY_HANDLE keyHandle = nullptr; + if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(alg, &keyHandle, nullptr, 0, + (PUCHAR)key.data(), (ULONG)key.size(), 0))) + { + BCryptCloseAlgorithmProvider(alg, 0); + VMProtectEnd(); + return QByteArray(); + } + + QByteArray nonce = Cipher.left(nonceSize); + QByteArray tag = Cipher.right(tagSize); + QByteArray body = Cipher.mid(nonceSize, Cipher.size() - nonceSize - tagSize); + + BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; + BCRYPT_INIT_AUTH_MODE_INFO(info); + info.pbNonce = (PUCHAR)nonce.data(); + info.cbNonce = (ULONG)nonce.size(); + info.pbTag = (PUCHAR)tag.data(); + info.cbTag = (ULONG)tag.size(); + + QByteArray plain(body.size(), '\0'); + ULONG written = 0; + NTSTATUS status = BCryptDecrypt(keyHandle, + (PUCHAR)body.data(), (ULONG)body.size(), + &info, nullptr, 0, + (PUCHAR)plain.data(), (ULONG)plain.size(), &written, 0); + + BCryptDestroyKey(keyHandle); + BCryptCloseAlgorithmProvider(alg, 0); + + if (!BCRYPT_SUCCESS(status)) + { + VMProtectEnd(); + return QByteArray(); + } + + Ok = true; + VMProtectEnd(); + return plain; +} + +QString Verify::EncryptBody(const QString& Plain, bool& Ok) +{ + Ok = true; +#if VERIFY_ENCRYPT_TYPE == 2 + QByteArray cipher = AesGcmEncrypt(Plain.toUtf8(), Ok); + return Ok ? QString::fromLatin1(cipher.toBase64()) : QString(); +#elif VERIFY_ENCRYPT_TYPE == 1 + return QString::fromLatin1(RC4(Plain.toUtf8(), ParamDecrypt(m_commKey)).toBase64()); +#else + return Plain; +#endif +} + +QString Verify::DecryptBody(const QString& Cipher, bool& Ok) +{ + Ok = true; +#if VERIFY_ENCRYPT_TYPE == 2 + QByteArray plain = AesGcmDecrypt(QByteArray::fromBase64(Cipher.toLatin1()), Ok); + return Ok ? QString::fromUtf8(plain) : QString(); +#elif VERIFY_ENCRYPT_TYPE == 1 + return QString::fromUtf8(RC4(QByteArray::fromBase64(Cipher.toLatin1()), ParamDecrypt(m_commKey))); +#else + return Cipher; +#endif +} + +// 发一个 /api/v1/app/{appKey} 请求 +// 请求体加密后放进 {"data": "..."},响应是 {"data": "..."},解密出来才是 {code,message,data} +bool Verify::Request(const QString& Path, const QJsonObject& Body, QJsonValue& Data, + QString& Result, bool WithToken, const QString& Method) { VMProtectBegin("Verify_Send"); - QNetworkAccessManager networkAccessManager; - // 获取当前时间戳 - QDateTime timeDate = QDateTime::currentDateTime(); - QString timestamp = QString::number(timeDate.toSecsSinceEpoch()); - //qDebug() << "解密:" << ParamDecrypt(m_commKey); - // 获取签名 - - // 转为十六进制文本 - QString PostData; - PostData.append(RC4(Data.toUtf8(), ParamDecrypt(m_commKey)).toHex()); - - //qDebug() << "RC4的结果:" << PostData; - QByteArray PostByte = PostData.toUtf8(); - //qDebug() << "RC4结果:" << PostByte.toHex(); - QByteArray SignData = PostByte + timestamp.toUtf8() + ParamDecrypt(m_commKey).toUtf8(); - // 转换为十六进制字符串 - - QString md5 = this->Md5(SignData); - // a98d0872e603bc63f04767a14617df64 - //qDebug() << "md5:" << md5; - QUrl strUrl = ParamDecrypt(m_webApi) + "&mod=" + Option + "&appId=" + this->ParamDecrypt(m_appId) + "&sign=" + md5 + "×tamp=" + timestamp; - //qDebug() << "访问地址:" << strUrl; - // 网络请求 - QNetworkRequest request; - // 设置请求地址 - request.setUrl(strUrl); - // 设置请求头 - // request.setRawHeader("Content-Type", "charset='utf-8'"); - request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");// "charset='utf-8'" - //request.setRawHeader("Content-Type", "application/json"); - // 网络应答 - - QNetworkReply* reply = networkAccessManager.post(request, PostData.toUtf8()); - QByteArray responseData; - // 事件循环 - if (async) + if (WithToken && m_token.isEmpty()) { - + Result = "未登录"; + VMProtectEnd(); + return false; } + + bool ok = false; + QString encrypted = EncryptBody(QString::fromUtf8(QJsonDocument(Body).toJson(QJsonDocument::Compact)), ok); + if (!ok) + { + Result = "请求加密失败"; + VMProtectEnd(); + return false; + } + + QJsonObject envelope; + envelope.insert("data", encrypted); + + QNetworkAccessManager networkAccessManager; + QNetworkRequest request; + request.setUrl(QUrl(ParamDecrypt(m_webApi) + "/api/v1/app/" + ParamDecrypt(m_appId) + Path)); + // 服务端只在 Content-Type 非空时才解密请求体,这个头不能省 + request.setRawHeader("Content-Type", "application/json"); + if (WithToken) + { + request.setRawHeader("Authorization", ("Bearer " + m_token).toUtf8()); + } + + QNetworkReply* reply = (Method == "GET") + ? networkAccessManager.get(request) + : networkAccessManager.post(request, QJsonDocument(envelope).toJson(QJsonDocument::Compact)); + + QTimer timer; + timer.setSingleShot(true); QEventLoop eventLoop; - // 连接信号和槽 + connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit())); connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); - // 开始循环 + timer.start(VERIFY_REQUEST_TIMEOUT); eventLoop.exec(); - //错误处理 + if (!reply->isFinished()) + { + reply->abort(); + reply->deleteLater(); + Result = "请求超时"; + VMProtectEnd(); + return false; + } + if (reply->error() != QNetworkReply::NoError) { - qDebug() << "Request protobufHttp handle errors here"; - QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); - // statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档 - qDebug("request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error()); - qDebug(qPrintable(reply->errorString())); + Result = "网络错误: " + reply->errorString(); reply->deleteLater(); - return ""; + VMProtectEnd(); + return false; } - //RC4(QByteArray::fromHex(数据.toUtf8()), ParamDecrypt(m_commKey)); - //QString strReply = reply->readAll(); - QString result = reply->readAll();//RC4(QByteArray::fromHex(reply->readAll()),ParamDecrypt(m_commKey)); - //qDebug() << "访问结果:" << result.toStdString().c_str(); + QByteArray responseData = reply->readAll(); reply->deleteLater(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) + QJsonDocument wrapped = QJsonDocument::fromJson(responseData); + if (!wrapped.isObject()) { - //qDebug() << "String NULL";; + Result = "服务器返回格式错误"; + VMProtectEnd(); + return false; } - QJsonObject jsonObject = jsonDocument.object(); - QString jsonCode = jsonObject["code"].toVariant().toString();//QString::number(jsonObject["code"].toInt()); - QString jsonMsg = jsonObject["msg"].toVariant().toString(); - QString jsonData = jsonObject["data"].toVariant().toString(); - QString jsonSign = jsonObject["sign"].toVariant().toString(); - QString jsonTampstamp = jsonObject["timestamp"].toVariant().toString(); - Result = RC4(QByteArray::fromHex(jsonData.toUtf8()), ParamDecrypt(m_commKey)); - if (!jsonSign.isEmpty()) + // 应用不存在 / 应用被禁用这类错误在加密中间件之前就返回了,没有 data 信封,是明文 + QJsonValue payload = wrapped.object().value("data"); + QString plain; + if (payload.isString()) { - QString verifySign = this->Md5(jsonCode.toUtf8() + jsonMsg.toUtf8() + jsonData.toUtf8()); - if (verifySign != jsonSign) + plain = DecryptBody(payload.toString(), ok); + if (!ok) { - Result = "数据校验失败"; + Result = "响应解密失败"; + VMProtectEnd(); return false; } } - - if (jsonCode == "1") + else { - return true; + plain = QString::fromUtf8(responseData); } - Result = jsonMsg; - return false; + + QJsonDocument response = QJsonDocument::fromJson(plain.toUtf8()); + if (!response.isObject()) + { + Result = "响应解密失败"; + VMProtectEnd(); + return false; + } + + QJsonObject jsonObject = response.object(); + int code = jsonObject.value("code").toVariant().toInt(); + Result = jsonObject.value("message").toVariant().toString(); + if (code != 200) + { + if (Result.isEmpty()) + { + Result = QString("请求失败(%1)").arg(code); + } + VMProtectEnd(); + return false; + } + + Data = jsonObject.value("data"); VMProtectEnd(); + return true; } +// 登录和心跳返回同一套计费字段: +// Balance == -1 -> is_permanent +// billing_type 订阅 -> expiry_at + expiry_timestamp +// 其他非免费计费 -> balance +void Verify::ParseBilling(const QJsonObject& Data) +{ + m_permanent = false; + m_balance = 0; + + if (Data.value("is_permanent").toVariant().toBool()) + { + m_billingMode = "permanent"; + m_permanent = true; + m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59)); + return; + } + + if (Data.contains("expiry_at") || Data.contains("expiry_timestamp")) + { + m_billingMode = "subscription"; + // 必须用 expiry_timestamp。服务器按 UTC 格式化 expiry_at,直接拿这个字符串当本地时间 + // 解析会早 8 个小时,用户会被提前踢下线。expiry_at 只在拿不到时间戳时才兜底 + qint64 stamp = Data.value("expiry_timestamp").toVariant().toLongLong(); + if (stamp > 0) + { + m_dueTime = QDateTime::fromSecsSinceEpoch(stamp); + } + else + { + m_dueTime = QDateTime::fromString(Data.value("expiry_at").toVariant().toString(), "yyyy-MM-dd HH:mm:ss"); + } + return; + } + + if (Data.contains("balance")) + { + m_billingMode = "balance"; + m_balance = Data.value("balance").toVariant().toDouble(); + m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59)); + return; + } + + // 免费应用没有计费字段,同样不存在到期一说 + m_billingMode = "free"; + m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59)); +} bool Verify::Login(QString Username, QString Password, QString& result) { VMProtectBegin("Verify_Login"); + QJsonObject JsonObject; JsonObject.insert("username", Username); JsonObject.insert("password", Password); - JsonObject.insert("hardwareCode", m_machineCode); - QJsonDocument jsonDoc = QJsonDocument(JsonObject); - QString post_data = jsonDoc.toJson(QJsonDocument::Compact); - //qDebug() << "参数:" << post_data.toStdString().c_str(); - if (!Send("login", post_data, result)) + // 后台把 device_id 当必填项,用机器码顶上,和旧协议的 hardwareCode 一个作用 + JsonObject.insert("device_id", m_machineCode); + JsonObject.insert("device_name", QSysInfo::machineHostName()); + JsonObject.insert("device_type", "windows"); + JsonObject.insert("instance_id", m_instanceId); + + QJsonValue data; + if (!Request("/login", JsonObject, data, result, false)) { - //qDebug() << "登录失败:" << result.toStdString().c_str(); - //result = "登录失败"; + VMProtectEnd(); return false; } - //qDebug() << "登录成功:" << result.toStdString().c_str(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) + + QJsonObject object = data.toObject(); + m_token = object.value("token").toVariant().toString(); + if (m_token.isEmpty()) { - //qDebug() << "String NULL";; - result = "登录失败"; + result = "登录失败:服务端没有返回令牌"; + VMProtectEnd(); return false; } - QJsonObject jsonObject = jsonDocument.object(); - QString jsonTime = jsonObject["expireTime"].toVariant().toString(); - m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss"); + m_username = Username; m_password = Password; - return true; + ParseBilling(object); + VMProtectEnd(); + return true; } bool Verify::Heartbeat(QString& result) { VMProtectBegin("Verify_Heartbeat"); - QJsonObject JsonObject; - JsonObject.insert("username", m_username); - JsonObject.insert("password", m_password); - JsonObject.insert("hardwareCode", m_machineCode); - QJsonDocument jsonDoc = QJsonDocument(JsonObject); - QString post_data = jsonDoc.toJson(QJsonDocument::Compact); - //qDebug() << "参数:" << post_data.toStdString().c_str(); - if (!Send("heartbeat", post_data, result)) - { - //qDebug() << "心跳失败:" << result.toStdString().c_str(); - return false; - } - //qDebug() << "登录成功:" << result.toStdString().c_str(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) - { - //qDebug() << "String NULL";; - return false; - } - QJsonObject jsonObject = jsonDocument.object(); - QString jsonTime = jsonObject["expireTime"].toVariant().toString(); - m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss"); - return true; + QJsonObject JsonObject; + // 心跳的身份信息全在 JWT 里,请求体只需要实例ID + JsonObject.insert("instance_id", m_instanceId); + + QJsonValue data; + if (!Request("/heartbeat", JsonObject, data, result, true)) + { + VMProtectEnd(); + return false; + } + + ParseBilling(data.toObject()); + VMProtectEnd(); + return true; } bool Verify::checkUpdate() { VMProtectBegin("Verify_Check"); + QString result; - QJsonObject JsonObject; - JsonObject.insert("username", m_username); - JsonObject.insert("password", m_password); - JsonObject.insert("hardwareCode", m_machineCode); - QJsonDocument jsonDoc = QJsonDocument(JsonObject); - QString post_data = jsonDoc.toJson(QJsonDocument::Compact); - //qDebug() << "参数:" << post_data.toStdString().c_str(); - if (!Send("version", post_data, result)) + QJsonValue data; + if (!Request("/check-update?version=" + QUrl::toPercentEncoding(m_version), + QJsonObject(), data, result, false, "GET")) { - //qDebug() << "获取版本失败:" << result.toStdString().c_str(); - return false; + // 拿不到更新信息就当是最新,别拦着主程序启动 + VMProtectEnd(); + return true; } - //qDebug() << "获取版本成功:" << result.toStdString().c_str(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) + + QJsonObject object = data.toObject(); + QString latest = object.value("latest_version").toVariant().toString(); + if (!latest.isEmpty()) { - //qDebug() << "String NULL";; - return false; + VMProtectEnd(); + return latest == m_version; } - QJsonObject jsonObject = jsonDocument.object(); - QString version = jsonObject["version"].toVariant().toString(); - //qDebug() << "最新版本:" << version; - if (m_version == version) - { - //qDebug() << "验证结果: 真"; - } - else - { - //qDebug() << "验证结果: 假"; - } - - return version == m_version; + VMProtectEnd(); + return !object.value("has_update").toVariant().toBool(); } QString Verify::Username() @@ -554,61 +789,114 @@ QDateTime Verify::GetDueTime() return m_dueTime; } -bool Verify::push_msg(QString type,QString app,QString account,QMap order) +bool Verify::IsPermanent() { - VMProtectBegin("Verify_Push"); - QString result; + return m_permanent; +} + +double Verify::Balance() +{ + return m_balance; +} + +QString Verify::BillingMode() +{ + return m_billingMode; +} + +QString Verify::DueTimeText() +{ + if (m_billingMode.isEmpty()) + { + return "未获取"; + } + if (m_billingMode == "permanent") + { + return "永久授权"; + } + if (m_billingMode == "balance") + { + return QString("剩余点数: %1").arg(m_balance, 0, 'g', 10); + } + if (m_billingMode == "free") + { + return "无到期限制"; + } + return m_dueTime.toString("yyyy-MM-dd HH:mm:ss"); +} + +bool Verify::ChangePassword(QString OldPassword, QString NewPassword, QString& result) +{ + VMProtectBegin("Verify_ChangePwd"); + QJsonObject JsonObject; JsonObject.insert("username", m_username); - JsonObject.insert("password", m_password); - JsonObject.insert("account", m_machineCode); + JsonObject.insert("old_password", OldPassword); + JsonObject.insert("new_password", NewPassword); + + QJsonValue data; + bool ok = Request("/change-password", JsonObject, data, result, false); + if (ok) + { + m_password = NewPassword; + } + + VMProtectEnd(); + return ok; +} + +bool Verify::Devices(QJsonArray& list, QString& result) +{ + VMProtectBegin("Verify_Devices"); + + QJsonValue data; + if (!Request("/devices", QJsonObject(), data, result, true, "GET")) + { + VMProtectEnd(); + return false; + } + + list = data.toArray(); + + VMProtectEnd(); + return true; +} + +bool Verify::UnbindDevice(QString DeviceId, QString& result) +{ + VMProtectBegin("Verify_Unbind"); + + QJsonObject JsonObject; + JsonObject.insert("device_id", DeviceId); + + QJsonValue data; + bool ok = Request("/unbind-device", JsonObject, data, result, true); + + VMProtectEnd(); + return ok; +} + +bool Verify::push_msg(QString type, QString app, QString account, QMap order) +{ + VMProtectBegin("Verify_Push"); + + QJsonObject JsonObject; JsonObject.insert("type", type); JsonObject.insert("app", app); JsonObject.insert("account", account); + JsonObject.insert("time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")); - // 修复:直接将 QMap 转换为 QJsonObject QJsonObject orderJson; for (auto it = order.begin(); it != order.end(); ++it) { - if (it.key() == "TEAM_H") - { - //qDebug() << "队伍H:" << it.value(); - } - if (it.key() == "TEAM_C") - { - //qDebug() << "队伍C:" << it.value(); - } orderJson.insert(it.key(), it.value()); } - //qDebug() << orderJson; JsonObject.insert("order", orderJson); - QJsonDocument jsonDoc = QJsonDocument(JsonObject); - QString post_data = jsonDoc.toJson(QJsonDocument::Compact); - //qDebug() << "参数:" << post_data.toStdString().c_str(); - if (!Send("push", post_data, result)) - { - //qDebug() << "推送消息失败:" << result.toStdString().c_str(); - return false; - } - //qDebug() << "推送成功:" << result.toStdString().c_str(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data()); - if (jsonDocument.isNull()) - { - //qDebug() << "String NULL";; - return false; - } - QJsonObject jsonObject = jsonDocument.object(); - QString version = jsonObject["version"].toVariant().toString(); - //qDebug() << "最新版本:" << version; - if (m_version == version) - { - //qDebug() << "验证结果: 真"; - } - else - { - //qDebug() << "验证结果: 假"; - } + // 后台没有专门的推送接口,写进云端变量记录:POST /variables/{key}/records + QString result; + QJsonValue data; + bool ok = Request("/variables/" VERIFY_PUSH_VARIABLE_KEY "/records", JsonObject, data, result, true); - return false; VMProtectEnd(); + return ok; } diff --git a/CrownServer/Verify.h b/CrownServer/Verify.h index f5d9c05..e038199 100644 --- a/CrownServer/Verify.h +++ b/CrownServer/Verify.h @@ -2,16 +2,33 @@ #include #include #include +#include #include +#include #include #include #include #include +#include +#include #include +#include + +// 服务端「应用 -> 加密方式」,改后台配置时这里要跟着改 +// 0 = 不加密 1 = RC4 2 = AES-256-GCM +#define VERIFY_ENCRYPT_TYPE 2 + +// 订单推送写进哪个云端变量。后台要先建一个 var_type=stream、 +// 写权限包含 app_user 的变量,key 填这里 +#define VERIFY_PUSH_VARIABLE_KEY "order_push" + +// 永久授权 / 点数计费拿不到真实到期日,用这个占位,保证主程序的到期判断永远不触发 +#define VERIFY_NO_EXPIRY_DATE QDate(2999, 12, 31) + class Verify :public QObject { Q_OBJECT - + public: Verify(QString Url, QString AppKey, QString CommKey, QString Verison); ~Verify(); @@ -26,29 +43,54 @@ private: private: QString ParamEncrypt(QString Param); QString ParamDecrypt(QString Param); - bool Send(QString Option, QString Data, QString& Result, bool async = false); + // AES-256-GCM,布局与后端 crypto.encryptAES 一致:nonce(12) || 密文 || tag(16) + QByteArray AesGcmEncrypt(const QByteArray& Plain, bool& Ok); + QByteArray AesGcmDecrypt(const QByteArray& Cipher, bool& Ok); + // 按后台配置的加密方式处理请求体 / 响应体,输入输出都是 base64 + QString EncryptBody(const QString& Plain, bool& Ok); + QString DecryptBody(const QString& Cipher, bool& Ok); + // 发一个 /api/v1/app/{appKey} 请求,成功时 Data 是业务 data(可能是对象也可能是数组) + bool Request(const QString& Path, const QJsonObject& Body, QJsonValue& Data, QString& Result, + bool WithToken = true, const QString& Method = "POST"); + // 登录和心跳返回同一套计费字段,统一解析 + void ParseBilling(const QJsonObject& Data); public: // 登录 bool Login(QString Username, QString Password, QString& result); // 心跳 bool Heartbeat(QString& result); - // 检查更新 + // 检查更新(主程序的更新已交给 Update.exe,这里只在需要时做补充判断) bool checkUpdate(); // 软件登录账号 QString Username(); + // 到期时间;永久授权和点数计费没有到期日,返回 2999-12-31 QDateTime GetDueTime(); + // 是否永久授权 + bool IsPermanent(); + // 剩余点数,非点数计费时无意义 + double Balance(); + // 计费模式:permanent / subscription / balance / free,未登录时为空 + QString BillingMode(); + // 界面上的到期文案,把三种计费模式合并成一句话 + QString DueTimeText(); + // 修改密码 + bool ChangePassword(QString OldPassword, QString NewPassword, QString& result); + // 已绑定的设备列表 + bool Devices(QJsonArray& list, QString& result); + // 解绑设备 + bool UnbindDevice(QString DeviceId, QString& result); public slots: // 推送消息 - bool push_msg(QString type,QString app, QString account, QMap order); + bool push_msg(QString type, QString app, QString account, QMap order); private: // 随机密码字符串 非十六进制 QString m_randomeKey; - // 应用密钥 + // 应用密钥(verify 后台的 AppKey) QString m_appId; - // 通信密钥 + // 通信密钥(verify 后台的 EncryptKey) QString m_commKey; - // 网络接口 + // 服务地址 QString m_webApi; // 机器码 QString m_machineCode; @@ -58,13 +100,18 @@ private: QString m_username; // 密码 QString m_password; - + // 登录拿到的 JWT,心跳和云端接口都要带 + QString m_token; + // 实例ID,同一台机器多开时区分进程 + QString m_instanceId; private: // 到期时间 QDateTime m_dueTime; - -private: - - -}; \ No newline at end of file + // 是否永久授权 + bool m_permanent; + // 剩余点数 + double m_balance; + // 计费模式 + QString m_billingMode; +}; diff --git a/CrownServer/main.cpp b/CrownServer/main.cpp index a04f476..5e7cbd4 100644 --- a/CrownServer/main.cpp +++ b/CrownServer/main.cpp @@ -7,6 +7,7 @@ #include "Login.h" #include "Global.h" #include +#include #include #include @@ -18,6 +19,56 @@ #include "Utils.h" #include "StyleLoader.h" #include "MessageHandle.h" + +namespace { + +// 更新服务应用 AppKey,取自 verify 后台 -> 应用 -> AppKey +const char* kUpdaterAppKey = "abab3280114bfe824acfdbc6255538fb"; + +// Update.exe --check-only 的退出码 +const int kUpdaterNoUpdate = 0; // 已是最新版本 +const int kUpdaterHasUpdate = 1; // 有更新 +const int kUpdaterFailed = 2; // 检查失败(网络/解密/解析异常) +const int kUpdaterBadVersion = 3; // 服务端版本表里没有当前版本,只能整包重装 + +// 静默检查更新。返回 true 表示主程序可以继续往下走(进入登录), +// false 表示已经把更新交给 Update.exe,主程序应当退出 +bool CheckAndRunUpdater() +{ + const QString appDir = QCoreApplication::applicationDirPath(); + const QString updater = appDir + "/Update.exe"; + if (!QFileInfo::exists(updater)) { + return true; // 没有更新器就保持原有行为 + } + + const QString exeName = QFileInfo(QCoreApplication::applicationFilePath()).fileName(); + const int code = QProcess::execute(updater, QStringList() + << "--check-only" + << "--app-key" << kUpdaterAppKey + << "--version" << VERSION); + + if (code == kUpdaterNoUpdate || code == kUpdaterFailed) { + // 已经是最新,或者服务器/网络有问题——后者放行,避免把用户挡在门外 + return true; + } + + QStringList args; + if (code == kUpdaterBadVersion) { + // 服务端不认识当前版本,补丁包无从生成,直接整包覆盖安装到程序所在目录 + args << "--app-key" << kUpdaterAppKey << "--dir" << appDir; + } else { + // 常规补丁包更新 + args << "--app-key" << kUpdaterAppKey << "--version" << VERSION + << "--dir" << appDir; + } + args << "--launch" << exeName; + + QProcess::startDetached(updater, args, appDir); + return false; +} + +} + int main(int argc, char* argv[]) { // 禁用GPU加速(如果黑屏) @@ -68,23 +119,19 @@ int main(int argc, char* argv[]) // 初始化配置 g_config = new Config(); - // 初始化验证 - g_verify = new Verify("https://gendan.xyz", "72", "NAO87ZGQXTXR1HLFHGL3NSLXD", VERSION); + // 初始化验证(AppKey 和 EncryptKey 都取自 verify 后台的应用配置) + g_verify = new Verify("https://gendan.xyz", "abab3280114bfe824acfdbc6255538fb", + "07dab7c3c772a8a8f2dad3f45e2e397806d92f560ac954532ee7562a03c1df14", VERSION); - // 检测版本更新 - if (g_verify->checkUpdate()) + // 检测版本更新(由 Update.exe 走 verify 新版接口静默检查) + if (CheckAndRunUpdater()) { Login w; w.show(); return a.exec(); } - else - { - QProcess::execute(QCoreApplication::applicationDirPath() + "/Update.exe"); - QApplication::quit(); - } - + return 0; } diff --git a/Update/Api.cpp b/Update/Api.cpp new file mode 100644 index 0000000..9ee8cc3 --- /dev/null +++ b/Update/Api.cpp @@ -0,0 +1,171 @@ +#include "Api.h" + +#include "Config.h" +#include "Crypto.h" +#include "Http.h" +#include "Json.h" +#include "Utils.h" + +namespace updater { + +namespace { + +void ParseStringList(const Json& value, std::vector& out) { + out.clear(); + if (value.isArray()) { + for (size_t i = 0; i < value.arraySize(); ++i) { + std::wstring item = Utils::Utf8ToWide(value[static_cast(i)].stringValue()); + item = Utils::Trim(item); + if (!item.empty()) out.push_back(item); + } + return; + } + if (value.isString()) { + // 后台把 JSON 数组存成了 text 字段,这里再解析一次 + std::string raw = value.stringValue(); + Json parsed; + std::string err; + if (!raw.empty() && Json::Parse(raw, parsed, err) && parsed.isArray()) { + ParseStringList(parsed, out); + return; + } + std::wstring item = Utils::Trim(Utils::Utf8ToWide(raw)); + if (!item.empty()) out.push_back(item); + } +} + +std::wstring ReadString(const Json& obj, const char* key) { + if (!obj.isObject()) return std::wstring(); + return Utils::Utf8ToWide(obj[key].stringValue()); +} + +unsigned long long ReadUInt64(const Json& obj, const char* key) { + if (!obj.isObject()) return 0; + return static_cast(obj[key].intValue(0)); +} + +} + +std::wstring Api::BuildCheckUpdateUrl(const std::wstring& appKey, + const std::wstring& clientVersion) { + std::wstring url = std::wstring(UPDATER_SERVER_URL) + L"/api/v1/app/" + + Utils::UrlEncode(appKey) + L"/check-update"; + if (!clientVersion.empty()) { + url += L"?version=" + Utils::UrlEncode(clientVersion); + } + return url; +} + +std::wstring Api::ResolveUrl(const std::wstring& url) { + std::wstring trimmed = Utils::Trim(url); + if (trimmed.empty()) return std::wstring(); + if (Utils::IsAbsoluteUrl(trimmed)) return trimmed; + + std::wstring base = UPDATER_SERVER_URL; + while (!base.empty() && (base.back() == L'/' || base.back() == L'\\')) base.pop_back(); + if (trimmed.front() != L'/') trimmed.insert(trimmed.begin(), L'/'); + return base + trimmed; +} + +Api::Result Api::CheckUpdate(const std::wstring& appKey, const std::wstring& clientVersion) { + Result result; + + Http::SetTimeoutSec(UPDATER_TIMEOUT_SEC); + + std::wstring url = BuildCheckUpdateUrl(appKey, clientVersion); + HttpResult http; + std::wstring err; + if (!Http::Get(url, http, err)) { + result.error = L"连接服务器失败:" + err; + return result; + } + + Json root; + std::string parseErr; + if (!Json::Parse(http.body, root, parseErr)) { + result.error = L"服务器返回内容无法解析"; + return result; + } + + // 服务端开启通信加密时,data 是一整段 base64 密文,解密后才是真正的响应 +#if UPDATER_ENCRYPT_TYPE != 0 + if (root.isObject() && root["data"].isString()) { + std::string plain; + std::string cryptoErr; + std::string key = Utils::WideToUtf8(UPDATER_ENCRYPT_KEY); + if (!Crypto::Decrypt(static_cast(UPDATER_ENCRYPT_TYPE), key, + root["data"].stringValue(), plain, cryptoErr)) { + result.error = L"响应解密失败:" + Utils::Utf8ToWide(cryptoErr); + return result; + } + if (!Json::Parse(plain, root, parseErr)) { + result.error = L"服务器返回内容无法解析"; + return result; + } + } +#endif + + result.httpStatus = http.status; + result.code = static_cast(root["code"].intValue(0)); + result.message = Utils::Utf8ToWide(root["message"].stringValue()); + + // 业务层失败(如 404 应用不存在、400 版本号参数错误) + if (result.code != 200 && result.code != 0) { + result.error = result.message.empty() ? L"请求失败" : result.message; + return result; + } + + // 正常响应字段在 data 里,兼容后台直接把字段放在根上的情况 + const Json& data = root["data"].isObject() ? root["data"] : root; + if (!data.isObject()) { + result.error = L"服务器返回内容无法解析"; + return result; + } + + UpdateInfo& info = result.info; + info.hasUpdate = data["has_update"].boolValue(false); + info.appName = ReadString(data, "app_name"); + info.currentVersion = ReadString(data, "current_version"); + info.latestVersion = ReadString(data, "latest_version"); + + info.downloadUrl = ResolveUrl(ReadString(data, "download_url")); + info.downloadSize = ReadUInt64(data, "file_size"); + info.downloadHash = ReadString(data, "file_hash"); + + info.entryFile = ReadString(data, "entry_file"); + ParseStringList(data["entry_files"], info.entryFiles); + ParseStringList(data["desktop_shortcut_files"], info.desktopShortcutFiles); + + info.updateNotes = ReadString(data, "update_notes"); + info.changelog = ReadString(data, "changelog"); + info.updateStrategy = ReadString(data, "update_strategy"); + info.updateType = ReadString(data, "update_type"); + info.updateMethod = ReadString(data, "update_method"); + + info.isPatch = data["is_patch"].boolValue(false); + info.patchUrl = ResolveUrl(ReadString(data, "patch_url")); + info.patchSize = ReadUInt64(data, "patch_size"); + info.patchHash = ReadString(data, "patch_hash"); + + info.fullPackageUrl = ResolveUrl(ReadString(data, "full_package_url")); + info.fullPackageSize = ReadUInt64(data, "full_package_size"); + info.fullPackageHash = ReadString(data, "full_package_hash"); + + // 补丁包信息缺失时用主下载地址兜底 + if (info.isPatch && info.patchUrl.empty()) { + info.patchUrl = info.downloadUrl; + info.patchSize = info.downloadSize; + info.patchHash = info.downloadHash; + } + // 完整包信息缺失时用主下载地址兜底 + if (info.fullPackageUrl.empty() && !info.isPatch) { + info.fullPackageUrl = info.downloadUrl; + info.fullPackageSize = info.downloadSize; + info.fullPackageHash = info.downloadHash; + } + + result.ok = true; + return result; +} + +} diff --git a/Update/Api.h b/Update/Api.h new file mode 100644 index 0000000..490b031 --- /dev/null +++ b/Update/Api.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +namespace updater { + +// check-update 返回的版本信息 +struct UpdateInfo { + bool hasUpdate = false; + + std::wstring appName; + std::wstring currentVersion; + std::wstring latestVersion; + + // 主下载地址:补丁模式下为补丁包,全量模式下为完整包 + std::wstring downloadUrl; + unsigned long long downloadSize = 0; + std::wstring downloadHash; + + std::wstring entryFile; + std::vector entryFiles; + std::vector desktopShortcutFiles; + + std::wstring updateNotes; // Description,简短说明 + std::wstring changelog; // 详细变更记录 + std::wstring updateStrategy; // optional / forced + std::wstring updateType; // full / patch + std::wstring updateMethod; // auto / manual / silent + + bool isPatch = false; + std::wstring patchUrl; + unsigned long long patchSize = 0; + std::wstring patchHash; + + std::wstring fullPackageUrl; + unsigned long long fullPackageSize = 0; + std::wstring fullPackageHash; +}; + +class Api { +public: + struct Result { + bool ok = false; + std::wstring error; // 失败原因(已本地化) + long httpStatus = 0; // HTTP 状态码 + int code = 0; // 业务 code + std::wstring message; // 服务端 message + UpdateInfo info; + }; + + // clientVersion 为空时按“安装器模式”请求,服务端优先返回全量包 + static Result CheckUpdate(const std::wstring& appKey, + const std::wstring& clientVersion); + + static std::wstring BuildCheckUpdateUrl(const std::wstring& appKey, + const std::wstring& clientVersion); + + // 把服务端返回的相对路径补全为绝对地址 + static std::wstring ResolveUrl(const std::wstring& url); +}; + +} diff --git a/Update/Config.h b/Update/Config.h new file mode 100644 index 0000000..0d8115b --- /dev/null +++ b/Update/Config.h @@ -0,0 +1,81 @@ +#pragma once + +// 编译期配置:按实际情况修改下面几个宏后重新编译 + +// 服务端地址(末尾不要带斜杠) +#ifndef UPDATER_SERVER_URL +#define UPDATER_SERVER_URL L"https://gendan.xyz" +#endif + +// 应用 AppKey,取自 verify 后台 -> 应用 -> AppKey +#ifndef UPDATER_APP_KEY +#define UPDATER_APP_KEY L"abab3280114bfe824acfdbc6255538fb" +#endif + +// 通信加密方式:0 = 不加密,1 = RC4,2 = AES-256-GCM +// 取自 verify 后台 -> 应用 -> 安全设置 -> 加密方式 +#ifndef UPDATER_ENCRYPT_TYPE +#define UPDATER_ENCRYPT_TYPE 2 +#endif + +// 通信密钥,取自 verify 后台 -> 应用 -> 安全设置 -> 加密密钥 +// 服务端用 AES-GCM 加密整个响应体,密钥不对会直接解密失败 +#ifndef UPDATER_ENCRYPT_KEY +#define UPDATER_ENCRYPT_KEY L"07dab7c3c772a8a8f2dad3f45e2e397806d92f560ac954532ee7562a03c1df14" +#endif + +// 窗口标题 +#ifndef UPDATER_TITLE +#define UPDATER_TITLE L"自动更新" +#endif + +// 更新完成后拉起的程序(相对更新目录),留空则不拉起 +#ifndef UPDATER_LAUNCH_EXE +#define UPDATER_LAUNCH_EXE L"金运来客户端2.exe" +#endif + +// 应用名称,显示在安装目录选择界面上 +#ifndef UPDATER_APP_NAME +#define UPDATER_APP_NAME L"金运来皇冠跟单软件" +#endif + +// 完整包安装时建议的默认目录,留空则用更新器自身所在目录 +// (更新器由主程序从自身目录启动,所以默认就是主程序所在目录) +#ifndef UPDATER_DEFAULT_INSTALL_DIR +#define UPDATER_DEFAULT_INSTALL_DIR L"" +#endif + +// 更新目标目录,留空表示更新器自身所在目录(完整包模式下会先让用户选择) +#ifndef UPDATER_TARGET_DIR +#define UPDATER_TARGET_DIR L"" +#endif + +// 是否校验下载包的 SHA256(与服务端返回的 file_hash 比对) +#ifndef UPDATER_VERIFY_HASH +#define UPDATER_VERIFY_HASH 1 +#endif + +// 下载时是否允许使用系统代理 +#ifndef UPDATER_USE_PROXY +#define UPDATER_USE_PROXY 1 +#endif + +// 更新前等待主程序退出的秒数(0 表示不等待) +#ifndef UPDATER_WAIT_EXIT_SEC +#define UPDATER_WAIT_EXIT_SEC 10 +#endif + +// 网络超时(秒) +#define UPDATER_TIMEOUT_SEC 30 + +// 窗口尺寸 +#define UPDATER_WINDOW_WIDTH 860 +#define UPDATER_WINDOW_HEIGHT 480 + +// 静默检查(--check-only)的退出码,主程序据此决定继续启动还是交给更新器 +#define UPDATER_EXIT_NO_UPDATE 0 // 已是最新,主程序正常往下走 +#define UPDATER_EXIT_HAS_UPDATE 1 // 有更新,主程序拉起更新器后退出 +#define UPDATER_EXIT_FAILED 2 // 检查失败(网络异常/解密失败/解析失败) +#define UPDATER_EXIT_BAD_VERSION 3 // 服务端不认识这个版本(HTTP 400 版本号参数错误),只能整包重装 + +// 主程序收到“检查失败”时是否放行由主程序决定(默认放行,避免断网把用户挡在门外) diff --git a/Update/Crypto.cpp b/Update/Crypto.cpp new file mode 100644 index 0000000..60be640 --- /dev/null +++ b/Update/Crypto.cpp @@ -0,0 +1,209 @@ +#include "Crypto.h" + +#define NOMINMAX +#include + +#include + +#include +#include + +#pragma comment(lib, "bcrypt.lib") + +namespace updater { + +std::vector Crypto::PadKey(const std::vector& key, size_t target) { + if (key.size() >= target) { + return std::vector(key.begin(), key.begin() + target); + } + std::vector padded(target, 0); + for (size_t i = 0; i < target; ++i) padded[i] = key[i % key.size()]; + return padded; +} + +bool Crypto::Base64Decode(const std::string& input, std::vector& out) { + static const int table[256] = { + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, + 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, + 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, + -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, + 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1 + }; + + out.clear(); + unsigned int buffer = 0; + int bits = 0; + for (unsigned char c : input) { + int value = table[c]; + if (value < 0) { + if (c == '=' || c == '\r' || c == '\n' || c == ' ' || c == '\t') continue; + return false; + } + buffer = (buffer << 6) | static_cast(value); + bits += 6; + if (bits >= 8) { + bits -= 8; + out.push_back(static_cast((buffer >> bits) & 0xFF)); + } + } + return true; +} + +std::string Crypto::Base64Encode(const std::vector& input) { + static const char* chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::string out; + out.reserve(((input.size() + 2) / 3) * 4); + for (size_t i = 0; i < input.size(); i += 3) { + unsigned int n = static_cast(input[i]) << 16; + if (i + 1 < input.size()) n |= static_cast(input[i + 1]) << 8; + if (i + 2 < input.size()) n |= static_cast(input[i + 2]); + + out.push_back(chars[(n >> 18) & 0x3F]); + out.push_back(chars[(n >> 12) & 0x3F]); + out.push_back((i + 1 < input.size()) ? chars[(n >> 6) & 0x3F] : '='); + out.push_back((i + 2 < input.size()) ? chars[n & 0x3F] : '='); + } + return out; +} + +bool Crypto::DecryptAes(const std::string& key, const std::string& ciphertext, std::string& out, + std::string& err) { + std::vector data; + if (!Base64Decode(ciphertext, data)) { + err = "密文 base64 解码失败"; + return false; + } + const size_t kNonceSize = 12; + const size_t kTagSize = 16; + if (data.size() < kNonceSize + kTagSize) { + err = "密文长度不足"; + return false; + } + + std::vector keyBytes = + PadKey(std::vector(key.begin(), key.end()), 32); + + BCRYPT_ALG_HANDLE alg = nullptr; + NTSTATUS status = BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0); + if (status < 0) { + err = "无法初始化 AES"; + return false; + } + + status = BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, + reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_GCM)), + static_cast((wcslen(BCRYPT_CHAIN_MODE_GCM) + 1) * sizeof(wchar_t)), + 0); + if (status < 0) { + BCryptCloseAlgorithmProvider(alg, 0); + err = "无法设置 GCM 模式"; + return false; + } + + // BCRYPT_KEY_DATA_BLOB:magic(4) + version(4) + cbKeyData(4) + key bytes + const ULONG kHeaderSize = 12; + std::vector blob(kHeaderSize + keyBytes.size(), 0); + ULONG magic = 0x4D42444B; // 'KDBM' + ULONG version = 1; + ULONG keyLen = static_cast(keyBytes.size()); + memcpy(blob.data(), &magic, sizeof(magic)); + memcpy(blob.data() + 4, &version, sizeof(version)); + memcpy(blob.data() + 8, &keyLen, sizeof(keyLen)); + memcpy(blob.data() + kHeaderSize, keyBytes.data(), keyBytes.size()); + + BCRYPT_KEY_HANDLE keyHandle = nullptr; + status = BCryptImportKey(alg, nullptr, BCRYPT_KEY_DATA_BLOB, &keyHandle, nullptr, 0, + blob.data(), static_cast(blob.size()), 0); + if (status < 0) { + BCryptCloseAlgorithmProvider(alg, 0); + err = "密钥导入失败"; + return false; + } + + // 密文布局:nonce || ciphertext || tag,tag 单独传给 bcrypt,不能算进密文长度 + size_t cipherLen = data.size() - kNonceSize - kTagSize; + std::vector nonce(data.begin(), data.begin() + kNonceSize); + std::vector tag(data.end() - kTagSize, data.end()); + std::vector plain(cipherLen, 0); + + BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; + BCRYPT_INIT_AUTH_MODE_INFO(info); + info.pbNonce = nonce.data(); + info.cbNonce = static_cast(nonce.size()); + info.pbTag = tag.data(); + info.cbTag = static_cast(tag.size()); + + ULONG plainLen = 0; + status = BCryptDecrypt(keyHandle, data.data() + kNonceSize, static_cast(cipherLen), + &info, nullptr, 0, plain.data(), static_cast(plain.size()), + &plainLen, 0); + + BCryptDestroyKey(keyHandle); + BCryptCloseAlgorithmProvider(alg, 0); + + if (status < 0) { + err = "解密失败(密钥不正确或数据被篡改)"; + return false; + } + + out.assign(reinterpret_cast(plain.data()), plainLen); + return true; +} + +bool Crypto::DecryptRc4(const std::string& key, const std::string& ciphertext, std::string& out, + std::string& err) { + std::vector data; + if (!Base64Decode(ciphertext, data)) { + err = "密文 base64 解码失败"; + return false; + } + if (key.empty()) { + err = "RC4 密钥为空"; + return false; + } + + unsigned char sbox[256]; + for (int i = 0; i < 256; ++i) sbox[i] = static_cast(i); + + unsigned char j = 0; + for (int i = 0; i < 256; ++i) { + j = static_cast(j + sbox[i] + key[i % key.size()]); + unsigned char tmp = sbox[i]; + sbox[i] = sbox[j]; + sbox[j] = tmp; + } + + unsigned char i = 0; + j = 0; + out.clear(); + out.reserve(data.size()); + for (unsigned char c : data) { + i = static_cast(i + 1); + j = static_cast(j + sbox[i]); + unsigned char tmp = sbox[i]; + sbox[i] = sbox[j]; + sbox[j] = tmp; + out.push_back(static_cast(c ^ sbox[(sbox[i] + sbox[j]) & 0xFF])); + } + return true; +} + +bool Crypto::Decrypt(EncryptType type, const std::string& key, const std::string& ciphertext, + std::string& out, std::string& err) { + if (type == EncryptType::None) { + out = ciphertext; + return true; + } + if (key.empty()) { + err = "未配置通信密钥"; + return false; + } + if (type == EncryptType::AES) return DecryptAes(key, ciphertext, out, err); + return DecryptRc4(key, ciphertext, out, err); +} + +} diff --git a/Update/Crypto.h b/Update/Crypto.h new file mode 100644 index 0000000..976294c --- /dev/null +++ b/Update/Crypto.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +namespace updater { + +enum class EncryptType { + None = 0, + RC4 = 1, + AES = 2, // AES-256-GCM:12 字节 nonce 前置 + 16 字节 tag +}; + +class Crypto { +public: + // 与 Go 端 crypto.padKey 保持一致:不足 target 时循环补齐,超出则截断 + static std::vector PadKey(const std::vector& key, size_t target); + + static bool Base64Decode(const std::string& input, std::vector& out); + static std::string Base64Encode(const std::vector& input); + + // ciphertext 为 base64 字符串,out 为解密后的明文 + static bool Decrypt(EncryptType type, const std::string& key, const std::string& ciphertext, + std::string& out, std::string& err); + +private: + static bool DecryptAes(const std::string& key, const std::string& ciphertext, std::string& out, + std::string& err); + static bool DecryptRc4(const std::string& key, const std::string& ciphertext, std::string& out, + std::string& err); +}; + +} diff --git a/Update/FileInfo.cpp b/Update/FileInfo.cpp deleted file mode 100644 index 575a914..0000000 --- a/Update/FileInfo.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "FileInfo.h" - - -bool FileInfo::QueryValue(const std::wstring wsValueName, const std::wstring wsModuleName, std::wstring &wsRetStr) -{ - bool bSuccess = FALSE; - BYTE *lpVersionData = NULL; - DWORD dwLangCharset = 0; - TCHAR *pStr = NULL; - - do - { - if (wsValueName.empty() || wsModuleName.empty()) - break; - - DWORD dwHandle; - // 判断系统能否检索到指定文件的版本信息 - DWORD dwDataSize = ::GetFileVersionInfoSize((LPCWSTR)wsModuleName.c_str(), &dwHandle); - if (dwDataSize == 0) - break; - - lpVersionData = new (std::nothrow) BYTE[dwDataSize];// 分配缓冲区 - if (NULL == lpVersionData) - break; - - // 检索信息 - if (!::GetFileVersionInfo((LPCWSTR)wsModuleName.c_str(), dwHandle, dwDataSize, (void*)lpVersionData)) - break; - - UINT nQuerySize; - DWORD *pTransTable; - // 设置语言 - if (!::VerQueryValue(lpVersionData, L"\\VarFileInfo\\Translation", (void **)&pTransTable, &nQuerySize)) - break; - - dwLangCharset = MAKELONG(HIWORD(pTransTable[0]), LOWORD(pTransTable[0])); - if (lpVersionData == NULL) - break; - - pStr = new (std::nothrow) TCHAR[128];// 分配缓冲区 - if (NULL == pStr) - break; - - //wchar_t str2[MAX_PATH]; - //wcscpy_s(str2, MAX_PATH, wsValueName.c_str()); - swprintf_s(pStr, 128, L"\\StringFileInfo\\%08lx\\%s", dwLangCharset, wsValueName.c_str()); - - LPVOID lpData; - - // 调用此函数查询前需要先依次调用函数GetFileVersionInfoSize和GetFileVersionInfo - if (::VerQueryValue((void *)lpVersionData, pStr, &lpData, &nQuerySize)) - wsRetStr = (TCHAR *)lpData; - - bSuccess = TRUE; - - } while (FALSE); - - // 销毁缓冲区 - if (lpVersionData) - { - delete[] lpVersionData; - lpVersionData = NULL; - } - if (pStr) - { - delete[] pStr; - pStr = NULL; - } - - return bSuccess; -} diff --git a/Update/FileInfo.h b/Update/FileInfo.h deleted file mode 100644 index 3e9d8ad..0000000 --- a/Update/FileInfo.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include -#include - -#pragma comment(lib,"Version.lib") - -class FileInfo -{ -public: - static bool GetFileDescription(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"FileDescription", szModuleName, RetStr); } - static bool GetFileVersion(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"FileVersion", szModuleName, RetStr); } - static bool GetInternalName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"InternalName", szModuleName, RetStr); } - static bool GetCompanyName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"CompanyName", szModuleName, RetStr); } - static bool GetLegalCopyright(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"LegalCopyright", szModuleName, RetStr); } - static bool GetOriginalFilename(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"OriginalFilename", szModuleName, RetStr); } - static bool GetProductName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"ProductName", szModuleName, RetStr); } - static bool GetProductVersion(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"ProductVersion", szModuleName, RetStr); } - -private: - static bool QueryValue(const std::wstring wsValueName, const std::wstring wsModuleName, std::wstring &wsRetStr); -}; diff --git a/Update/Http.cpp b/Update/Http.cpp new file mode 100644 index 0000000..da092e9 --- /dev/null +++ b/Update/Http.cpp @@ -0,0 +1,253 @@ +#include "Http.h" + +#include + +#include +#include + +#pragma comment(lib, "winhttp.lib") + +namespace updater { + +int Http::timeoutSec_ = 30; + +namespace { + +struct UrlParts { + std::wstring host; + std::wstring path; + INTERNET_PORT port = INTERNET_DEFAULT_HTTP_PORT; + bool https = false; +}; + +bool CrackUrl(const std::wstring& url, UrlParts& out) { + URL_COMPONENTS uc; + ZeroMemory(&uc, sizeof(uc)); + uc.dwStructSize = sizeof(uc); + uc.dwSchemeLength = static_cast(-1); + uc.dwHostNameLength = static_cast(-1); + uc.dwUrlPathLength = static_cast(-1); + uc.dwExtraInfoLength = static_cast(-1); + if (!WinHttpCrackUrl(url.c_str(), static_cast(url.size()), 0, &uc)) return false; + + out.host.assign(uc.lpszHostName, uc.dwHostNameLength); + out.path.assign(uc.lpszUrlPath, uc.dwUrlPathLength); + if (uc.dwExtraInfoLength > 0 && uc.lpszExtraInfo) { + out.path.append(uc.lpszExtraInfo, uc.dwExtraInfoLength); + } + if (out.path.empty()) out.path = L"/"; + out.port = uc.nPort; + out.https = uc.nScheme == INTERNET_SCHEME_HTTPS; + return true; +} + +std::wstring ResolveUrl(const std::wstring& base, const std::wstring& location) { + if (location.empty()) return std::wstring(); + if (_wcsnicmp(location.c_str(), L"http://", 7) == 0 || + _wcsnicmp(location.c_str(), L"https://", 8) == 0) { + return location; + } + UrlParts parts; + if (!CrackUrl(base, parts)) return location; + std::wstring scheme = parts.https ? L"https://" : L"http://"; + std::wstring hostPort = parts.host; + if ((parts.https && parts.port != INTERNET_DEFAULT_HTTPS_PORT) || + (!parts.https && parts.port != INTERNET_DEFAULT_HTTP_PORT)) { + hostPort += L":" + std::to_wstring(parts.port); + } + if (location[0] == L'/') return scheme + hostPort + location; + + std::wstring dir = parts.path; + size_t pos = dir.find_last_of(L'/'); + if (pos == std::wstring::npos) dir = L"/"; + else dir = dir.substr(0, pos + 1); + return scheme + hostPort + dir + location; +} + +class Session { +public: + Session() { + DWORD access = WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY; + hSession_ = WinHttpOpen(L"Updater/1.0", access, WINHTTP_NO_PROXY_NAME, + WINHTTP_NO_PROXY_BYPASS, 0); + } + ~Session() { + if (hSession_) WinHttpCloseHandle(hSession_); + } + bool valid() const { return hSession_ != nullptr; } + HINTERNET get() const { return hSession_; } + +private: + HINTERNET hSession_ = nullptr; +}; + +class Request { +public: + Request(HINTERNET session, const std::wstring& url, bool download) { + if (!CrackUrl(url, parts_)) return; + hConnect_ = WinHttpConnect(session, parts_.host.c_str(), parts_.port, 0); + if (!hConnect_) return; + DWORD flags = parts_.https ? WINHTTP_FLAG_SECURE : 0; + hRequest_ = WinHttpOpenRequest(hConnect_, L"GET", parts_.path.c_str(), nullptr, + WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags); + if (!hRequest_) return; + WinHttpSetTimeouts(hRequest_, Http::TimeoutMs(), Http::TimeoutMs(), + Http::TimeoutMs(), Http::TimeoutMs()); + if (!download) { + DWORD disable = WINHTTP_DISABLE_COOKIES; + WinHttpSetOption(hRequest_, WINHTTP_OPTION_DISABLE_FEATURE, &disable, + sizeof(disable)); + } + opened_ = true; + } + ~Request() { + if (hRequest_) WinHttpCloseHandle(hRequest_); + if (hConnect_) WinHttpCloseHandle(hConnect_); + } + bool opened() const { return opened_; } + bool Send() { + return WinHttpSendRequest(hRequest_, WINHTTP_NO_REQUEST_DATA, 0, + WINHTTP_NO_REQUEST_DATA, 0, 0, 0) != FALSE && + WinHttpReceiveResponse(hRequest_, nullptr) != FALSE; + } + long Status() { + DWORD code = 0; + DWORD size = sizeof(code); + if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, + WINHTTP_HEADER_NAME_BY_INDEX, &code, &size, + WINHTTP_NO_HEADER_INDEX)) { + return static_cast(code); + } + return 0; + } + std::wstring Location() { + wchar_t buf[4096] = {0}; + DWORD size = sizeof(buf); + if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_LOCATION, WINHTTP_HEADER_NAME_BY_INDEX, + buf, &size, WINHTTP_NO_HEADER_INDEX)) { + return std::wstring(buf); + } + return std::wstring(); + } + unsigned long long ContentLength() { + wchar_t buf[64] = {0}; + DWORD size = sizeof(buf); + if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_CONTENT_LENGTH, + WINHTTP_HEADER_NAME_BY_INDEX, buf, &size, + WINHTTP_NO_HEADER_INDEX)) { + return _wcstoui64(buf, nullptr, 10); + } + return 0; + } + bool ReadAll(std::string& out) { + DWORD available = 0; + std::vector chunk(64 * 1024); + for (;;) { + if (!WinHttpQueryDataAvailable(hRequest_, &available)) return false; + if (available == 0) break; + if (available > chunk.size()) chunk.resize(available); + DWORD read = 0; + if (!WinHttpReadData(hRequest_, chunk.data(), available, &read)) return false; + if (read == 0) break; + out.append(chunk.data(), read); + } + return true; + } + bool ReadToFile(HANDLE hFile, Http::ProgressFunc progress, unsigned long long total, + unsigned long long& written) { + DWORD available = 0; + std::vector chunk(64 * 1024); + for (;;) { + if (!WinHttpQueryDataAvailable(hRequest_, &available)) return false; + if (available == 0) break; + if (available > chunk.size()) chunk.resize(available); + DWORD read = 0; + if (!WinHttpReadData(hRequest_, chunk.data(), available, &read)) return false; + if (read == 0) break; + DWORD done = 0; + while (done < read) { + DWORD step = 0; + if (!WriteFile(hFile, chunk.data() + done, read - done, &step, nullptr)) return false; + done += step; + } + written += read; + if (progress && !progress(written, total)) return false; + } + return true; + } + +private: + UrlParts parts_; + HINTERNET hConnect_ = nullptr; + HINTERNET hRequest_ = nullptr; + bool opened_ = false; +}; + +} + +static const int kMaxRedirect = 6; + +bool Http::Get(const std::wstring& url, HttpResult& out, std::wstring& err) { + std::wstring current = url; + for (int i = 0; i < kMaxRedirect; ++i) { + Session session; + if (!session.valid()) { err = L"无法初始化网络"; return false; } + Request request(session.get(), current, false); + if (!request.opened()) { err = L"无法创建请求: " + current; return false; } + if (!request.Send()) { err = L"请求失败: " + current; return false; } + long status = request.Status(); + if (status >= 300 && status < 400) { + std::wstring loc = request.Location(); + std::wstring next = ResolveUrl(current, loc); + if (next.empty()) { err = L"重定向地址无效"; return false; } + current = next; + continue; + } + out.status = status; + if (!request.ReadAll(out.body)) { err = L"读取响应失败"; return false; } + return true; + } + err = L"重定向次数过多"; + return false; +} + +bool Http::Download(const std::wstring& url, const std::wstring& savePath, + ProgressFunc progress, std::wstring& err) { + std::wstring current = url; + for (int i = 0; i < kMaxRedirect; ++i) { + Session session; + if (!session.valid()) { err = L"无法初始化网络"; return false; } + Request request(session.get(), current, true); + if (!request.opened()) { err = L"无法创建请求: " + current; return false; } + if (!request.Send()) { err = L"请求失败: " + current; return false; } + long status = request.Status(); + if (status >= 300 && status < 400) { + std::wstring loc = request.Location(); + std::wstring next = ResolveUrl(current, loc); + if (next.empty()) { err = L"重定向地址无效"; return false; } + current = next; + continue; + } + if (status != 200) { + err = L"下载失败,HTTP " + std::to_wstring(status); + return false; + } + HANDLE hFile = CreateFileW(savePath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (hFile == INVALID_HANDLE_VALUE) { err = L"无法创建临时文件"; return false; } + unsigned long long written = 0; + bool ok = request.ReadToFile(hFile, progress, request.ContentLength(), written); + FlushFileBuffers(hFile); + CloseHandle(hFile); + if (!ok) { + DeleteFileW(savePath.c_str()); + err = L"下载中断"; + return false; + } + return true; + } + err = L"重定向次数过多"; + return false; +} + +} diff --git a/Update/Http.h b/Update/Http.h new file mode 100644 index 0000000..6b9929a --- /dev/null +++ b/Update/Http.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +#include +#include + +namespace updater { + +struct HttpResult { + long status = 0; + std::string body; +}; + +class Http { +public: + using ProgressFunc = std::function; + + static bool Get(const std::wstring& url, HttpResult& out, std::wstring& err); + + static bool Download(const std::wstring& url, + const std::wstring& savePath, + ProgressFunc progress, + std::wstring& err); + + static void SetTimeoutSec(int sec) { timeoutSec_ = sec; } + + static int TimeoutMs() { return timeoutSec_ * 1000; } + +private: + static int timeoutSec_; +}; + +} diff --git a/Update/Json.cpp b/Update/Json.cpp new file mode 100644 index 0000000..3c78e06 --- /dev/null +++ b/Update/Json.cpp @@ -0,0 +1,277 @@ +#include "Json.h" + +#include + +namespace updater { + +struct Json::Impl { + bool boolVal = false; + double numVal = 0.0; + std::string strVal; + std::vector arrVal; + std::map objVal; +}; + +struct JsonAccess { + static Json::Impl& impl(Json& j) { return *j.impl_; } + static void setType(Json& j, Json::Type t) { j.type_ = t; } +}; + +Json::Json() : impl_(std::make_shared()), type_(Null) {} +Json::Json(Type type) : impl_(std::make_shared()), type_(type) {} + +bool Json::boolValue(bool def) const { + if (type_ == Bool) return impl_->boolVal; + if (type_ == Number) return impl_->numVal != 0.0; + return def; +} + +double Json::numberValue(double def) const { + if (type_ == Number) return impl_->numVal; + return def; +} + +long long Json::intValue(long long def) const { + if (type_ == Number) return static_cast(impl_->numVal); + return def; +} + +std::string Json::stringValue(const std::string& def) const { + if (type_ == String) return impl_->strVal; + return def; +} + +const Json& Json::operator[](const char* key) const { + static const Json nullValue; + if (type_ != Object) return nullValue; + auto it = impl_->objVal.find(key); + if (it == impl_->objVal.end()) return nullValue; + return it->second; +} + +const Json& Json::operator[](const std::string& key) const { + return (*this)[key.c_str()]; +} + +const Json& Json::operator[](size_t index) const { + static const Json nullValue; + if (type_ != Array || index >= impl_->arrVal.size()) return nullValue; + return impl_->arrVal[index]; +} + +bool Json::contains(const char* key) const { + return type_ == Object && impl_->objVal.find(key) != impl_->objVal.end(); +} + +size_t Json::arraySize() const { + return type_ == Array ? impl_->arrVal.size() : 0; +} + +namespace { + +void AppendUtf8(std::string& out, unsigned int cp) { + if (cp < 0x80) { + out += static_cast(cp); + } else if (cp < 0x800) { + out += static_cast(0xC0 | (cp >> 6)); + out += static_cast(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + out += static_cast(0xE0 | (cp >> 12)); + out += static_cast(0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(0x80 | (cp & 0x3F)); + } else { + out += static_cast(0xF0 | (cp >> 18)); + out += static_cast(0x80 | ((cp >> 12) & 0x3F)); + out += static_cast(0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(0x80 | (cp & 0x3F)); + } +} + +bool Hex4(const std::string& s, size_t pos, unsigned int& out) { + if (pos + 4 > s.size()) return false; + unsigned int v = 0; + for (size_t i = 0; i < 4; ++i) { + char c = s[pos + i]; + v <<= 4; + if (c >= '0' && c <= '9') v |= static_cast(c - '0'); + else if (c >= 'a' && c <= 'f') v |= static_cast(c - 'a' + 10); + else if (c >= 'A' && c <= 'F') v |= static_cast(c - 'A' + 10); + else return false; + } + out = v; + return true; +} + +class Parser { +public: + explicit Parser(const std::string& text) : s_(text) {} + + bool ParseValue(Json& out, std::string& err) { + SkipSpace(); + if (pos_ >= s_.size()) { err = "unexpected end"; return false; } + char c = s_[pos_]; + if (c == '{') return ParseObject(out, err); + if (c == '[') return ParseArray(out, err); + if (c == '"') { + std::string str; + if (!ParseString(str, err)) return false; + JsonAccess::setType(out, Json::String); + JsonAccess::impl(out).strVal = str; + return true; + } + if (s_.compare(pos_, 4, "true") == 0) { + pos_ += 4; + JsonAccess::setType(out, Json::Bool); + JsonAccess::impl(out).boolVal = true; + return true; + } + if (s_.compare(pos_, 5, "false") == 0) { + pos_ += 5; + JsonAccess::setType(out, Json::Bool); + JsonAccess::impl(out).boolVal = false; + return true; + } + if (s_.compare(pos_, 4, "null") == 0) { + pos_ += 4; + JsonAccess::setType(out, Json::Null); + return true; + } + return ParseNumber(out, err); + } + +private: + void SkipSpace() { + while (pos_ < s_.size()) { + char c = s_[pos_]; + if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++pos_; + else break; + } + } + + bool ParseString(std::string& out, std::string& err) { + if (pos_ >= s_.size() || s_[pos_] != '"') { err = "expected string"; return false; } + ++pos_; + out.clear(); + while (pos_ < s_.size()) { + char c = s_[pos_]; + if (c == '"') { ++pos_; return true; } + if (c == '\\') { + ++pos_; + if (pos_ >= s_.size()) break; + char e = s_[pos_++]; + switch (e) { + case '"': out += '"'; break; + case '\\': out += '\\'; break; + case '/': out += '/'; break; + case 'b': out += '\b'; break; + case 'f': out += '\f'; break; + case 'n': out += '\n'; break; + case 'r': out += '\r'; break; + case 't': out += '\t'; break; + case 'u': { + unsigned int cp = 0; + if (!Hex4(s_, pos_, cp)) { err = "bad unicode escape"; return false; } + pos_ += 4; + if (cp >= 0xD800 && cp <= 0xDBFF && pos_ + 1 < s_.size() && + s_[pos_] == '\\' && s_[pos_ + 1] == 'u') { + unsigned int lo = 0; + if (Hex4(s_, pos_ + 2, lo) && lo >= 0xDC00 && lo <= 0xDFFF) { + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); + pos_ += 6; + } + } + AppendUtf8(out, cp); + break; + } + default: out += e; break; + } + } else { + out += c; + ++pos_; + } + } + err = "unterminated string"; + return false; + } + + bool ParseNumber(Json& out, std::string& err) { + size_t start = pos_; + if (pos_ < s_.size() && (s_[pos_] == '-' || s_[pos_] == '+')) ++pos_; + bool hasDigit = false; + while (pos_ < s_.size() && s_[pos_] >= '0' && s_[pos_] <= '9') { ++pos_; hasDigit = true; } + if (pos_ < s_.size() && s_[pos_] == '.') { + ++pos_; + while (pos_ < s_.size() && s_[pos_] >= '0' && s_[pos_] <= '9') { ++pos_; hasDigit = true; } + } + if (hasDigit && pos_ < s_.size() && (s_[pos_] == 'e' || s_[pos_] == 'E')) { + ++pos_; + if (pos_ < s_.size() && (s_[pos_] == '-' || s_[pos_] == '+')) ++pos_; + while (pos_ < s_.size() && s_[pos_] >= '0' && s_[pos_] <= '9') ++pos_; + } + if (!hasDigit) { err = "invalid number"; return false; } + std::string num = s_.substr(start, pos_ - start); + JsonAccess::setType(out, Json::Number); + JsonAccess::impl(out).numVal = strtod(num.c_str(), nullptr); + return true; + } + + bool ParseArray(Json& out, std::string& err) { + ++pos_; + JsonAccess::setType(out, Json::Array); + SkipSpace(); + if (pos_ < s_.size() && s_[pos_] == ']') { ++pos_; return true; } + while (pos_ < s_.size()) { + Json item; + if (!ParseValue(item, err)) return false; + JsonAccess::impl(out).arrVal.push_back(item); + SkipSpace(); + if (pos_ < s_.size() && s_[pos_] == ',') { ++pos_; continue; } + if (pos_ < s_.size() && s_[pos_] == ']') { ++pos_; return true; } + err = "expected , or ]"; + return false; + } + err = "unterminated array"; + return false; + } + + bool ParseObject(Json& out, std::string& err) { + ++pos_; + JsonAccess::setType(out, Json::Object); + SkipSpace(); + if (pos_ < s_.size() && s_[pos_] == '}') { ++pos_; return true; } + while (pos_ < s_.size()) { + SkipSpace(); + std::string key; + if (!ParseString(key, err)) return false; + SkipSpace(); + if (pos_ >= s_.size() || s_[pos_] != ':') { err = "expected :"; return false; } + ++pos_; + Json value; + if (!ParseValue(value, err)) return false; + JsonAccess::impl(out).objVal[key] = value; + SkipSpace(); + if (pos_ < s_.size() && s_[pos_] == ',') { ++pos_; continue; } + if (pos_ < s_.size() && s_[pos_] == '}') { ++pos_; return true; } + err = "expected , or }"; + return false; + } + err = "unterminated object"; + return false; + } + + const std::string& s_; + size_t pos_ = 0; +}; + +} + +bool Json::Parse(const std::string& text, Json& out, std::string& err) { + Parser parser(text); + Json value; + if (!parser.ParseValue(value, err)) return false; + JsonAccess::setType(out, value.type()); + JsonAccess::impl(out) = JsonAccess::impl(value); + return true; +} + +} diff --git a/Update/Json.h b/Update/Json.h new file mode 100644 index 0000000..9079bf2 --- /dev/null +++ b/Update/Json.h @@ -0,0 +1,48 @@ +#pragma once + +#include +#include +#include +#include + +namespace updater { + +class Json { +public: + enum Type { Null, Bool, Number, String, Array, Object }; + + Json(); + explicit Json(Type type); + + Type type() const { return type_; } + + bool isNull() const { return type_ == Null; } + bool isBool() const { return type_ == Bool; } + bool isNumber() const { return type_ == Number; } + bool isString() const { return type_ == String; } + bool isArray() const { return type_ == Array; } + bool isObject() const { return type_ == Object; } + + bool boolValue(bool def = false) const; + double numberValue(double def = 0.0) const; + long long intValue(long long def = 0) const; + std::string stringValue(const std::string& def = "") const; + + const Json& operator[](const char* key) const; + const Json& operator[](const std::string& key) const; + const Json& operator[](size_t index) const; + bool contains(const char* key) const; + + size_t arraySize() const; + + static bool Parse(const std::string& text, Json& out, std::string& err); + +private: + struct Impl; + std::shared_ptr impl_; + Type type_; + + friend struct JsonAccess; +}; + +} diff --git a/Update/Unzip.cpp b/Update/Unzip.cpp new file mode 100644 index 0000000..26ff168 --- /dev/null +++ b/Update/Unzip.cpp @@ -0,0 +1,274 @@ +#include "Unzip.h" + +#define NOMINMAX +#include + +#include "Utils.h" +#include "Miniz.h" + +#include +#include +#include +#include + +namespace updater { + +struct Unzip::Archive { + mz_zip_archive zip; +}; + +namespace { + +// Zip Slip 防护:拒绝绝对路径、盘符、.. 片段 +bool IsSafeRelativePath(const std::wstring& rel) { + if (rel.empty()) return false; + if (rel.front() == L'/' || rel.front() == L'\\') return false; + if (rel.size() >= 2 && rel[1] == L':') return false; + + size_t start = 0; + for (;;) { + size_t pos = rel.find_first_of(L"/\\", start); + std::wstring seg = (pos == std::wstring::npos) + ? rel.substr(start) + : rel.substr(start, pos - start); + if (seg == L"..") return false; + if (pos == std::wstring::npos) break; + start = pos + 1; + if (start >= rel.size()) break; + } + return true; +} + +// 解压回调上下文:把数据写入目标文件 +struct WriteContext { + HANDLE file = INVALID_HANDLE_VALUE; + bool ok = true; +}; + +size_t WriteCallback(void* opaque, mz_uint64 /*file_ofs*/, const void* buf, size_t n) { + WriteContext* ctx = static_cast(opaque); + if (!ctx->ok) return 0; + if (n == 0) return n; + + const char* data = static_cast(buf); + size_t done = 0; + while (done < n) { + DWORD step = 0; + DWORD want = static_cast(n - done); + if (!WriteFile(ctx->file, data + done, want, &step, nullptr) || step == 0) { + ctx->ok = false; + return done; + } + done += step; + } + return done; +} + +class FileHandle { +public: + FileHandle() = default; + ~FileHandle() { Close(); } + + bool Open(const std::wstring& path) { + path_ = path; + handle_ = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + return handle_ != INVALID_HANDLE_VALUE; + } + void Close() { + if (handle_ != INVALID_HANDLE_VALUE) { + FlushFileBuffers(handle_); + CloseHandle(handle_); + handle_ = INVALID_HANDLE_VALUE; + } + } + bool valid() const { return handle_ != INVALID_HANDLE_VALUE; } + HANDLE get() const { return handle_; } + const std::wstring& path() const { return path_; } + +private: + HANDLE handle_ = INVALID_HANDLE_VALUE; + std::wstring path_; +}; + +} + +Unzip::Unzip() : archive_(new Archive()) { + memset(&archive_->zip, 0, sizeof(archive_->zip)); +} + +Unzip::~Unzip() { + Close(); + delete archive_; + archive_ = nullptr; +} + +bool Unzip::Open(const std::wstring& zipPath, std::wstring& err) { + Close(); + if (!Utils::FileExists(zipPath)) { + err = L"压缩包不存在:" + zipPath; + return false; + } + + std::string utf8 = Utils::WideToUtf8(zipPath); + // miniz 内部用 CP_UTF8 转换后 fopen,传入 UTF-8 路径即可支持中文 + if (!mz_zip_reader_init_file(&archive_->zip, utf8.c_str(), 0)) { + err = L"无法打开压缩包(文件损坏或不是 zip)"; + memset(&archive_->zip, 0, sizeof(archive_->zip)); + return false; + } + opened_ = true; + return true; +} + +void Unzip::Close() { + if (opened_) { + mz_zip_reader_end(&archive_->zip); + opened_ = false; + } + memset(&archive_->zip, 0, sizeof(archive_->zip)); +} + +unsigned int Unzip::EntryCount() const { + if (!opened_) return 0; + return mz_zip_reader_get_num_files(&archive_->zip); +} + +bool Unzip::EntryAt(unsigned int index, Entry& out) const { + if (!opened_) return false; + mz_zip_archive_file_stat stat; + if (!mz_zip_reader_file_stat(&archive_->zip, index, &stat)) return false; + + out.name = Utils::NormalizeSlashes(Utils::DecodeEntryName(std::string(stat.m_filename))); + out.size = static_cast(stat.m_uncomp_size); + out.directory = stat.m_is_directory != 0; + return true; +} + +bool Unzip::DetectCommonRoot(std::wstring& root) const { + root.clear(); + unsigned int count = EntryCount(); + if (count == 0) return false; + + std::wstring candidate; + for (unsigned int i = 0; i < count; ++i) { + Entry entry; + if (!EntryAt(i, entry)) return false; + if (entry.name.empty()) return false; + + size_t pos = entry.name.find_first_of(L"/\\"); + if (pos == std::wstring::npos || pos == 0) return false; + std::wstring seg = entry.name.substr(0, pos); + std::wstring rest = entry.name.substr(pos + 1); + if (rest.empty()) return false; // 存在仅根目录自身的条目,说明不是纯包装目录 + + if (candidate.empty()) candidate = seg; + else if (candidate != seg) return false; + } + + if (candidate.empty()) return false; + root = candidate; + return true; +} + +bool Unzip::ExtractAll(const std::wstring& targetDir, bool stripRoot, ProgressFunc progress, + std::vector& writtenFiles, std::wstring& err) { + writtenFiles.clear(); + if (!opened_) { + err = L"压缩包未打开"; + return false; + } + + std::wstring root; + bool hasRoot = stripRoot && DetectCommonRoot(root); + if (hasRoot && !IsSafeRelativePath(root)) hasRoot = false; + + unsigned int count = EntryCount(); + unsigned long long totalBytes = 0; + std::vector entries; + std::vector indices; // 条目在压缩包中的原始下标 + entries.reserve(count); + indices.reserve(count); + for (unsigned int i = 0; i < count; ++i) { + Entry entry; + if (!EntryAt(i, entry)) { + err = L"读取压缩包条目失败"; + return false; + } + if (hasRoot) { + if (entry.name.size() > root.size()) entry.name = entry.name.substr(root.size() + 1); + else entry.name.clear(); + } + if (entry.name.empty()) continue; + if (!IsSafeRelativePath(entry.name)) { + err = L"压缩包包含非法路径,已中止:" + entry.name; + return false; + } + totalBytes += entry.size; + entries.push_back(entry); + indices.push_back(i); + } + + if (!Utils::CreateDirRecursive(targetDir)) { + err = L"无法创建目录:" + targetDir; + return false; + } + + unsigned long long doneBytes = 0; + for (size_t i = 0; i < entries.size(); ++i) { + const Entry& entry = entries[i]; + std::wstring dest = Utils::JoinPath(targetDir, entry.name); + + if (entry.directory) { + if (!Utils::CreateDirRecursive(dest)) { + err = L"无法创建目录:" + dest; + return false; + } + continue; + } + + std::wstring parent = Utils::GetParentDir(dest); + if (!parent.empty() && !Utils::CreateDirRecursive(parent)) { + err = L"无法创建目录:" + parent; + return false; + } + + Utils::DeleteFileForce(dest); + + FileHandle file; + if (!file.Open(dest)) { + err = L"无法写入文件:" + dest; + return false; + } + + WriteContext ctx; + ctx.file = file.get(); + if (!mz_zip_reader_extract_to_callback(&archive_->zip, + static_cast(indices[i]), + &WriteCallback, &ctx, 0)) { + file.Close(); + DeleteFileW(dest.c_str()); + err = L"解压失败:" + entry.name; + return false; + } + if (!ctx.ok) { + file.Close(); + DeleteFileW(dest.c_str()); + err = L"写入失败(磁盘空间不足?):" + dest; + return false; + } + file.Close(); + + writtenFiles.push_back(dest); + doneBytes += entry.size; + + if (progress && !progress(doneBytes, totalBytes, entry.name)) { + err = L"已取消"; + return false; + } + } + + return true; +} + +} diff --git a/Update/Unzip.h b/Update/Unzip.h new file mode 100644 index 0000000..a764753 --- /dev/null +++ b/Update/Unzip.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include + +namespace updater { + +// 基于 miniz 的只读解压封装:支持 UTF-8/GBK 条目名、Zip Slip 防护、进度回调 +class Unzip { +public: + struct Entry { + std::wstring name; // 解码后的相对路径 + unsigned long long size = 0; // 解压后大小 + bool directory = false; + }; + + // 返回 false 表示中止解压 + using ProgressFunc = std::function; + + Unzip(); + ~Unzip(); + + Unzip(const Unzip&) = delete; + Unzip& operator=(const Unzip&) = delete; + + bool Open(const std::wstring& zipPath, std::wstring& err); + void Close(); + bool opened() const { return opened_; } + + unsigned int EntryCount() const; + bool EntryAt(unsigned int index, Entry& out) const; + + // 判断包内是否所有条目都位于同一个顶层目录下 + bool DetectCommonRoot(std::wstring& root) const; + + // 解压全部条目到 targetDir + // stripRoot=true 时去掉公共顶层目录 + // writtenFiles 返回实际写入的文件绝对路径 + bool ExtractAll(const std::wstring& targetDir, + bool stripRoot, + ProgressFunc progress, + std::vector& writtenFiles, + std::wstring& err); + +private: + struct Archive; + Archive* archive_ = nullptr; + bool opened_ = false; +}; + +} diff --git a/Update/Update.cpp b/Update/Update.cpp deleted file mode 100644 index 3275f24..0000000 --- a/Update/Update.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "Update.h" -#include "Worker.h" -#include -#include -Update::Update(QWidget *parent):QWidget(parent) -{ - ui.setupUi(this); - - Worker* worker = new Worker(); - - - connect(worker,&Worker::signalProgress,this,&Update::slotUpdateProgress); - connect(worker,&Worker::sigShowStatus,this,&Update::slotUpdateInfo); - connect(worker, &Worker::signalFinished, this, &Update::slotFinished); - worker->start(); -} - -Update::~Update() -{ - -} - - - -// 更新进度 -void Update::slotUpdateProgress(qintptr progress, qintptr max) -{ - qDebug() << "更新进度"; - if (progress > 0 && max > 0) - { - qDebug() << "设置进度:" << progress << "|" << max; - ui.progressBar->setMaximum(max); - ui.progressBar->setValue(progress); - if (progress == max) - { - slotFinished(); - } - } - - -} - -// 完成更新 -void Update::slotFinished() -{ - QMessageBox::information(NULL, "提示", "更新完成!"); - exit(1); - // 启动主程序 - - // 关闭更新程序自身 - -} - -void Update::slotUpdateInfo(QString info) -{ - ui.versionInfo->append(info); -} diff --git a/Update/Update.h b/Update/Update.h deleted file mode 100644 index 177bd5f..0000000 --- a/Update/Update.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include -#include "ui_Update.h" - -class Update : public QWidget -{ - Q_OBJECT - -public: - Update(QWidget *parent = nullptr); - ~Update(); - -public slots: - void slotUpdateProgress(qintptr progress, qintptr max); - void slotFinished(); - void slotUpdateInfo(QString info); - -private: - Ui::UpdateClass ui; -}; diff --git a/Update/Update.qrc b/Update/Update.qrc deleted file mode 100644 index 9ca172d..0000000 --- a/Update/Update.qrc +++ /dev/null @@ -1,9 +0,0 @@ - - - res/alert.png - res/close_0_28_28.png - res/close_1_28_28.png - res/close_2_28_28.png - res/bg.gif - - diff --git a/Update/Update.rc b/Update/Update.rc index 51a448f..2a1a6d1 100644 --- a/Update/Update.rc +++ b/Update/Update.rc @@ -13,7 +13,7 @@ #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// -// ÖÐÎÄ(¼òÌ壬Öйú) resources +// ����(���壬�й�) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED @@ -67,13 +67,13 @@ BEGIN BEGIN BLOCK "080404b0" BEGIN - VALUE "CompanyName", "TODO: <¹«˾Ãû>" - VALUE "FileDescription", "TODO: <Îļþ˵Ã÷>" + VALUE "CompanyName", "TODO: <��˾��>" + VALUE "FileDescription", "TODO: <�ļ�˵��>" VALUE "FileVersion", "1.0.0.1" VALUE "InternalName", "Update.exe" VALUE "LegalCopyright", "Copyright (C) 2023" VALUE "OriginalFilename", "Update.exe" - VALUE "ProductName", "TODO: <²úƷÃû>" + VALUE "ProductName", "TODO: <��Ʒ��>" VALUE "ProductVersion", "1.0.0.1" END END @@ -83,9 +83,20 @@ BEGIN END END -#endif // ÖÐÎÄ(¼òÌ壬Öйú) resources +#endif // ����(���壬�й�) resources ///////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////// +// +// RCDATA (updater self-draw resources, loaded by GDI+) +// + +IDR_BG RCDATA "res\\bg.gif" +IDR_CLOSE_NORMAL RCDATA "res\\close_0_28_28.png" +IDR_CLOSE_HOVER RCDATA "res\\close_1_28_28.png" +IDR_CLOSE_PRESS RCDATA "res\\close_2_28_28.png" + +///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED diff --git a/Update/Update.ui b/Update/Update.ui deleted file mode 100644 index 81c6a9c..0000000 --- a/Update/Update.ui +++ /dev/null @@ -1,79 +0,0 @@ - - - UpdateClass - - - - 0 - 0 - 540 - 370 - - - - Update - - - - - - 7 - - - QLayout::SetDefaultConstraint - - - - - - 微软雅黑 - 10 - - - - 0 - - - true - - - Qt::Horizontal - - - QProgressBar::TopToBottom - - - - - - - - 0 - 50 - - - - - 微软雅黑 - 12 - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'微软雅黑'; font-size:12pt; font-weight:400; font-style:normal;"> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> - - - - - - - - - - - - - diff --git a/Update/Update.vcxproj b/Update/Update.vcxproj index ba159b1..b8c8c8c 100644 --- a/Update/Update.vcxproj +++ b/Update/Update.vcxproj @@ -20,195 +20,147 @@ {9CBBB245-EA92-4F87-A00E-70C3D10F86E8} - QtVS_v304 - 10.0 - 10.0.17763.0 - 10.0.17763.0 - 10.0.17763.0 - $(MSBuildProjectDirectory)\QtMsBuild + Win32Proj + 10.0 + + Application + v142 + Unicode + Application - v143 + v142 + Unicode - + Application - v141 + v142 + Unicode Application - v143 - - - Application - v141 + v142 + Unicode - - - - - 5.12.5_msvc2017_64 - core;xml;network;gui;widgets - debug - - - 5.15.2_msvc2017_static - core;xml;network;gui;widgets - debug - - - 5.12.5_msvc2017_64 - core;xml;network;gui;widgets - release - - - 5.15.2_msvc2017_static - core;xml;network;gui;widgets - release - true - - - - + + + - - + - - - - - - - - - - - - - - + - /utf-8 %(AdditionalOptions) - - - - - - - /utf-8 %(AdditionalOptions) - MultiThreaded - - - - - - /utf-8 %(AdditionalOptions) - - - - - - /utf-8 %(AdditionalOptions) + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + /utf-8 /permissive- %(AdditionalOptions) MultiThreadedDebug - - - - - true - true ProgramDatabase - Disabled + true Windows true + winhttp.lib;bcrypt.lib;gdiplus.lib;shlwapi.lib;shell32.lib;comctl32.lib;%(AdditionalDependencies) - + - true - true - ProgramDatabase + Level3 Disabled + _DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + /utf-8 /permissive- %(AdditionalOptions) + MultiThreadedDebug + ProgramDatabase + true Windows true + winhttp.lib;bcrypt.lib;gdiplus.lib;shlwapi.lib;shell32.lib;comctl32.lib;%(AdditionalDependencies) - + - true - true - None + Level3 MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + /utf-8 /permissive- %(AdditionalOptions) + MultiThreaded + None + true Windows + true + true false + winhttp.lib;bcrypt.lib;gdiplus.lib;shlwapi.lib;shell32.lib;comctl32.lib;%(AdditionalDependencies) - + - true - true - None + Level3 MaxSpeed + true + true + NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + /utf-8 /permissive- %(AdditionalOptions) + MultiThreaded + None + true Windows + true + true false + winhttp.lib;bcrypt.lib;gdiplus.lib;shlwapi.lib;shell32.lib;comctl32.lib;%(AdditionalDependencies) - - - - - + + + + + + - - input - input - %(Filename).moc - %(Filename).moc - input - input - %(Filename).moc - %(Filename).moc - - - - - + + + + + - + + - + + - - - - \ No newline at end of file + + diff --git a/Update/Update.vcxproj.filters b/Update/Update.vcxproj.filters index 30fba93..11d8960 100644 --- a/Update/Update.vcxproj.filters +++ b/Update/Update.vcxproj.filters @@ -1,90 +1,86 @@  - + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - qml;cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + cpp;c;cc;cxx - + {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd + h;hh;hpp;hxx - + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - qrc;rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + rc;ico;png;gif;bmp - - {639EADAA-A684-42e4-A9AD-28FC9BCB8F7C} - ts - - - {4e4e8d8b-11ef-46c3-b18a-14d84970aaef} - - - {2c7bc095-d5bd-4ead-8de0-85ce763a70b8} - - - {222b971c-a4d2-4003-9645-92207e952f59} - - - - - Resource Files - - Source Files + 源文件 + + + 源文件 - Source Files + 源文件 - - Source Files\Form + + 源文件 - - Source Files\FileInfo + + 源文件 + + + 源文件 + + + 源文件 + + + 源文件 - Source Files - - - Source Files\Zip + 源文件 - - Source Files - - - Source Files\Form - - - - - Source Files\Form - - - - - Source Files\FileInfo + + 头文件 + + + 头文件 + + + 头文件 + + + 头文件 + + + 头文件 + + + 头文件 + + + 头文件 + + + 头文件 - Source Files - - - Header Files - - - Source Files\Zip + 头文件 - Source Files\Zip + 头文件 + + + 头文件 - Resource Files + 资源文件 - \ No newline at end of file + diff --git a/Update/Update.xml b/Update/Update.xml deleted file mode 100644 index 23d7c10..0000000 --- a/Update/Update.xml +++ /dev/null @@ -1,157 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Update/UpdateWindow.cpp b/Update/UpdateWindow.cpp new file mode 100644 index 0000000..fb61eae --- /dev/null +++ b/Update/UpdateWindow.cpp @@ -0,0 +1,721 @@ +#define NOMINMAX + +#include "UpdateWindow.h" + +#include "Config.h" +#include "Utils.h" + +#include + +#include + +#include +#include +#include +#include + +#include +#include + +// GDI+ 头文件依赖未限定的 min/max +using std::min; +using std::max; + +#include + +#pragma comment(lib, "gdiplus.lib") +#pragma comment(lib, "shlwapi.lib") +#pragma comment(lib, "ole32.lib") + +namespace updater { + +namespace { + +const UINT kWmState = WM_APP + 1; +const UINT kTimerClose = 1; + +const int kWidth = UPDATER_WINDOW_WIDTH; +const int kHeight = UPDATER_WINDOW_HEIGHT; + +const int kCloseSize = 28; +const int kCloseMarginX = 14; +const int kCloseMarginY = 12; + +// 更新进度面板 +const int kPanelX = 48; +const int kPanelY = 300; +const int kPanelW = kWidth - kPanelX * 2; +const int kPanelH = 132; + +const int kTextX = 72; +const int kTitleY = 316; +const int kStatusY = 356; +const int kBarX = 72; +const int kBarY = 388; +const int kBarW = kWidth - kBarX * 2; +const int kBarH = 12; + +// 安装目录选择面板 +const int kPickPanelX = 48; +const int kPickPanelY = 176; +const int kPickPanelW = kWidth - kPickPanelX * 2; +const int kPickPanelH = 248; + +const int kPickTextX = 72; +const int kPickTitleY = 196; +const int kPickHintY = 234; + +const int kPathX = 72; +const int kPathY = 268; +const int kPathW = 596; +const int kPathH = 38; + +const int kBrowseX = kPathX + kPathW + 12; +const int kBrowseW = 116; + +const int kSpaceY = 318; + +const int kButtonY = 356; +const int kButtonH = 44; +const int kInstallW = 148; +const int kInstallX = kPickPanelX + kPickPanelW - kInstallW; +const int kCancelW = 108; +const int kCancelX = kInstallX - 12 - kCancelW; + +const wchar_t* const kFontName = L"Microsoft YaHei"; + +void AddRoundRect(Gdiplus::GraphicsPath& path, int x, int y, int w, int h, int r) { + int d = r * 2; + path.AddArc(x, y, d, d, 180, 90); + path.AddArc(x + w - d, y, d, d, 270, 90); + path.AddArc(x + w - d, y + h - d, d, d, 0, 90); + path.AddArc(x, y + h - d, d, d, 90, 90); + path.CloseFigure(); +} + +void DrawButton(Gdiplus::Graphics& graphics, int x, int y, int w, int h, const wchar_t* text, + bool primary, int state) { + Gdiplus::GraphicsPath path; + AddRoundRect(path, x, y, w, h, 8); + + Gdiplus::Color top; + Gdiplus::Color bottom; + if (primary) { + if (state == 2) { + top = Gdiplus::Color(255, 30, 104, 182); + bottom = Gdiplus::Color(255, 22, 78, 142); + } else if (state == 1) { + top = Gdiplus::Color(255, 74, 182, 250); + bottom = Gdiplus::Color(255, 42, 136, 212); + } else { + top = Gdiplus::Color(255, 58, 160, 238); + bottom = Gdiplus::Color(255, 32, 114, 192); + } + } else { + if (state == 2) { + top = Gdiplus::Color(255, 54, 62, 78); + bottom = Gdiplus::Color(255, 40, 46, 60); + } else if (state == 1) { + top = Gdiplus::Color(255, 82, 92, 110); + bottom = Gdiplus::Color(255, 60, 68, 86); + } else { + top = Gdiplus::Color(255, 68, 76, 94); + bottom = Gdiplus::Color(255, 50, 56, 70); + } + } + + Gdiplus::LinearGradientBrush brush(Gdiplus::Point(x, y), Gdiplus::Point(x, y + h), top, + bottom); + graphics.FillPath(&brush, &path); + + Gdiplus::StringFormat format; + format.SetAlignment(Gdiplus::StringAlignmentCenter); + format.SetLineAlignment(Gdiplus::StringAlignmentCenter); + Gdiplus::Font font(kFontName, primary ? 15.0f : 14.0f, Gdiplus::FontStyleBold, + Gdiplus::UnitPixel); + Gdiplus::SolidBrush textBrush(Gdiplus::Color(255, 245, 248, 252)); + Gdiplus::RectF rect(static_cast(x), static_cast(y), static_cast(w), + static_cast(h)); + graphics.DrawString(text, -1, &font, rect, &format, &textBrush); +} + +Gdiplus::Image* LoadImageFromResource(HINSTANCE instance, int resourceId) { + HRSRC found = FindResourceW(instance, MAKEINTRESOURCEW(resourceId), RT_RCDATA); + if (!found) return nullptr; + HGLOBAL loaded = LoadResource(instance, found); + if (!loaded) return nullptr; + void* data = LockResource(loaded); + DWORD size = SizeofResource(instance, found); + if (!data || size == 0) return nullptr; + + IStream* stream = SHCreateMemStream(static_cast(data), size); + if (!stream) return nullptr; + Gdiplus::Image* image = Gdiplus::Image::FromStream(stream, FALSE); + stream->Release(); + return image; +} + +Gdiplus::Image* LoadImageFromFile(const std::wstring& path) { + if (path.empty() || !Utils::FileExists(path)) return nullptr; + return Gdiplus::Image::FromFile(path.c_str(), FALSE); +} + +std::wstring PercentText(int percent) { + return std::to_wstring(percent) + L"%"; +} + +// 完整包安装时的默认目录:更新器由主程序从自身目录启动,默认就装到主程序所在目录 +std::wstring DefaultInstallDir() { + std::wstring custom = UPDATER_DEFAULT_INSTALL_DIR; + if (!custom.empty()) return custom; + return Utils::GetModuleDir(); +} + +// 目录可能还不存在,向上回溯到存在的祖先再取可用空间 +bool QueryFreeSpace(const std::wstring& path, unsigned long long& freeBytes) { + std::wstring probe = path; + while (!probe.empty() && !Utils::DirExists(probe)) { + std::wstring parent = Utils::GetParentDir(probe); + if (parent.empty() || parent == probe) break; + probe = parent; + } + if (probe.empty()) return false; + + ULARGE_INTEGER available; + if (!GetDiskFreeSpaceExW(probe.c_str(), &available, nullptr, nullptr)) return false; + freeBytes = available.QuadPart; + return true; +} + +} + +struct UpdateWindow::RenderContext { + ULONG_PTR token = 0; + Gdiplus::Image* background = nullptr; + Gdiplus::Image* closeImages[3] = {nullptr, nullptr, nullptr}; +}; + +UpdateWindow::UpdateWindow() : render_(new RenderContext()) { + CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + Gdiplus::GdiplusStartupInput input; + Gdiplus::GdiplusStartup(&render_->token, &input, nullptr); +} + +UpdateWindow::~UpdateWindow() { + if (render_) { + delete render_->background; + for (int i = 0; i < 3; ++i) delete render_->closeImages[i]; + if (render_->token) Gdiplus::GdiplusShutdown(render_->token); + delete render_; + render_ = nullptr; + } + CoUninitialize(); +} + +bool UpdateWindow::Create(HINSTANCE instance, const UpdateOptions& options) { + instance_ = instance; + options_ = options; + + render_->background = LoadImageFromResource(instance, 101); + if (!render_->background) { + render_->background = LoadImageFromFile(Utils::JoinPath(Utils::GetModuleDir(), L"res\\bg.gif")); + } + render_->closeImages[0] = LoadImageFromResource(instance, 102); + render_->closeImages[1] = LoadImageFromResource(instance, 103); + render_->closeImages[2] = LoadImageFromResource(instance, 104); + + WNDCLASSW wc; + ZeroMemory(&wc, sizeof(wc)); + wc.style = CS_HREDRAW | CS_VREDRAW | CS_DROPSHADOW; + wc.lpfnWndProc = &UpdateWindow::WndProc; + wc.hInstance = instance; + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); + wc.hbrBackground = nullptr; + wc.lpszClassName = L"VerifyUpdaterWindowClass"; + RegisterClassW(&wc); + + int screenX = GetSystemMetrics(SM_CXSCREEN); + int screenY = GetSystemMetrics(SM_CYSCREEN); + int left = (screenX - kWidth) / 2; + int top = (screenY - kHeight) / 2; + + hwnd_ = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW, wc.lpszClassName, UPDATER_TITLE, + WS_POPUP, left, top, kWidth, kHeight, nullptr, nullptr, instance, + this); + if (!hwnd_) return false; + + HRGN region = CreateRoundRectRgn(0, 0, kWidth + 1, kHeight + 1, 12, 12); + SetWindowRgn(hwnd_, region, FALSE); + + // 完整包安装且没有指定目录时,先让用户选安装目录 + // 必须在首次显示之前定好阶段,否则首帧会画成更新进度面板 + bool pickDir = options.fullMode && options.targetDir.empty(); + if (pickDir) { + phase_ = Phase::PickDir; + installDir_ = DefaultInstallDir(); + status_ = L"请选择安装目录"; + } else { + phase_ = Phase::Updating; + status_ = options.fullMode ? L"正在准备完整包更新..." : L"正在检查版本更新..."; + } + + ShowWindow(hwnd_, SW_SHOW); + ::UpdateWindow(hwnd_); + + if (!pickDir) StartWorker(options); + return true; +} + +void UpdateWindow::StartWorker(const UpdateOptions& options) { + HWND hwnd = hwnd_; + worker_.Start(options, + [this, hwnd](int percent, const std::wstring& text) { + UiState* state = new UiState(); + state->percent = percent; + state->status = text; + PostMessageW(hwnd, kWmState, 0, reinterpret_cast(state)); + }, + [this, hwnd](bool ok, const std::wstring& text) { + UiState* state = new UiState(); + state->percent = ok ? 100 : percent_; + state->status = text; + state->finished = true; + state->success = ok; + PostMessageW(hwnd, kWmState, 0, reinterpret_cast(state)); + }); +} + +bool UpdateWindow::BrowseFolder() { + IFileDialog* dialog = nullptr; + HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&dialog)); + if (FAILED(hr)) return false; + + DWORD options = 0; + if (SUCCEEDED(dialog->GetOptions(&options))) { + dialog->SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); + } + dialog->SetTitle(L"选择安装目录"); + + if (!installDir_.empty() && Utils::DirExists(installDir_)) { + IShellItem* folder = nullptr; + if (SUCCEEDED(SHCreateItemFromParsingName(installDir_.c_str(), nullptr, + IID_PPV_ARGS(&folder)))) { + dialog->SetFolder(folder); + folder->Release(); + } + } + + bool changed = false; + if (SUCCEEDED(dialog->Show(hwnd_))) { + IShellItem* item = nullptr; + if (SUCCEEDED(dialog->GetResult(&item))) { + wchar_t* path = nullptr; + if (SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH, &path)) && path) { + installDir_ = path; + changed = true; + CoTaskMemFree(path); + } + item->Release(); + } + } + dialog->Release(); + return changed; +} + +void UpdateWindow::StartUpdate() { + if (started_ || installDir_.empty()) return; + started_ = true; + + phase_ = Phase::Updating; + closeState_ = browseState_ = installState_ = cancelState_ = 0; + pressed_ = 0; + + UpdateOptions options = options_; + options.targetDir = installDir_; + status_ = L"正在准备安装..."; + Invalidate(); + StartWorker(options); +} + +int UpdateWindow::MessageLoop() { + MSG msg; + while (GetMessageW(&msg, nullptr, 0, 0) > 0) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + return static_cast(msg.wParam); +} + +void UpdateWindow::Invalidate() { + if (hwnd_) InvalidateRect(hwnd_, nullptr, FALSE); +} + +bool UpdateWindow::HitCloseButton(int x, int y) const { + int left = kWidth - kCloseMarginX - kCloseSize; + return x >= left && x <= left + kCloseSize && y >= kCloseMarginY && + y <= kCloseMarginY + kCloseSize; +} + +bool UpdateWindow::HitBrowseButton(int x, int y) const { + return phase_ == Phase::PickDir && x >= kBrowseX && x <= kBrowseX + kBrowseW && y >= kPathY && + y <= kPathY + kPathH; +} + +bool UpdateWindow::HitInstallButton(int x, int y) const { + return phase_ == Phase::PickDir && x >= kInstallX && x <= kInstallX + kInstallW && + y >= kButtonY && y <= kButtonY + kButtonH; +} + +bool UpdateWindow::HitCancelButton(int x, int y) const { + return phase_ == Phase::PickDir && x >= kCancelX && x <= kCancelX + kCancelW && + y >= kButtonY && y <= kButtonY + kButtonH; +} + +bool UpdateWindow::HitAnyButton(int x, int y) const { + return HitCloseButton(x, y) || HitBrowseButton(x, y) || HitInstallButton(x, y) || + HitCancelButton(x, y); +} + +void UpdateWindow::UpdateHover(int x, int y) { + int close = HitCloseButton(x, y) ? (pressed_ == 1 ? 2 : 1) : 0; + int browse = HitBrowseButton(x, y) ? (pressed_ == 2 ? 2 : 1) : 0; + int install = HitInstallButton(x, y) ? (pressed_ == 3 ? 2 : 1) : 0; + int cancel = HitCancelButton(x, y) ? (pressed_ == 4 ? 2 : 1) : 0; + + if (close != closeState_ || browse != browseState_ || install != installState_ || + cancel != cancelState_) { + closeState_ = close; + browseState_ = browse; + installState_ = install; + cancelState_ = cancel; + Invalidate(); + } +} + +void UpdateWindow::RequestClose() { + if (closing_) return; + closing_ = true; + if (phase_ == Phase::Updating && !finished_) { + status_ = L"正在取消更新..."; + Invalidate(); + } + worker_.Cancel(); + DestroyWindow(hwnd_); +} + +void UpdateWindow::OnState(const UiState& state) { + if (closing_) return; + percent_ = std::max(0, std::min(100, state.percent)); + status_ = state.status; + if (state.finished) { + finished_ = true; + success_ = state.success; + if (success_) SetTimer(hwnd_, kTimerClose, 1500, nullptr); + } + Invalidate(); +} + +void UpdateWindow::DrawPickPanel(Gdiplus::Graphics& graphics) { + Gdiplus::GraphicsPath panelPath; + AddRoundRect(panelPath, kPickPanelX, kPickPanelY, kPickPanelW, kPickPanelH, 12); + Gdiplus::SolidBrush panelBrush(Gdiplus::Color(165, 12, 16, 24)); + graphics.FillPath(&panelBrush, &panelPath); + + Gdiplus::StringFormat nearFormat; + nearFormat.SetAlignment(Gdiplus::StringAlignmentNear); + nearFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter); + nearFormat.SetTrimming(Gdiplus::StringTrimmingEllipsisWord); + + Gdiplus::SolidBrush textBrush(Gdiplus::Color(255, 240, 244, 250)); + Gdiplus::SolidBrush dimBrush(Gdiplus::Color(200, 176, 186, 202)); + + Gdiplus::Font titleFont(kFontName, 18.0f, Gdiplus::FontStyleBold, Gdiplus::UnitPixel); + Gdiplus::RectF titleRect(static_cast(kPickTextX), static_cast(kPickTitleY), + static_cast(kPickPanelW - 48), 28.0f); + std::wstring appName = UPDATER_APP_NAME; + std::wstring titleText = + appName.empty() ? L"选择安装目录" : (L"选择 " + appName + L" 的安装目录"); + graphics.DrawString(titleText.c_str(), -1, &titleFont, titleRect, &nearFormat, &textBrush); + + Gdiplus::Font hintFont(kFontName, 13.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel); + Gdiplus::RectF hintRect(static_cast(kPickTextX), static_cast(kPickHintY), + static_cast(kPickPanelW - 48), 22.0f); + graphics.DrawString(L"请选择程序的安装位置,目录下的同名文件会被覆盖", -1, &hintFont, hintRect, + &nearFormat, &dimBrush); + + // 路径显示框 + Gdiplus::GraphicsPath boxPath; + AddRoundRect(boxPath, kPathX, kPathY, kPathW, kPathH, 8); + Gdiplus::SolidBrush boxBrush(Gdiplus::Color(130, 8, 10, 16)); + graphics.FillPath(&boxBrush, &boxPath); + Gdiplus::Pen boxPen(Gdiplus::Color(190, 98, 110, 130), 1.0f); + graphics.DrawPath(&boxPen, &boxPath); + + Gdiplus::StringFormat pathFormat; + pathFormat.SetAlignment(Gdiplus::StringAlignmentNear); + pathFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter); + pathFormat.SetTrimming(Gdiplus::StringTrimmingEllipsisPath); + Gdiplus::Font pathFont(kFontName, 14.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel); + Gdiplus::RectF pathRect(static_cast(kPathX + 12), static_cast(kPathY), + static_cast(kPathW - 24), static_cast(kPathH)); + graphics.DrawString(installDir_.c_str(), -1, &pathFont, pathRect, &pathFormat, &textBrush); + + DrawButton(graphics, kBrowseX, kPathY, kBrowseW, kPathH, L"浏览...", false, browseState_); + + // 可用空间与目录状态 + std::wstring spaceText; + unsigned long long freeBytes = 0; + if (QueryFreeSpace(installDir_, freeBytes)) { + spaceText = L"可用空间 " + Utils::FormatSize(freeBytes); + } + if (Utils::DirExists(installDir_)) { + if (!spaceText.empty()) spaceText += L" "; + spaceText += L"目录已存在,将覆盖其中的同名文件"; + } + if (!spaceText.empty()) { + Gdiplus::RectF spaceRect(static_cast(kPickTextX), static_cast(kSpaceY), + static_cast(kPickPanelW - 48), 22.0f); + graphics.DrawString(spaceText.c_str(), -1, &hintFont, spaceRect, &nearFormat, &dimBrush); + } + + DrawButton(graphics, kCancelX, kButtonY, kCancelW, kButtonH, L"取消", false, cancelState_); + DrawButton(graphics, kInstallX, kButtonY, kInstallW, kButtonH, L"开始安装", true, + installState_); +} + +void UpdateWindow::DrawProgressPanel(Gdiplus::Graphics& graphics) { + Gdiplus::GraphicsPath panelPath; + AddRoundRect(panelPath, kPanelX, kPanelY, kPanelW, kPanelH, 12); + Gdiplus::SolidBrush panelBrush(Gdiplus::Color(150, 12, 16, 24)); + graphics.FillPath(&panelBrush, &panelPath); + + Gdiplus::SolidBrush textBrush(Gdiplus::Color(255, 240, 244, 250)); + Gdiplus::SolidBrush dimBrush(Gdiplus::Color(200, 176, 186, 202)); + + Gdiplus::StringFormat nearFormat; + nearFormat.SetAlignment(Gdiplus::StringAlignmentNear); + nearFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter); + nearFormat.SetTrimming(Gdiplus::StringTrimmingEllipsisWord); + + Gdiplus::Font titleFont(kFontName, 18.0f, Gdiplus::FontStyleBold, Gdiplus::UnitPixel); + Gdiplus::RectF titleRect(static_cast(kTextX), static_cast(kTitleY), + static_cast(kPanelW - 48), 28.0f); + graphics.DrawString(UPDATER_TITLE, -1, &titleFont, titleRect, &nearFormat, &textBrush); + + Gdiplus::Font statusFont(kFontName, 14.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel); + Gdiplus::RectF statusRect(static_cast(kTextX), static_cast(kStatusY), + static_cast(kBarW - 90), 24.0f); + graphics.DrawString(status_.c_str(), -1, &statusFont, statusRect, &nearFormat, &dimBrush); + + Gdiplus::StringFormat farFormat; + farFormat.SetAlignment(Gdiplus::StringAlignmentFar); + farFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter); + Gdiplus::Font percentFont(kFontName, 15.0f, Gdiplus::FontStyleBold, Gdiplus::UnitPixel); + Gdiplus::RectF percentRect(static_cast(kBarX + kBarW - 80), + static_cast(kStatusY), 80.0f, 24.0f); + graphics.DrawString(PercentText(percent_).c_str(), -1, &percentFont, percentRect, + &farFormat, &textBrush); + + Gdiplus::GraphicsPath trackPath; + AddRoundRect(trackPath, kBarX, kBarY, kBarW, kBarH, kBarH / 2); + Gdiplus::SolidBrush trackBrush(Gdiplus::Color(200, 48, 54, 68)); + graphics.FillPath(&trackBrush, &trackPath); + + int fillW = static_cast(static_cast(kBarW) * percent_ / 100.0); + if (fillW > kBarH) { + Gdiplus::GraphicsPath fillPath; + AddRoundRect(fillPath, kBarX, kBarY, fillW, kBarH, kBarH / 2); + + bool failed = finished_ && !success_; + Gdiplus::Color c1 = failed ? Gdiplus::Color(255, 226, 92, 92) + : Gdiplus::Color(255, 88, 196, 248); + Gdiplus::Color c2 = failed ? Gdiplus::Color(255, 198, 58, 72) + : Gdiplus::Color(255, 46, 140, 226); + Gdiplus::LinearGradientBrush fillBrush( + Gdiplus::Point(kBarX, kBarY), Gdiplus::Point(kBarX + fillW, kBarY + kBarH), c1, c2); + graphics.FillPath(&fillBrush, &fillPath); + } +} + +void UpdateWindow::OnPaint() { + PAINTSTRUCT ps; + HDC hdc = BeginPaint(hwnd_, &ps); + + RECT rc; + GetClientRect(hwnd_, &rc); + int width = rc.right - rc.left; + int height = rc.bottom - rc.top; + + HDC memDc = CreateCompatibleDC(hdc); + HBITMAP memBmp = CreateCompatibleBitmap(hdc, width, height); + HGDIOBJ old = SelectObject(memDc, memBmp); + + { + Gdiplus::Graphics graphics(memDc); + graphics.SetSmoothingMode(Gdiplus::SmoothingModeHighQuality); + graphics.SetTextRenderingHint(Gdiplus::TextRenderingHintAntiAliasGridFit); + graphics.SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic); + + if (render_->background && render_->background->GetLastStatus() == Gdiplus::Ok) { + graphics.DrawImage(render_->background, 0, 0, width, height); + } else { + Gdiplus::LinearGradientBrush bgBrush( + Gdiplus::Point(0, 0), Gdiplus::Point(0, height), + Gdiplus::Color(255, 32, 38, 52), Gdiplus::Color(255, 18, 22, 32)); + graphics.FillRectangle(&bgBrush, 0, 0, width, height); + } + + if (phase_ == Phase::PickDir) { + DrawPickPanel(graphics); + } else { + DrawProgressPanel(graphics); + } + + int closeLeft = kWidth - kCloseMarginX - kCloseSize; + Gdiplus::Image* closeImage = render_->closeImages[closeState_]; + if (closeImage && closeImage->GetLastStatus() == Gdiplus::Ok) { + graphics.DrawImage(closeImage, closeLeft, kCloseMarginY, kCloseSize, kCloseSize); + } else { + Gdiplus::Color penColor(220, 235, 240, 248); + Gdiplus::Pen pen(penColor, 2.0f); + graphics.DrawLine(&pen, closeLeft + 8, kCloseMarginY + 8, closeLeft + kCloseSize - 8, + kCloseMarginY + kCloseSize - 8); + graphics.DrawLine(&pen, closeLeft + kCloseSize - 8, kCloseMarginY + 8, closeLeft + 8, + kCloseMarginY + kCloseSize - 8); + } + } + + BitBlt(hdc, 0, 0, width, height, memDc, 0, 0, SRCCOPY); + SelectObject(memDc, old); + DeleteObject(memBmp); + DeleteDC(memDc); + EndPaint(hwnd_, &ps); +} + +LRESULT UpdateWindow::HandleMessage(UINT msg, WPARAM wParam, LPARAM lParam) { + switch (msg) { + case WM_PAINT: + OnPaint(); + return 0; + + case WM_ERASEBKGND: + return 1; + + case kWmState: { + UiState* state = reinterpret_cast(lParam); + if (state) { + OnState(*state); + delete state; + } + return 0; + } + + case WM_NCHITTEST: { + POINT pt; + pt.x = GET_X_LPARAM(lParam); + pt.y = GET_Y_LPARAM(lParam); + ScreenToClient(hwnd_, &pt); + // 按钮区域交给客户区消息处理,其余部分允许拖动窗口 + if (HitAnyButton(pt.x, pt.y)) return HTCLIENT; + return HTCAPTION; + } + + case WM_MOUSEMOVE: { + int x = GET_X_LPARAM(lParam); + int y = GET_Y_LPARAM(lParam); + UpdateHover(x, y); + if (!tracking_) { + TRACKMOUSEEVENT tme; + ZeroMemory(&tme, sizeof(tme)); + tme.cbSize = sizeof(tme); + tme.dwFlags = TME_LEAVE; + tme.hwndTrack = hwnd_; + TrackMouseEvent(&tme); + tracking_ = true; + } + return 0; + } + + case WM_MOUSELEAVE: + tracking_ = false; + pressed_ = 0; + if (closeState_ != 0 || browseState_ != 0 || installState_ != 0 || cancelState_ != 0) { + closeState_ = browseState_ = installState_ = cancelState_ = 0; + Invalidate(); + } + return 0; + + case WM_LBUTTONDOWN: { + int x = GET_X_LPARAM(lParam); + int y = GET_Y_LPARAM(lParam); + if (HitCloseButton(x, y)) pressed_ = 1; + else if (HitBrowseButton(x, y)) pressed_ = 2; + else if (HitInstallButton(x, y)) pressed_ = 3; + else if (HitCancelButton(x, y)) pressed_ = 4; + else pressed_ = 0; + UpdateHover(x, y); + return 0; + } + + case WM_LBUTTONUP: { + int x = GET_X_LPARAM(lParam); + int y = GET_Y_LPARAM(lParam); + int hit = pressed_; + pressed_ = 0; + UpdateHover(x, y); + + if (hit == 1 && HitCloseButton(x, y)) { + RequestClose(); + } else if (hit == 2 && HitBrowseButton(x, y)) { + if (BrowseFolder()) Invalidate(); + } else if (hit == 3 && HitInstallButton(x, y)) { + StartUpdate(); + } else if (hit == 4 && HitCancelButton(x, y)) { + RequestClose(); + } + return 0; + } + + case WM_TIMER: + if (wParam == kTimerClose) { + KillTimer(hwnd_, kTimerClose); + closing_ = true; + DestroyWindow(hwnd_); + } + return 0; + + case WM_KEYDOWN: + if (wParam == VK_ESCAPE) RequestClose(); + if (phase_ == Phase::PickDir && wParam == VK_RETURN) StartUpdate(); + return 0; + + case WM_CLOSE: + RequestClose(); + return 0; + + case WM_DESTROY: + PostQuitMessage(0); + return 0; + + default: + break; + } + return DefWindowProcW(hwnd_, msg, wParam, lParam); +} + +LRESULT CALLBACK UpdateWindow::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { + UpdateWindow* self = nullptr; + if (msg == WM_NCCREATE) { + CREATESTRUCTW* cs = reinterpret_cast(lParam); + self = static_cast(cs->lpCreateParams); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast(self)); + if (self) self->hwnd_ = hwnd; + } else { + self = reinterpret_cast(GetWindowLongPtrW(hwnd, GWLP_USERDATA)); + } + if (self) return self->HandleMessage(msg, wParam, lParam); + return DefWindowProcW(hwnd, msg, wParam, lParam); +} + +} diff --git a/Update/UpdateWindow.h b/Update/UpdateWindow.h new file mode 100644 index 0000000..d6d8376 --- /dev/null +++ b/Update/UpdateWindow.h @@ -0,0 +1,86 @@ +#pragma once + +#include + +#include + +#include "Worker.h" + +namespace Gdiplus { +class Graphics; +} + +namespace updater { + +// 工作线程 -> UI 线程的状态投递结构,由窗口负责释放 +struct UiState { + int percent = 0; + std::wstring status; + bool finished = false; + bool success = false; +}; + +class UpdateWindow { +public: + UpdateWindow(); + ~UpdateWindow(); + + UpdateWindow(const UpdateWindow&) = delete; + UpdateWindow& operator=(const UpdateWindow&) = delete; + + bool Create(HINSTANCE instance, const UpdateOptions& options); + int MessageLoop(); + +private: + // 完整包模式下先让用户选安装目录,之后再切到更新进度 + enum class Phase { PickDir, Updating }; + + static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); + LRESULT HandleMessage(UINT msg, WPARAM wParam, LPARAM lParam); + + void OnPaint(); + void DrawPickPanel(Gdiplus::Graphics& graphics); + void DrawProgressPanel(Gdiplus::Graphics& graphics); + void OnState(const UiState& state); + void RequestClose(); + void Invalidate(); + + // 目录选择阶段 + bool BrowseFolder(); + void StartUpdate(); + void StartWorker(const UpdateOptions& options); + + bool HitCloseButton(int x, int y) const; + bool HitBrowseButton(int x, int y) const; + bool HitInstallButton(int x, int y) const; + bool HitCancelButton(int x, int y) const; + bool HitAnyButton(int x, int y) const; + void UpdateHover(int x, int y); + + HWND hwnd_ = nullptr; + HINSTANCE instance_ = nullptr; + Worker worker_; + + Phase phase_ = Phase::Updating; + UpdateOptions options_; + std::wstring installDir_; + bool started_ = false; + + int percent_ = 0; + std::wstring status_; + bool finished_ = false; + bool success_ = false; + bool closing_ = false; + + int closeState_ = 0; // 0 普通 1 悬停 2 按下 + int browseState_ = 0; + int installState_ = 0; + int cancelState_ = 0; + int pressed_ = 0; // 0 无 1 关闭 2 浏览 3 安装 4 取消 + bool tracking_ = false; + + struct RenderContext; + RenderContext* render_ = nullptr; +}; + +} diff --git a/Update/Utils.cpp b/Update/Utils.cpp index c77bb2a..77c79e2 100644 --- a/Update/Utils.cpp +++ b/Update/Utils.cpp @@ -1,41 +1,348 @@ #include "Utils.h" -Utils::Utils() -{ +#include +#include + +#include +#include +#include +#include + +#pragma comment(lib, "bcrypt.lib") +#pragma comment(lib, "shell32.lib") +#pragma comment(lib, "kernel32.lib") + +namespace updater { + +std::wstring Utils::Utf8ToWide(const std::string& s) { + if (s.empty()) return std::wstring(); + int len = MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast(s.size()), nullptr, 0); + if (len <= 0) return std::wstring(); + std::wstring out(static_cast(len), L'\0'); + MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast(s.size()), &out[0], len); + return out; } -Utils::~Utils() -{ +std::string Utils::WideToUtf8(const std::wstring& s) { + if (s.empty()) return std::string(); + int len = WideCharToMultiByte(CP_UTF8, 0, s.data(), static_cast(s.size()), + nullptr, 0, nullptr, nullptr); + if (len <= 0) return std::string(); + std::string out(static_cast(len), '\0'); + WideCharToMultiByte(CP_UTF8, 0, s.data(), static_cast(s.size()), &out[0], len, + nullptr, nullptr); + return out; } -Utils &Utils::instance() -{ - static Utils m_instance; - return m_instance; -} -// 不要忘记在使用完wchar_t*后delete[]释放内存 -WCHAR* Utils::A2W(const CHAR* ansi) -{ - // 第一次调用返回转换后的字符串长度,用于确认为wchar_t*开辟多大的内存空间 - int size = MultiByteToWideChar(CP_OEMCP, 0, ansi, strlen(ansi) + 1, NULL, 0); - WCHAR* buffer = new WCHAR[size]; - // 第二次调用将单字节字符串转换成双字节字符串 - MultiByteToWideChar(CP_OEMCP, 0, ansi, strlen(ansi) + 1, buffer, size); - return buffer; +std::wstring Utils::CodePageToWide(const std::string& s, UINT codePage) { + if (s.empty()) return std::wstring(); + int len = MultiByteToWideChar(codePage, 0, s.data(), static_cast(s.size()), nullptr, 0); + if (len <= 0) return std::wstring(); + std::wstring out(static_cast(len), L'\0'); + MultiByteToWideChar(codePage, 0, s.data(), static_cast(s.size()), &out[0], len); + return out; } -// 不要忘记使用完char*后delete[]释放内存 -CHAR* Utils::W2A(const WCHAR* unicode) -{ - //第一次调用确认转换后单字节字符串的长度,用于开辟空间 - int length = WideCharToMultiByte(CP_OEMCP, 0, unicode, wcslen(unicode), NULL, 0, NULL, NULL); - char* buffer = new char[length + 1]; - //第二次调用将双字节字符串转换成单字节字符串 - WideCharToMultiByte(CP_OEMCP, 0, unicode, wcslen(unicode), buffer, length, NULL, NULL); - buffer[length] = '\0'; - return buffer; - - //如果想要转换成string,直接赋值即可 - //string pKey = pCStrKey; +bool Utils::IsValidUtf8(const std::string& s) { + size_t i = 0; + while (i < s.size()) { + unsigned char c = static_cast(s[i]); + size_t extra; + unsigned int cp; + if (c < 0x80) { i++; continue; } + if ((c & 0xE0) == 0xC0) { extra = 1; cp = c & 0x1F; } + else if ((c & 0xF0) == 0xE0) { extra = 2; cp = c & 0x0F; } + else if ((c & 0xF8) == 0xF0) { extra = 3; cp = c & 0x07; } + else return false; + if (i + extra >= s.size()) return false; + for (size_t k = 1; k <= extra; ++k) { + unsigned char cc = static_cast(s[i + k]); + if ((cc & 0xC0) != 0x80) return false; + cp = (cp << 6) | (cc & 0x3F); + } + if (cp > 0x10FFFF) return false; + if (cp >= 0xD800 && cp <= 0xDFFF) return false; + if (extra == 1 && cp < 0x80) return false; + if (extra == 2 && cp < 0x800) return false; + if (extra == 3 && cp < 0x10000) return false; + i += extra + 1; + } + return true; } +std::wstring Utils::DecodeEntryName(const std::string& raw) { + if (IsValidUtf8(raw)) return Utf8ToWide(raw); + return CodePageToWide(raw, 936); +} + +std::wstring Utils::GetModuleDir() { + wchar_t buf[MAX_PATH] = {0}; + GetModuleFileNameW(nullptr, buf, MAX_PATH); + std::wstring full(buf); + size_t pos = full.find_last_of(L"\\/"); + if (pos == std::wstring::npos) return L"."; + return full.substr(0, pos); +} + +std::wstring Utils::GetTempDir() { + wchar_t buf[MAX_PATH] = {0}; + if (GetTempPathW(MAX_PATH, buf) == 0) return L"."; + std::wstring path(buf); + while (!path.empty() && (path.back() == L'\\' || path.back() == L'/')) path.pop_back(); + return path; +} + +std::wstring Utils::JoinPath(const std::wstring& dir, const std::wstring& rel) { + if (dir.empty()) return rel; + if (rel.empty()) return dir; + wchar_t last = dir.back(); + if (last == L'\\' || last == L'/') return dir + rel; + return dir + L"\\" + rel; +} + +std::wstring Utils::GetParentDir(const std::wstring& path) { + size_t pos = path.find_last_of(L"\\/"); + if (pos == std::wstring::npos) return std::wstring(); + return path.substr(0, pos); +} + +std::wstring Utils::Trim(const std::wstring& s) { + size_t b = 0, e = s.size(); + while (b < e && (s[b] == L' ' || s[b] == L'\t' || s[b] == L'\r' || s[b] == L'\n')) ++b; + while (e > b && (s[e - 1] == L' ' || s[e - 1] == L'\t' || s[e - 1] == L'\r' || s[e - 1] == L'\n')) --e; + return s.substr(b, e - b); +} + +std::wstring Utils::NormalizeSlashes(std::wstring path) { + std::replace(path.begin(), path.end(), L'/', L'\\'); + return path; +} + +bool Utils::CreateDirRecursive(const std::wstring& dir) { + if (dir.empty()) return false; + if (DirExists(dir)) return true; + std::wstring parent = GetParentDir(dir); + if (!parent.empty() && parent != dir) CreateDirRecursive(parent); + return CreateDirectoryW(dir.c_str(), nullptr) != FALSE || GetLastError() == ERROR_ALREADY_EXISTS; +} + +bool Utils::FileExists(const std::wstring& path) { + DWORD attr = GetFileAttributesW(path.c_str()); + return attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY); +} + +bool Utils::DirExists(const std::wstring& path) { + DWORD attr = GetFileAttributesW(path.c_str()); + return attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; +} + +bool Utils::DeleteFileForce(const std::wstring& path) { + SetFileAttributesW(path.c_str(), FILE_ATTRIBUTE_NORMAL); + return DeleteFileW(path.c_str()) != FALSE; +} + +std::wstring Utils::MakeUniqueTempFile(const std::wstring& dir, const std::wstring& prefix) { + for (int i = 0; i < 100; ++i) { + wchar_t name[MAX_PATH]; + swprintf_s(name, MAX_PATH, L"%s_%lu_%d.tmp", prefix.c_str(), GetCurrentProcessId(), i); + std::wstring full = JoinPath(dir, name); + HANDLE h = CreateFileW(full.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h != INVALID_HANDLE_VALUE) { + CloseHandle(h); + DeleteFileW(full.c_str()); + return full; + } + if (GetLastError() != ERROR_FILE_EXISTS && GetLastError() != ERROR_ALREADY_EXISTS) break; + } + wchar_t name[MAX_PATH]; + swprintf_s(name, MAX_PATH, L"%s_%lu.tmp", prefix.c_str(), GetTickCount()); + return JoinPath(dir, name); +} + +std::wstring Utils::FormatSize(unsigned long long bytes) { + const wchar_t* units[] = {L"B", L"KB", L"MB", L"GB"}; + double value = static_cast(bytes); + int unit = 0; + while (value >= 1024.0 && unit < 3) { + value /= 1024.0; + ++unit; + } + wchar_t buf[64]; + if (unit == 0) swprintf_s(buf, 64, L"%llu %s", bytes, units[unit]); + else swprintf_s(buf, 64, L"%.1f %s", value, units[unit]); + return std::wstring(buf); +} + +std::wstring Utils::FormatSpeed(unsigned long long bytesPerSec) { + return FormatSize(bytesPerSec) + L"/s"; +} + +std::string Utils::Sha256Hex(const void* data, size_t size) { + std::string result; + BCRYPT_ALG_HANDLE hAlg = nullptr; + if (BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0) return result; + BCRYPT_HASH_HANDLE hHash = nullptr; + if (BCryptCreateHash(hAlg, &hHash, nullptr, 0, nullptr, 0, 0) < 0) { + BCryptCloseAlgorithmProvider(hAlg, 0); + return result; + } + if (data && size) BCryptHashData(hHash, const_cast(static_cast(data)), + static_cast(size), 0); + BYTE hash[32] = {0}; + if (BCryptFinishHash(hHash, hash, sizeof(hash), 0) >= 0) { + static const char* hex = "0123456789abcdef"; + for (int i = 0; i < 32; ++i) { + result += hex[(hash[i] >> 4) & 0xF]; + result += hex[hash[i] & 0xF]; + } + } + BCryptDestroyHash(hHash); + BCryptCloseAlgorithmProvider(hAlg, 0); + return result; +} + +std::string Utils::Sha256HexFile(const std::wstring& path) { + HANDLE hFile = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (hFile == INVALID_HANDLE_VALUE) return std::string(); + + BCRYPT_ALG_HANDLE hAlg = nullptr; + if (BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0) { + CloseHandle(hFile); + return std::string(); + } + BCRYPT_HASH_HANDLE hHash = nullptr; + if (BCryptCreateHash(hAlg, &hHash, nullptr, 0, nullptr, 0, 0) < 0) { + BCryptCloseAlgorithmProvider(hAlg, 0); + CloseHandle(hFile); + return std::string(); + } + + const DWORD bufSize = 64 * 1024; + std::vector buffer(bufSize); + DWORD read = 0; + while (ReadFile(hFile, buffer.data(), bufSize, &read, nullptr) && read > 0) { + BCryptHashData(hHash, buffer.data(), read, 0); + } + CloseHandle(hFile); + + BYTE hash[32] = {0}; + std::string result; + if (BCryptFinishHash(hHash, hash, sizeof(hash), 0) >= 0) { + static const char* hex = "0123456789abcdef"; + for (int i = 0; i < 32; ++i) { + result += hex[(hash[i] >> 4) & 0xF]; + result += hex[hash[i] & 0xF]; + } + } + BCryptDestroyHash(hHash); + BCryptCloseAlgorithmProvider(hAlg, 0); + return result; +} + +std::string Utils::ToLowerAscii(const std::string& s) { + std::string out = s; + std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) { + return static_cast((c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c); + }); + return out; +} + +std::wstring Utils::UrlEncode(const std::wstring& s) { + std::string utf8 = WideToUtf8(s); + static const char* hex = "0123456789ABCDEF"; + std::string out; + for (unsigned char c : utf8) { + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '-' || c == '_' || c == '.' || c == '~') { + out += static_cast(c); + } else { + out += '%'; + out += hex[(c >> 4) & 0xF]; + out += hex[c & 0xF]; + } + } + return Utf8ToWide(out); +} + +bool Utils::IsAbsoluteUrl(const std::wstring& url) { + if (url.size() >= 7 && _wcsnicmp(url.c_str(), L"http://", 7) == 0) return true; + if (url.size() >= 8 && _wcsnicmp(url.c_str(), L"https://", 8) == 0) return true; + return false; +} + +bool Utils::LaunchProcess(const std::wstring& exe, const std::wstring& args, + const std::wstring& workDir) { + if (exe.empty()) return false; + + // 用 CreateProcess 而不是 ShellExecute:后者在目标不存在时会弹系统错误对话框, + // 更新器会一直卡在等用户点确定的状态,退出码也就回不来了 + std::wstring cmd = L"\"" + exe + L"\""; + if (!args.empty()) cmd += L" " + args; + + std::vector cmdBuf(cmd.begin(), cmd.end()); + cmdBuf.push_back(L'\0'); + + STARTUPINFOW si; + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + si.dwFlags = STARTF_USESHOWWINDOW; + si.wShowWindow = SW_SHOWNORMAL; + + PROCESS_INFORMATION pi; + ZeroMemory(&pi, sizeof(pi)); + + BOOL ok = CreateProcessW(nullptr, cmdBuf.data(), nullptr, nullptr, FALSE, 0, nullptr, + workDir.empty() ? nullptr : workDir.c_str(), &si, &pi); + if (!ok) return false; + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return true; +} + +bool Utils::WaitForProcessExit(const std::wstring& processName, int timeoutSec) { + DWORD ticks = GetTickCount(); + DWORD limit = static_cast(timeoutSec) * 1000; + while (GetTickCount() - ticks < limit) { + bool found = false; + HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (snap != INVALID_HANDLE_VALUE) { + PROCESSENTRY32W pe = {0}; + pe.dwSize = sizeof(pe); + if (Process32FirstW(snap, &pe)) { + do { + if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0) { found = true; break; } + } while (Process32NextW(snap, &pe)); + } + CloseHandle(snap); + } + if (!found) return true; + Sleep(300); + } + return false; +} + +bool Utils::ReplaceInUse(const std::wstring& srcTmp, const std::wstring& target) { + if (MoveFileExW(srcTmp.c_str(), target.c_str(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE) { + return true; + } + std::wstring old = target + L".old"; + MoveFileExW(target.c_str(), old.c_str(), MOVEFILE_REPLACE_EXISTING); + if (MoveFileExW(srcTmp.c_str(), target.c_str(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE) { + // 正在运行的映像无法直接删除(例如更新器替换自身),交给系统重启时清理 + if (DeleteFileW(old.c_str()) == FALSE) { + MoveFileExW(old.c_str(), nullptr, MOVEFILE_DELAY_UNTIL_REBOOT); + } + return true; + } + if (MoveFileExW(srcTmp.c_str(), target.c_str(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_DELAY_UNTIL_REBOOT) != FALSE) { + return false; + } + return false; +} + +} diff --git a/Update/Utils.h b/Update/Utils.h index 01e87a7..4eb1dd6 100644 --- a/Update/Utils.h +++ b/Update/Utils.h @@ -1,14 +1,49 @@ #pragma once + #include + #include -class Utils -{ -private: - Utils(); - ~Utils(); +#include + +namespace updater { + +class Utils { public: - static Utils& instance(); -public: - WCHAR* A2W(const CHAR* ansi); - CHAR* W2A(const WCHAR* unicode); -}; \ No newline at end of file + static std::wstring Utf8ToWide(const std::string& s); + static std::string WideToUtf8(const std::wstring& s); + static std::wstring CodePageToWide(const std::string& s, UINT codePage); + + static bool IsValidUtf8(const std::string& s); + static std::wstring DecodeEntryName(const std::string& raw); + + static std::wstring GetModuleDir(); + static std::wstring GetTempDir(); + static std::wstring JoinPath(const std::wstring& dir, const std::wstring& rel); + static std::wstring GetParentDir(const std::wstring& path); + static std::wstring Trim(const std::wstring& s); + static std::wstring NormalizeSlashes(std::wstring path); + + static bool CreateDirRecursive(const std::wstring& dir); + static bool FileExists(const std::wstring& path); + static bool DirExists(const std::wstring& path); + static bool DeleteFileForce(const std::wstring& path); + static std::wstring MakeUniqueTempFile(const std::wstring& dir, const std::wstring& prefix); + + static std::wstring FormatSize(unsigned long long bytes); + static std::wstring FormatSpeed(unsigned long long bytesPerSec); + + static std::string Sha256Hex(const void* data, size_t size); + static std::string Sha256HexFile(const std::wstring& path); + static std::string ToLowerAscii(const std::string& s); + + static std::wstring UrlEncode(const std::wstring& s); + static bool IsAbsoluteUrl(const std::wstring& url); + + static bool LaunchProcess(const std::wstring& exe, + const std::wstring& args, + const std::wstring& workDir); + static bool WaitForProcessExit(const std::wstring& processName, int timeoutSec); + static bool ReplaceInUse(const std::wstring& srcTmp, const std::wstring& target); +}; + +} diff --git a/Update/Worker.cpp b/Update/Worker.cpp index 7d0b9f1..e8f5622 100644 --- a/Update/Worker.cpp +++ b/Update/Worker.cpp @@ -1,435 +1,352 @@ #include "Worker.h" -#include -#include -#include -#include -#include -#include -#include "FileInfo.h" + +#include "Api.h" +#include "Config.h" +#include "Http.h" +#include "Unzip.h" #include "Utils.h" -#include +#include -Worker::Worker() -{ - qDebug() << "线程初始化"; - // 初始化文件总大小 - m_downloadSize=0; - m_filesSize = 0; - // 保存XML文件下载地址 - m_url = "http://88.151.33.134:5666/Crown"; +#include - connect(this,&Worker::signalCheckUpdate,this,&Worker::slotCheckUpdate); +#include +#include + +#pragma comment(lib, "shlwapi.lib") + +namespace updater { + +namespace { + +void CollectFiles(const std::wstring& dir, const std::wstring& relBase, + std::vector& files, std::vector& dirs) { + WIN32_FIND_DATAW data; + std::wstring pattern = dir; + if (!pattern.empty() && pattern.back() != L'\\') pattern += L'\\'; + pattern += L"*"; + + HANDLE handle = FindFirstFileW(pattern.c_str(), &data); + if (handle == INVALID_HANDLE_VALUE) return; + do { + std::wstring name = data.cFileName; + if (name == L"." || name == L"..") continue; + std::wstring rel = relBase.empty() ? name : relBase + L"\\" + name; + if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + dirs.push_back(rel); + CollectFiles(dir + L"\\" + name, rel, files, dirs); + } else { + files.push_back(rel); + } + } while (FindNextFileW(handle, &data)); + FindClose(handle); } -Worker::~Worker() -{ +bool SameHash(const std::wstring& expected, const std::string& actual) { + std::string want = Utils::WideToUtf8(expected); + if (want.empty()) return true; + return Utils::ToLowerAscii(want) == Utils::ToLowerAscii(actual); +} } -void Worker::slotCheckUpdate() -{ - QList files; - // 解析XML文件获取最新文件列表 - this->parseXML(QCoreApplication::applicationDirPath() + "/Update.xml"); - for (int i = 0; i < m_fileInfo.count(); i++) - { - QFileInfo fileInfo(QCoreApplication::applicationDirPath() + "/" + m_fileInfo.at(i).path); - QDir dir(QCoreApplication::applicationDirPath() + "/" + m_fileInfo.at(i).path); - // 如果文件不存在则直接下载文件或创建文件夹 - if (!fileInfo.exists()) - { - if (m_fileInfo[i].type == "File") - { - // 下载文件 - qDebug() << "文件大小" << m_fileInfo[i].size; - m_filesSize += m_fileInfo[i].size; - files.append(m_fileInfo[i]); - } - else if (m_fileInfo[i].type == "Dir") - { - // 创建文件夹 - dir.mkpath(QCoreApplication::applicationDirPath() + "/" + m_fileInfo.at(i).path); - } - continue; - } - - // 存在版本信息则对比版本 - if (!m_fileInfo[i].version.isEmpty()) - { - // 如果是文件则获取版本对比 - if (fileInfo.isFile()) - { - QString version = this->getFileVertion(QCoreApplication::applicationDirPath() + "/" + m_fileInfo.at(i).path); - - if (!version.contains(m_fileInfo[i].version)) - { - qDebug() << m_fileInfo [i].path << "当前版本: " << version << "| 最新版本: " << m_fileInfo[i].version; - m_filesSize += m_fileInfo[i].size; - // 版本号不一致则下载文件 - files.append(m_fileInfo[i]); - continue; - } - } - } - - } - - qDebug() << "更新文件数量:" << files.count(); - qDebug() << "更新文件总大小:" << m_filesSize; - - for (int i = 0; i < files.count(); i++) - { - QUrl url = QUrl::fromUserInput(m_url + "/Update/"+ files[i].path); - // 失败直接加上目标文件大小 - if (FAILURE == download(&url, QCoreApplication::applicationDirPath() + "/" + files[i].path, "正在下载:" + files[i].name)) - { - m_downloadSize += files[i].size; - } - } - - +Worker::Worker() : cancel_(false), running_(false) {} +Worker::~Worker() { + Cancel(); + if (thread_) { + WaitForSingleObject(thread_, 5000); + CloseHandle(thread_); + thread_ = nullptr; + } } -QString Worker::getFileVertion(QString fullName) -{ - QString result = ""; - char* pData = nullptr; - do - { - DWORD dwLen = GetFileVersionInfoSize(fullName.toStdWString().c_str(), 0); - if (0 == dwLen) - { - break; - } - pData = new char[dwLen + 1]; - BOOL bSuccess = GetFileVersionInfo(fullName.toStdWString().c_str(), 0, dwLen, pData); - if (!bSuccess) - { - break; - } - struct LANGANDCODEPAGE - { - WORD wLanguage; - WORD wCodePage; - } *lpTranslate; - LPVOID lpBuffer = nullptr; - UINT uLen = 0; - bSuccess = VerQueryValue(pData, (TEXT("\\VarFileInfo\\Translation")), (LPVOID*)&lpTranslate, &uLen); - if (!bSuccess) - { - break; - } - QString str1, str2; - str1.setNum(lpTranslate->wLanguage, 16); - str2.setNum(lpTranslate->wCodePage, 16); - str1 = "000" + str1; - str2 = "000" + str2; - QString verPath = "\\StringFileInfo\\" + str1.right(4) + str2.right(4) + "\\FileVersion";//ProductVersion:产品版本号 FileVersion:文件版本号 - bSuccess = VerQueryValue(pData, (verPath.toStdWString().c_str()), &lpBuffer, &uLen); - if (!bSuccess) - { - break; - } - result = QString::fromUtf16((const unsigned short int *)lpBuffer); - } while (false); - if (nullptr != pData) - { - delete pData; - } - return result; +unsigned __stdcall Worker::ThreadEntry(void* param) { + Worker* worker = static_cast(param); + worker->Run(); + _endthreadex(0); + return 0; } -QList Worker::FindFile(const QString& path) -{ - QList result; - - // QDir的路径一定要是全路径,相对路径会有错误 - QDir dir(path); - if (!dir.exists()) - { - return result; - } - - - // 取到所有的文件和文件名,去掉.和..文件夹 - dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); - // 设置排序方式 - dir.setSorting(QDir::DirsFirst); - // 将其转化为一个list - QFileInfoList list = dir.entryInfoList(); - if (list.size() < 1) - { - return result; - } - - - int i = 0; - // 采用递归算法 - do { - QFileInfo fileInfo = list.at(i); - FILE_INFO file; - // 判断是否为文件夹 - bool isDirectory = fileInfo.isDir(); - if (isDirectory) - { - qDebug() << "[Dir]" << fileInfo.filePath() << " -> " << fileInfo.size() << " -> " << file.version; - // 获取文件信息 - file.path = fileInfo.filePath(); - file.size = 0; - file.type = "Dir"; - file.version.clear(); - auto tmp = FindFile(fileInfo.filePath()); - result = result + tmp; - } - else - { - // 获取文件信息 - file.path = fileInfo.filePath(); - file.size = fileInfo.size(); - file.type = "File"; - file.version = this->getFileVertion(file.path); - result.append(file); - // qDebug() << "[File]" << fileInfo.filePath() << " -> " << fileInfo.size() << " -> " << file.version; - } - ++i; - } while (i < list.size()); - - return result; +void Worker::Cancel() { + cancel_.store(true); } -void Worker::run() -{ - // 开始工作 - m_currentState = DownloadXML; - // 下载XML文件 - QUrl xmlUrl = QUrl::fromUserInput(m_url + "/Update.xml"); - qDebug() << "下载地址:" << m_url + "/Update.xml"; - download(&xmlUrl, QCoreApplication::applicationDirPath() + "/Update.xml", "正在检查更新"); +void Worker::Emit(int percent, const std::wstring& text) { + if (onState_) onState_(percent, text); } -void Worker::updateProgress(qint64 dowloadedBytes, qint64 totalBytes) -{ - - - int statusCode = m_networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if (m_currentState!= DownloadXML) - { - m_downloadTempSize = dowloadedBytes; - if (dowloadedBytes == totalBytes) - { - // 下载完成一个文件清空临时大小并附加到总大小 - m_downloadSize += m_downloadTempSize; - m_downloadTempSize = 0; - emit signalProgress(m_downloadSize, m_filesSize); - } - else - { - emit signalProgress(m_downloadSize + m_downloadTempSize, m_filesSize); - } - qDebug() << "下载进度: " << m_downloadSize << "|" << dowloadedBytes << "|"<< totalBytes << "|"; - - - - - } +void Worker::Finish(bool success, const std::wstring& text) { + running_.store(false); + if (onFinish_) onFinish_(success, text); } -void Worker::slotReadyRead() -{ - int statusCode = m_networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if (statusCode == 200) - { - - QByteArray bytes = m_networkReply->readAll(); - m_downloadFile->write(bytes); - } +void Worker::Start(const UpdateOptions& options, StateCallback onState, FinishCallback onFinish) { + options_ = options; + onState_ = onState; + onFinish_ = onFinish; + cancel_.store(false); + running_.store(true); + + if (thread_) { + CloseHandle(thread_); + thread_ = nullptr; + } + thread_ = reinterpret_cast(_beginthreadex(nullptr, 0, &Worker::ThreadEntry, this, 0, nullptr)); + if (!thread_) { + running_.store(false); + Finish(false, L"无法创建工作线程"); + } } -void Worker::slotFinished() -{ - - int statusCode = m_networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - qDebug() << "代码:" << statusCode; - switch (statusCode) - { - case 200: - // 关闭文件 - m_downloadFile->close(); - // 销毁文件类 - delete m_downloadFile; - // 销毁网络请求类 - m_networkReply->deleteLater(); - // 销毁网络管理类 - m_networkManager->deleteLater(); +bool Worker::CopyToTarget(const std::wstring& staging, const std::wstring& targetDir, + std::wstring& err) { + std::vector files; + std::vector dirs; + CollectFiles(staging, L"", files, dirs); - switch (m_currentState) - { - case DownloadXML: - connect(this, SIGNAL(sigCheckUpdate()), this, SLOT(checkUpdate())); - // 更新状态 - m_currentState = DownloadUpdate; - // 发出检查更新信号 - emit signalCheckUpdate(); - break; - case DownloadUpdate: - qDebug() << "[结束]下载进度: "<< m_downloadSize ; - break; - default: - break; - } - break; - case 302: - { - qDebug() << "重定向"; - // 重定向 再次尝试 - QUrl url = m_networkReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); - m_networkReply = m_networkManager->get(QNetworkRequest(url)); - connect(m_networkReply, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); - connect(m_networkReply, SIGNAL(finished()), this, SLOT(slotFinished())); - connect(m_networkReply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateProgress(qint64, qint64))); - break; - } - default: - qDebug() << "网络错误"; - emit signalError("网络错误", "错误代码: " + QString::number(statusCode)); - m_downloadFile->close(); - delete m_downloadFile; - m_networkReply->deleteLater(); - m_networkManager->deleteLater(); - break; - } + if (!Utils::CreateDirRecursive(targetDir)) { + err = L"无法创建目录:" + targetDir; + return false; + } + + for (size_t i = 0; i < dirs.size(); ++i) { + std::wstring dst = Utils::JoinPath(targetDir, dirs[i]); + if (!Utils::CreateDirRecursive(dst)) { + err = L"无法创建目录:" + dst; + return false; + } + } + + for (size_t i = 0; i < files.size(); ++i) { + if (cancel_.load()) { + err = L"已取消"; + return false; + } + int percent = 92 + static_cast((i + 1) * 6 / (files.size() + 1)); + Emit(percent, L"正在更新文件 (" + std::to_wstring(i + 1) + L"/" + + std::to_wstring(files.size()) + L")"); + + std::wstring src = Utils::JoinPath(staging, files[i]); + std::wstring dst = Utils::JoinPath(targetDir, files[i]); + + if (Utils::FileExists(dst)) { + if (CopyFileW(src.c_str(), dst.c_str(), FALSE)) continue; + // 目标文件可能被占用,改用延时替换 + std::wstring tmp = dst + L".updater.tmp"; + Utils::DeleteFileForce(tmp); + if (!CopyFileW(src.c_str(), tmp.c_str(), FALSE)) { + err = L"无法写入文件:" + dst; + return false; + } + if (!Utils::ReplaceInUse(tmp, dst)) { + Utils::DeleteFileForce(tmp); + err = L"文件被占用,无法替换:" + dst; + return false; + } + continue; + } + + if (!CopyFileW(src.c_str(), dst.c_str(), TRUE)) { + err = L"无法写入文件:" + dst; + return false; + } + } + return true; } -// 下载文件 -int Worker::download(QUrl *url, QString path, QString status) -{ - if (!url->isValid()) - { - qDebug() << "下载失败: 网址无效"; - emit signalError("无效网址", "目标网址无效"); - return FAILURE; - } - m_downloadFile = new QFile(path); - if (!m_downloadFile->open(QIODevice::WriteOnly)) - { - qDebug() << "下载失败: 无法打开文件" << path; - emit signalError("文件操作失败", "无法打开临时文件!"); - return FAILURE; - } +void Worker::Run() { + std::wstring targetDir = options_.targetDir; + if (targetDir.empty()) targetDir = UPDATER_TARGET_DIR; + if (targetDir.empty()) targetDir = Utils::GetModuleDir(); + Emit(2, L"正在准备更新..."); +#if UPDATER_WAIT_EXIT_SEC > 0 + std::wstring waitName = options_.launchExe.empty() ? UPDATER_LAUNCH_EXE : options_.launchExe; + if (!waitName.empty()) { + Emit(3, L"正在等待主程序退出..."); + Utils::WaitForProcessExit(waitName, UPDATER_WAIT_EXIT_SEC); + } +#endif - m_networkManager = new QNetworkAccessManager; - m_networkReply = m_networkManager->get(QNetworkRequest(*url)); - connect(m_networkReply, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); - connect(m_networkReply, SIGNAL(finished()), this, SLOT(slotFinished())); - connect(m_networkReply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateProgress(qint64, qint64))); + if (cancel_.load()) { Finish(false, L"已取消"); return; } - emit sigShowStatus(status); - // 事件循环 - QEventLoop eventLoop; - // 连接信号和槽 - connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); - // 开始循环 - eventLoop.exec(); + Emit(5, L"正在检查更新..."); + Api::Result result = Api::CheckUpdate(options_.appKey, options_.clientVersion); + if (!result.ok) { + Finish(false, result.error); + return; + } - qDebug() << "开始下载"; - // 更新状态 - - return SUCCESS; + UpdateInfo& info = result.info; + if (!info.hasUpdate) { + Finish(true, L"当前已是最新版本,无需更新"); + return; + } + + // 选择要下载的包:全量模式取完整包,补丁模式优先取补丁包 + std::wstring url; + unsigned long long size = 0; + std::wstring hash; + std::wstring modeText; + bool stripRoot = false; + + if (options_.fullMode) { + url = info.fullPackageUrl; + size = info.fullPackageSize; + hash = info.fullPackageHash; + modeText = L"完整包"; + stripRoot = true; + if (url.empty()) { + url = info.downloadUrl; + size = info.downloadSize; + hash = info.downloadHash; + } + } else { + if (info.isPatch && !info.patchUrl.empty()) { + url = info.patchUrl; + size = info.patchSize; + hash = info.patchHash; + modeText = L"补丁包"; + } else { + // 没有补丁包信息时,download_url 就是完整包(服务端 update_type 恒为 patch,不能用来判断) + url = info.downloadUrl; + size = info.downloadSize; + hash = info.downloadHash; + modeText = L"完整包"; + stripRoot = true; + } + } + + if (url.empty()) { + Finish(false, L"服务器没有返回下载地址"); + return; + } + + std::wstring versionText = info.latestVersion.empty() ? L"" : L" (" + info.latestVersion + L")"; + Emit(8, L"开始下载" + modeText + versionText + L"..."); + + std::wstring tempDir = Utils::GetTempDir(); + std::wstring package = Utils::MakeUniqueTempFile(tempDir, L"updater_pkg"); + std::wstring err; + + int lastPercent = -1; + unsigned long long lastTick = 0; + bool ok = Http::Download(url, package, + [this, &lastPercent, &lastTick, size](unsigned long long received, + unsigned long long total) { + if (cancel_.load()) return false; + unsigned long long base = total > 0 ? total : size; + int percent = 8; + if (base > 0) { + double ratio = static_cast(received) / static_cast(base); + if (ratio > 1.0) ratio = 1.0; + percent = 8 + static_cast(ratio * 62.0); + } + unsigned long long now = GetTickCount64(); + if (percent != lastPercent || now - lastTick > 300) { + lastPercent = percent; + lastTick = now; + Emit(percent, L"正在下载 " + Utils::FormatSize(received) + + (base > 0 ? (L" / " + Utils::FormatSize(base)) : L"")); + } + return true; + }, + err); + + if (!ok) { + Utils::DeleteFileForce(package); + Finish(false, cancel_.load() ? L"已取消" : (L"下载失败:" + err)); + return; + } + + if (cancel_.load()) { + Utils::DeleteFileForce(package); + Finish(false, L"已取消"); + return; + } + +#if UPDATER_VERIFY_HASH + if (!hash.empty()) { + Emit(72, L"正在校验文件..."); + std::string actual = Utils::Sha256HexFile(package); + if (!SameHash(hash, actual)) { + Utils::DeleteFileForce(package); + Finish(false, L"文件校验失败,已中止更新"); + return; + } + } +#endif + + Emit(75, L"正在解压..."); + std::wstring staging = Utils::MakeUniqueTempFile(tempDir, L"updater_dir"); + DeleteFileW(staging.c_str()); + if (!Utils::CreateDirRecursive(staging)) { + Utils::DeleteFileForce(package); + Finish(false, L"无法创建临时目录"); + return; + } + + Unzip unzip; + std::vector written; + std::wstring unzipErr; + if (!unzip.Open(package, unzipErr)) { + Utils::DeleteFileForce(package); + Finish(false, unzipErr); + return; + } + bool extracted = unzip.ExtractAll( + staging, stripRoot, + [this](unsigned long long done, unsigned long long total, const std::wstring& name) { + if (cancel_.load()) return false; + int percent = 75; + if (total > 0) { + double ratio = static_cast(done) / static_cast(total); + percent = 75 + static_cast(ratio * 17.0); + } + Emit(percent, L"正在解压 " + name); + return true; + }, + written, unzipErr); + unzip.Close(); + Utils::DeleteFileForce(package); + (void)written; + + if (!extracted) { + Finish(false, cancel_.load() ? L"已取消" : unzipErr); + return; + } + + Emit(92, L"正在应用更新..."); + std::wstring copyErr; + if (!CopyToTarget(staging, targetDir, copyErr)) { + Finish(false, copyErr); + return; + } + + Emit(98, L"正在清理临时文件..."); + std::vector stagedFiles; + std::vector stagedDirs; + CollectFiles(staging, L"", stagedFiles, stagedDirs); + for (size_t i = 0; i < stagedFiles.size(); ++i) { + Utils::DeleteFileForce(Utils::JoinPath(staging, stagedFiles[i])); + } + for (size_t i = stagedDirs.size(); i > 0; --i) { + RemoveDirectoryW(Utils::JoinPath(staging, stagedDirs[i - 1]).c_str()); + } + RemoveDirectoryW(staging.c_str()); + + Emit(100, L"更新完成"); + +#if defined(UPDATER_LAUNCH_EXE) + std::wstring launch = options_.launchExe.empty() ? UPDATER_LAUNCH_EXE : options_.launchExe; + if (!launch.empty()) { + Utils::LaunchProcess(Utils::JoinPath(targetDir, launch), L"", targetDir); + } +#endif + + Finish(true, L"更新完成" + versionText); } - - -// 解析XML文件 -void Worker::parseXML(QString fileName) -{ - // 避免中文乱码 - QTextCodec *codec = QTextCodec::codecForName("UTF8"); - QFile file(fileName); - - // 打开XML文件 - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - { - emit signalError("文件操作失败", "无法打开XML文件!"); - return; - } - - // 读取XML文件并解析 - QDomDocument doc; - if (!doc.setContent(&file)) - { - emit signalError("文件操作失败","无法解析XML文件!"); - file.close(); - return; - } - file.close(); - - // 获取根节点 - QDomElement root = doc.documentElement(); - // 获取第一个子节点 - QDomNode node = root.firstChild(); - // 遍历子节点 - while (!node.isNull()) - { - // 如果节点是元素 - if (node.isElement()) - { - // 转换为元素 - QDomElement element = node.toElement(); - if (!element.isNull()) - { - FILE_INFO fileInfo; - fileInfo.name = element.attribute("name"); - fileInfo.path = element.attribute("path"); - fileInfo.size = element.attribute("size").toInt(); - - fileInfo.type = element.attribute("type"); - fileInfo.version = element.attribute("version"); - m_fileInfo.append(fileInfo); - } - } - // 下一个兄弟节点 - node = node.nextSibling(); - } } - -// 删除文件或目录 -bool Worker::deleteFileOrDirectory(QString path) -{ - // 判断路径是否为空 - if (path.isEmpty() || !QDir().exists(path)) - { - return false; - } - - QFileInfo fileInfo(path); - // 删除文件 - if (fileInfo.isFile()) - { - return QFile::remove(path); - } - // 删除目录 - else if (fileInfo.isDir()) - { - QDir dir(path); - dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); - QFileInfoList fileList = dir.entryInfoList(); - foreach(QFileInfo fi, fileList) - { - if (fi.isFile()) - { - fi.dir().remove(fi.fileName()); - } - else - { - deleteFileOrDirectory(fi.absoluteFilePath()); - } - } - dir.rmpath(dir.absolutePath()); - } - return true; -} - diff --git a/Update/Worker.h b/Update/Worker.h index 64e903f..ed6d5fb 100644 --- a/Update/Worker.h +++ b/Update/Worker.h @@ -1,92 +1,48 @@ #pragma once -#include -#include -#include -#include -#include -#include +#include +#include +#include +namespace updater { -// 检查更新 -#define MSG_CHECK_UPDATE "正在检查更新..." -// 更新中 -#define MSG_UPDATE "更新中..." -// 正在启动游戏 -#define MSG_LAUNCH "Launching the game..." -#define SUCCESS 1 -#define FAILURE 0 - - -typedef enum _ProgramState -{ - // 下载XML - DownloadXML, - // 下载游戏 - DownloadUpdate, -}ProgramState; - -typedef struct _FILE_INFO { - QString name; - QString path; - QString type; - QString version; - int size; -}FILE_INFO; - - -class Worker : public QThread { - - Q_OBJECT -public: - Worker(); - ~Worker(); -private: - QNetworkAccessManager* m_networkManager; - QNetworkReply* m_networkReply; - QList m_fileInfo; -private: - QString getFileVertion(QString fullName); - QList FindFile(const QString& path); -signals: - // 显示下载进度 - void signalProgress(qint64, qint64); - // 显示状态信息 - void sigShowStatus(const QString &); - // 显示更新信息 - void sigShowInfo(const QString &); - // 显示错误信息 - void signalError(const QString &, const QString &); - // 检查更新 - void signalCheckUpdate(); - // 启动客户端 - void sigLaunchGame(); - // 退出 - void signalFinished(); - -private slots: - void slotCheckUpdate(); - void updateProgress(qint64, qint64); // update the progress bar - - void slotReadyRead(); - void slotFinished(); -public: - void run(); -private: - // 当前状态 - ProgramState m_currentState; - // XML文件下载地址 - QString m_url; - - // 全部文件下载大小 - qint64 m_downloadSize; - // 需要下载文件总大小 - qint64 m_filesSize; - // 当前文件大小 - qint64 m_downloadTempSize; - QFile* m_downloadFile; - bool showProgress; - int download(QUrl*, QString, QString); - void parseXML(QString); - bool deleteFileOrDirectory(QString path); +struct UpdateOptions { + std::wstring appKey; + std::wstring clientVersion; // 为空表示全量安装模式 + std::wstring targetDir; // 为空时用 UPDATER_TARGET_DIR / 程序所在目录 + bool fullMode = false; // true = 下载完整包;false = 按版本下载补丁包 + std::wstring launchExe; // 更新完成后拉起的程序,留空用 UPDATER_LAUNCH_EXE }; + +class Worker { +public: + using StateCallback = std::function; + using FinishCallback = std::function; + + Worker(); + ~Worker(); + + Worker(const Worker&) = delete; + Worker& operator=(const Worker&) = delete; + + void Start(const UpdateOptions& options, StateCallback onState, FinishCallback onFinish); + void Cancel(); + bool running() const { return running_; } + +private: + static unsigned __stdcall ThreadEntry(void* param); + void Run(); + void Emit(int percent, const std::wstring& text); + void Finish(bool success, const std::wstring& text); + bool CopyToTarget(const std::wstring& staging, const std::wstring& targetDir, + std::wstring& err); + + UpdateOptions options_; + StateCallback onState_; + FinishCallback onFinish_; + std::atomic cancel_; + std::atomic running_; + void* thread_ = nullptr; +}; + +} diff --git a/Update/Zip.cpp b/Update/Zip.cpp deleted file mode 100644 index cc432e8..0000000 --- a/Update/Zip.cpp +++ /dev/null @@ -1,1791 +0,0 @@ -/* - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ -#define __STDC_WANT_LIB_EXT1__ 1 - -#include -#include -#include - -#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ - defined(__MINGW32__) - /* Win32, DOS, MSVC, MSVS */ -#include - -#define STRCLONE(STR) ((STR) ? _strdup(STR) : NULL) -#define HAS_DEVICE(P) \ - ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) && \ - (P)[1] == ':') -#define FILESYSTEM_PREFIX_LEN(P) (HAS_DEVICE(P) ? 2 : 0) - -#else - -#include // needed for symlink() -#define STRCLONE(STR) ((STR) ? strdup(STR) : NULL) - -#endif - -#ifdef __MINGW32__ -#include -#include -#endif - -#include "miniz.h" -#include "zip.h" - -#ifdef _MSC_VER -#include - -#define ftruncate(fd, sz) (-(_chsize_s((fd), (sz)) != 0)) -#define fileno _fileno -#endif - -#if defined(__TINYC__) && (defined(_WIN32) || defined(_WIN64)) -#include - -#define ftruncate(fd, sz) (-(_chsize_s((fd), (sz)) != 0)) -#define fileno _fileno -#endif - -#ifndef HAS_DEVICE -#define HAS_DEVICE(P) 0 -#endif - -#ifndef FILESYSTEM_PREFIX_LEN -#define FILESYSTEM_PREFIX_LEN(P) 0 -#endif - -#ifndef ISSLASH -#define ISSLASH(C) ((C) == '/' || (C) == '\\') -#endif - -#define CLEANUP(ptr) \ - do { \ - if (ptr) { \ - free((void *)ptr); \ - ptr = NULL; \ - } \ - } while (0) - -#define UNX_IFDIR 0040000 /* Unix directory */ -#define UNX_IFREG 0100000 /* Unix regular file */ -#define UNX_IFSOCK 0140000 /* Unix socket (BSD, not SysV or Amiga) */ -#define UNX_IFLNK 0120000 /* Unix symbolic link (not SysV, Amiga) */ -#define UNX_IFBLK 0060000 /* Unix block special (not Amiga) */ -#define UNX_IFCHR 0020000 /* Unix character special (not Amiga) */ -#define UNX_IFIFO 0010000 /* Unix fifo (BCC, not MSC or Amiga) */ - -struct zip_entry_t { - ssize_t index; - char* name; - mz_uint64 uncomp_size; - mz_uint64 comp_size; - mz_uint32 uncomp_crc32; - mz_uint64 offset; - mz_uint8 header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - mz_uint64 header_offset; - mz_uint16 method; - mz_zip_writer_add_state state; - tdefl_compressor comp; - mz_uint32 external_attr; - time_t m_time; -}; - -struct zip_t { - mz_zip_archive archive; - mz_uint level; - struct zip_entry_t entry; -}; - -enum zip_modify_t { - MZ_KEEP = 0, - MZ_DELETE = 1, - MZ_MOVE = 2, -}; - -struct zip_entry_mark_t { - ssize_t file_index; - enum zip_modify_t type; - mz_uint64 m_local_header_ofs; - size_t lf_length; -}; - -static const char* const zip_errlist[30] = { - NULL, - "not initialized\0", - "invalid entry name\0", - "entry not found\0", - "invalid zip mode\0", - "invalid compression level\0", - "no zip 64 support\0", - "memset error\0", - "cannot write data to entry\0", - "cannot initialize tdefl compressor\0", - "invalid index\0", - "header not found\0", - "cannot flush tdefl buffer\0", - "cannot write entry header\0", - "cannot create entry header\0", - "cannot write to central dir\0", - "cannot open file\0", - "invalid entry type\0", - "extracting data using no memory allocation\0", - "file not found\0", - "no permission\0", - "out of memory\0", - "invalid zip archive name\0", - "make dir error\0", - "symlink error\0", - "close archive error\0", - "capacity size too small\0", - "fseek error\0", - "fread error\0", - "fwrite error\0", -}; - -const char* zip_strerror(int errnum) { - errnum = -errnum; - if (errnum <= 0 || errnum >= 30) { - return NULL; - } - - return zip_errlist[errnum]; -} - -static const char* zip_basename(const char* name) { - char const* p; - char const* base = name += FILESYSTEM_PREFIX_LEN(name); - int all_slashes = 1; - - for (p = name; *p; p++) { - if (ISSLASH(*p)) - base = p + 1; - else - all_slashes = 0; - } - - /* If NAME is all slashes, arrange to return `/'. */ - if (*base == '\0' && ISSLASH(*name) && all_slashes) - --base; - - return base; -} - -static int zip_mkpath(char* path) { - char* p; - char npath[MAX_PATH + 1]; - int len = 0; - int has_device = HAS_DEVICE(path); - - memset(npath, 0, MAX_PATH + 1); - if (has_device) { - // only on windows - npath[0] = path[0]; - npath[1] = path[1]; - len = 2; - } - for (p = path + len; *p && len < MAX_PATH; p++) { - if (ISSLASH(*p) && ((!has_device && len > 0) || (has_device && len > 2))) { -#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ - defined(__MINGW32__) -#else - if ('\\' == *p) { - *p = '/'; - } -#endif - - if (MZ_MKDIR(npath) == -1) { - if (errno != EEXIST) { - return ZIP_EMKDIR; - } - } - } - npath[len++] = *p; - } - - return 0; -} - -static char* zip_strrpl(const char* str, size_t n, char oldchar, char newchar) { - char c; - size_t i; - char* rpl = (char*)calloc((1 + n), sizeof(char)); - char* begin = rpl; - if (!rpl) { - return NULL; - } - - for (i = 0; (i < n) && (c = *str++); ++i) { - if (c == oldchar) { - c = newchar; - } - *rpl++ = c; - } - - return begin; -} - -static char* zip_name_normalize(char* name, char* const nname, size_t len) { - size_t offn = 0; - size_t offnn = 0, ncpy = 0; - - if (name == NULL || nname == NULL || len <= 0) { - return NULL; - } - // skip trailing '/' - while (ISSLASH(*name)) - name++; - - for (; offn < len; offn++) { - if (ISSLASH(name[offn])) { - if (ncpy > 0 && strcmp(&nname[offnn], ".\0") && - strcmp(&nname[offnn], "..\0")) { - offnn += ncpy; - nname[offnn++] = name[offn]; // append '/' - } - ncpy = 0; - } - else { - nname[offnn + ncpy] = name[offn]; - ncpy++; - } - } - - // at the end, extra check what we've already copied - if (ncpy == 0 || !strcmp(&nname[offnn], ".\0") || - !strcmp(&nname[offnn], "..\0")) { - nname[offnn] = 0; - } - return nname; -} - -static mz_bool zip_name_match(const char* name1, const char* name2) { - char* nname2 = NULL; - -#ifdef ZIP_RAW_ENTRYNAME - nname2 = STRCLONE(name2); -#else - nname2 = zip_strrpl(name2, strlen(name2), '\\', '/'); -#endif - - if (!nname2) { - return MZ_FALSE; - } - - mz_bool res = (strcmp(name1, nname2) == 0) ? MZ_TRUE : MZ_FALSE; - CLEANUP(nname2); - return res; -} - -static int zip_archive_truncate(mz_zip_archive* pzip) { - mz_zip_internal_state* pState = pzip->m_pState; - mz_uint64 file_size = pzip->m_archive_size; - if ((pzip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { - return 0; - } - if (pzip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED) { - if (pState->m_pFile) { - int fd = fileno(pState->m_pFile); - return ftruncate(fd, file_size); - } - } - return 0; -} - -static int zip_archive_extract(mz_zip_archive* zip_archive, const char* dir, - int (*on_extract)(const char* filename, - void* arg), - void* arg) { - int err = 0; - mz_uint i, n; - char path[MAX_PATH + 1]; - char symlink_to[MAX_PATH + 1]; - mz_zip_archive_file_stat info; - size_t dirlen = 0, filename_size = MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE; - mz_uint32 xattr = 0; - - memset(path, 0, sizeof(path)); - memset(symlink_to, 0, sizeof(symlink_to)); - - dirlen = strlen(dir); - if (dirlen + 1 > MAX_PATH) { - return ZIP_EINVENTNAME; - } - - memset((void*)&info, 0, sizeof(mz_zip_archive_file_stat)); - -#if defined(_MSC_VER) - strcpy_s(path, MAX_PATH, dir); -#else - strcpy(path, dir); -#endif - - if (!ISSLASH(path[dirlen - 1])) { -#if defined(_WIN32) || defined(__WIN32__) - path[dirlen] = '\\'; -#else - path[dirlen] = '/'; -#endif - ++dirlen; - } - - if (filename_size > MAX_PATH - dirlen) { - filename_size = MAX_PATH - dirlen; - } - // Get and print information about each file in the archive. - n = mz_zip_reader_get_num_files(zip_archive); - for (i = 0; i < n; ++i) { - if (!mz_zip_reader_file_stat(zip_archive, i, &info)) { - // Cannot get information about zip archive; - err = ZIP_ENOENT; - goto out; - } - - if (!zip_name_normalize(info.m_filename, info.m_filename, - strlen(info.m_filename))) { - // Cannot normalize file name; - err = ZIP_EINVENTNAME; - goto out; - } - -#if defined(_MSC_VER) - strncpy_s(&path[dirlen], filename_size, info.m_filename, - filename_size); -#else - strncpy(&path[dirlen], info.m_filename, filename_size); -#endif - err = zip_mkpath(path); - if (err < 0) { - // Cannot make a path - goto out; - } - - if ((((info.m_version_made_by >> 8) == 3) || - ((info.m_version_made_by >> 8) == - 19)) // if zip is produced on Unix or macOS (3 and 19 from - // section 4.4.2.2 of zip standard) - && info.m_external_attr & - (0x20 << 24)) { // and has sym link attribute (0x80 is file, 0x40 - // is directory) -#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ - defined(__MINGW32__) -#else - if (info.m_uncomp_size > MAX_PATH || - !mz_zip_reader_extract_to_mem_no_alloc(zip_archive, i, symlink_to, - MAX_PATH, 0, NULL, 0)) { - err = ZIP_EMEMNOALLOC; - goto out; - } - symlink_to[info.m_uncomp_size] = '\0'; - if (symlink(symlink_to, path) != 0) { - err = ZIP_ESYMLINK; - goto out; - } -#endif - } - else { - if (!mz_zip_reader_is_file_a_directory(zip_archive, i)) { - if (!mz_zip_reader_extract_to_file(zip_archive, i, path, 0)) { - // Cannot extract zip archive to file - err = ZIP_ENOFILE; - goto out; - } - } - -#if defined(_MSC_VER) || defined(PS4) - (void)xattr; // unused -#else - xattr = (info.m_external_attr >> 16) & 0xFFFF; - if (xattr > 0 && xattr <= MZ_UINT16_MAX) { - if (CHMOD(path, (mode_t)xattr) < 0) { - err = ZIP_ENOPERM; - goto out; - } - } -#endif - } - - if (on_extract) { - if (on_extract(path, arg) < 0) { - goto out; - } - } - } - -out: - // Close the archive, freeing any resources it was using - if (!mz_zip_reader_end(zip_archive)) { - // Cannot end zip reader - err = ZIP_ECLSZIP; - } - return err; -} - -static inline void zip_archive_finalize(mz_zip_archive* pzip) { - mz_zip_writer_finalize_archive(pzip); - zip_archive_truncate(pzip); -} - -static ssize_t zip_entry_mark(struct zip_t* zip, - struct zip_entry_mark_t* entry_mark, - const ssize_t n, char* const entries[], - const size_t len) { - ssize_t i = 0; - ssize_t err = 0; - if (!zip || !entry_mark || !entries) { - return ZIP_ENOINIT; - } - - mz_zip_archive_file_stat file_stat; - mz_uint64 d_pos = ~0UL; - for (i = 0; i < n; ++i) { - if ((err = zip_entry_openbyindex(zip, i))) { - return (ssize_t)err; - } - - mz_bool name_matches = MZ_FALSE; - { - size_t j; - for (j = 0; j < len; ++j) { - if (zip_name_match(zip->entry.name, entries[j])) { - name_matches = MZ_TRUE; - break; - } - } - } - if (name_matches) { - entry_mark[i].type = MZ_DELETE; - } - else { - entry_mark[i].type = MZ_KEEP; - } - - if (!mz_zip_reader_file_stat(&zip->archive, i, &file_stat)) { - return ZIP_ENOENT; - } - - zip_entry_close(zip); - - entry_mark[i].m_local_header_ofs = file_stat.m_local_header_ofs; - entry_mark[i].file_index = (ssize_t)-1; - entry_mark[i].lf_length = 0; - if ((entry_mark[i].type) == MZ_DELETE && - (d_pos > entry_mark[i].m_local_header_ofs)) { - d_pos = entry_mark[i].m_local_header_ofs; - } - } - - for (i = 0; i < n; ++i) { - if ((entry_mark[i].m_local_header_ofs > d_pos) && - (entry_mark[i].type != MZ_DELETE)) { - entry_mark[i].type = MZ_MOVE; - } - } - return err; -} - -static ssize_t zip_index_next(mz_uint64* local_header_ofs_array, - ssize_t cur_index) { - ssize_t new_index = 0, i; - for (i = cur_index - 1; i >= 0; --i) { - if (local_header_ofs_array[cur_index] > local_header_ofs_array[i]) { - new_index = i + 1; - return new_index; - } - } - return new_index; -} - -static ssize_t zip_sort(mz_uint64* local_header_ofs_array, ssize_t cur_index) { - ssize_t nxt_index = zip_index_next(local_header_ofs_array, cur_index); - - if (nxt_index != cur_index) { - mz_uint64 temp = local_header_ofs_array[cur_index]; - ssize_t i; - for (i = cur_index; i > nxt_index; i--) { - local_header_ofs_array[i] = local_header_ofs_array[i - 1]; - } - local_header_ofs_array[nxt_index] = temp; - } - return nxt_index; -} - -static int zip_index_update(struct zip_entry_mark_t* entry_mark, - ssize_t last_index, ssize_t nxt_index) { - ssize_t j; - for (j = 0; j < last_index; j++) { - if (entry_mark[j].file_index >= nxt_index) { - entry_mark[j].file_index += 1; - } - } - entry_mark[nxt_index].file_index = last_index; - return 0; -} - -static int zip_entry_finalize(struct zip_t* zip, - struct zip_entry_mark_t* entry_mark, - const ssize_t n) { - - ssize_t i = 0; - mz_uint64* local_header_ofs_array = (mz_uint64*)calloc(n, sizeof(mz_uint64)); - if (!local_header_ofs_array) { - return ZIP_EOOMEM; - } - - for (i = 0; i < n; ++i) { - local_header_ofs_array[i] = entry_mark[i].m_local_header_ofs; - ssize_t index = zip_sort(local_header_ofs_array, i); - - if (index != i) { - zip_index_update(entry_mark, i, index); - } - entry_mark[i].file_index = index; - } - - size_t* length = (size_t*)calloc(n, sizeof(size_t)); - if (!length) { - CLEANUP(local_header_ofs_array); - return ZIP_EOOMEM; - } - for (i = 0; i < n - 1; i++) { - length[i] = - (size_t)(local_header_ofs_array[i + 1] - local_header_ofs_array[i]); - } - length[n - 1] = - (size_t)(zip->archive.m_archive_size - local_header_ofs_array[n - 1]); - - for (i = 0; i < n; i++) { - entry_mark[i].lf_length = length[entry_mark[i].file_index]; - } - - CLEANUP(length); - CLEANUP(local_header_ofs_array); - return 0; -} - -static ssize_t zip_entry_set(struct zip_t* zip, - struct zip_entry_mark_t* entry_mark, ssize_t n, - char* const entries[], const size_t len) { - ssize_t err = 0; - - if ((err = zip_entry_mark(zip, entry_mark, n, entries, len)) < 0) { - return err; - } - if ((err = zip_entry_finalize(zip, entry_mark, n)) < 0) { - return err; - } - return 0; -} - -static ssize_t zip_file_move(MZ_FILE* m_pFile, const mz_uint64 to, - const mz_uint64 from, const size_t length, - mz_uint8* move_buf, const size_t capacity_size) { - if (length > capacity_size) { - return ZIP_ECAPSIZE; - } - if (MZ_FSEEK64(m_pFile, (long)from, SEEK_SET)) { - return ZIP_EFSEEK; - } - if (fread(move_buf, 1, length, m_pFile) != length) { - return ZIP_EFREAD; - } - if (MZ_FSEEK64(m_pFile, (long)to, SEEK_SET)) { - return ZIP_EFSEEK; - } - if (fwrite(move_buf, 1, length, m_pFile) != length) { - return ZIP_EFWRITE; - } - return (ssize_t)length; -} - -static ssize_t zip_files_move(MZ_FILE* m_pFile, mz_uint64 writen_num, - mz_uint64 read_num, size_t length) { - ssize_t n = 0; - const size_t page_size = 1 << 12; // 4K - mz_uint8* move_buf = (mz_uint8*)calloc(1, page_size); - if (!move_buf) { - return ZIP_EOOMEM; - } - - ssize_t moved_length = 0; - ssize_t move_count = 0; - while ((mz_int64)length > 0) { - move_count = (length >= page_size) ? page_size : length; - n = zip_file_move(m_pFile, writen_num, read_num, move_count, move_buf, - page_size); - if (n < 0) { - moved_length = n; - goto cleanup; - } - - if (n != move_count) { - goto cleanup; - } - - writen_num += move_count; - read_num += move_count; - length -= move_count; - moved_length += move_count; - } - -cleanup: - CLEANUP(move_buf); - return moved_length; -} - -static int zip_central_dir_move(mz_zip_internal_state* pState, int begin, - int end, int entry_num) { - if (begin == entry_num) { - return 0; - } - - size_t l_size = 0; - size_t r_size = 0; - mz_uint32 d_size = 0; - mz_uint8* next = NULL; - mz_uint8* deleted = &MZ_ZIP_ARRAY_ELEMENT( - &pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, begin)); - l_size = (size_t)(deleted - (mz_uint8*)(pState->m_central_dir.m_p)); - if (end == entry_num) { - r_size = 0; - } - else { - next = &MZ_ZIP_ARRAY_ELEMENT( - &pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, end)); - r_size = pState->m_central_dir.m_size - - (mz_uint32)(next - (mz_uint8*)(pState->m_central_dir.m_p)); - d_size = (mz_uint32)(next - deleted); - } - - if (next && l_size == 0) { - memmove(pState->m_central_dir.m_p, next, r_size); - pState->m_central_dir.m_p = MZ_REALLOC(pState->m_central_dir.m_p, r_size); - { - int i; - for (i = end; i < entry_num; i++) { - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i) -= - d_size; - } - } - } - - if (next && l_size * r_size != 0) { - memmove(deleted, next, r_size); - { - int i; - for (i = end; i < entry_num; i++) { - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i) -= - d_size; - } - } - } - - pState->m_central_dir.m_size = l_size + r_size; - return 0; -} - -static int zip_central_dir_delete(mz_zip_internal_state* pState, - int* deleted_entry_index_array, - int entry_num) { - int i = 0; - int begin = 0; - int end = 0; - int d_num = 0; - while (i < entry_num) { - while ((i < entry_num) && (!deleted_entry_index_array[i])) { - i++; - } - begin = i; - - while ((i < entry_num) && (deleted_entry_index_array[i])) { - i++; - } - end = i; - zip_central_dir_move(pState, begin, end, entry_num); - } - - i = 0; - while (i < entry_num) { - while ((i < entry_num) && (!deleted_entry_index_array[i])) { - i++; - } - begin = i; - if (begin == entry_num) { - break; - } - while ((i < entry_num) && (deleted_entry_index_array[i])) { - i++; - } - end = i; - int k = 0, j; - for (j = end; j < entry_num; j++) { - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, - begin + k) = - (mz_uint32)MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, - mz_uint32, j); - k++; - } - d_num += end - begin; - } - - pState->m_central_dir_offsets.m_size = - sizeof(mz_uint32) * (entry_num - d_num); - return 0; -} - -static ssize_t zip_entries_delete_mark(struct zip_t* zip, - struct zip_entry_mark_t* entry_mark, - int entry_num) { - mz_uint64 writen_num = 0; - mz_uint64 read_num = 0; - size_t deleted_length = 0; - size_t move_length = 0; - int i = 0; - size_t deleted_entry_num = 0; - ssize_t n = 0; - - mz_bool* deleted_entry_flag_array = - (mz_bool*)calloc(entry_num, sizeof(mz_bool)); - if (deleted_entry_flag_array == NULL) { - return ZIP_EOOMEM; - } - - mz_zip_internal_state* pState = zip->archive.m_pState; - zip->archive.m_zip_mode = MZ_ZIP_MODE_WRITING; - - if ((!pState->m_pFile) || MZ_FSEEK64(pState->m_pFile, 0, SEEK_SET)) { - CLEANUP(deleted_entry_flag_array); - return ZIP_ENOENT; - } - - while (i < entry_num) { - while ((i < entry_num) && (entry_mark[i].type == MZ_KEEP)) { - writen_num += entry_mark[i].lf_length; - read_num = writen_num; - i++; - } - - while ((i < entry_num) && (entry_mark[i].type == MZ_DELETE)) { - deleted_entry_flag_array[i] = MZ_TRUE; - read_num += entry_mark[i].lf_length; - deleted_length += entry_mark[i].lf_length; - i++; - deleted_entry_num++; - } - - while ((i < entry_num) && (entry_mark[i].type == MZ_MOVE)) { - move_length += entry_mark[i].lf_length; - mz_uint8* p = &MZ_ZIP_ARRAY_ELEMENT( - &pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i)); - if (!p) { - CLEANUP(deleted_entry_flag_array); - return ZIP_ENOENT; - } - mz_uint32 offset = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - offset -= (mz_uint32)deleted_length; - MZ_WRITE_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS, offset); - i++; - } - - n = zip_files_move(pState->m_pFile, writen_num, read_num, move_length); - if (n != (ssize_t)move_length) { - CLEANUP(deleted_entry_flag_array); - return n; - } - writen_num += move_length; - read_num += move_length; - } - - zip->archive.m_archive_size -= (mz_uint64)deleted_length; - zip->archive.m_total_files = - (mz_uint32)entry_num - (mz_uint32)deleted_entry_num; - - zip_central_dir_delete(pState, deleted_entry_flag_array, entry_num); - CLEANUP(deleted_entry_flag_array); - - return (ssize_t)deleted_entry_num; -} - -struct zip_t* zip_open(const char* zipname, int level, char mode) { - struct zip_t* zip = NULL; - - if (!zipname || strlen(zipname) < 1) { - // zip_t archive name is empty or NULL - goto cleanup; - } - - if (level < 0) - level = MZ_DEFAULT_LEVEL; - if ((level & 0xF) > MZ_UBER_COMPRESSION) { - // Wrong compression level - goto cleanup; - } - - zip = (struct zip_t*)calloc((size_t)1, sizeof(struct zip_t)); - if (!zip) - goto cleanup; - - zip->level = (mz_uint)level; - switch (mode) { - case 'w': - // Create a new archive. - if (!mz_zip_writer_init_file_v2(&(zip->archive), zipname, 0, - MZ_ZIP_FLAG_WRITE_ZIP64)) { - // Cannot initialize zip_archive writer - goto cleanup; - } - break; - - case 'r': - case 'a': - case 'd': - if (!mz_zip_reader_init_file_v2_rpb( - &(zip->archive), zipname, - zip->level | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) { - // An archive file does not exist or cannot initialize - // zip_archive reader - goto cleanup; - } - if ((mode == 'a' || mode == 'd')) { - if (!mz_zip_writer_init_from_reader_v2_noreopen(&(zip->archive), zipname, - 0)) { - mz_zip_reader_end(&(zip->archive)); - goto cleanup; - } - } - break; - - default: - goto cleanup; - } - - return zip; - -cleanup: - CLEANUP(zip); - return NULL; -} - -void zip_close(struct zip_t* zip) { - if (zip) { - // Always finalize, even if adding failed for some reason, so we have a - // valid central directory. - mz_zip_writer_finalize_archive(&(zip->archive)); - zip_archive_truncate(&(zip->archive)); - mz_zip_writer_end(&(zip->archive)); - mz_zip_reader_end(&(zip->archive)); - - CLEANUP(zip); - } -} - -int zip_is64(struct zip_t* zip) { - if (!zip || !zip->archive.m_pState) { - // zip_t handler or zip state is not initialized - return ZIP_ENOINIT; - } - - return (int)zip->archive.m_pState->m_zip64; -} - -static int _zip_entry_open(struct zip_t* zip, const char* entryname, - int case_sensitive) { - size_t entrylen = 0; - mz_zip_archive* pzip = NULL; - mz_uint num_alignment_padding_bytes, level; - mz_zip_archive_file_stat stats; - int err = 0; - mz_uint16 dos_time, dos_date; - mz_uint32 extra_size = 0; - mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; - mz_uint64 local_dir_header_ofs = 0; - - if (!zip) { - return ZIP_ENOINIT; - } - - local_dir_header_ofs = zip->archive.m_archive_size; - - if (!entryname) { - return ZIP_EINVENTNAME; - } - - entrylen = strlen(entryname); - if (entrylen == 0) { - return ZIP_EINVENTNAME; - } - - /* - .ZIP File Format Specification Version: 6.3.3 - - 4.4.17.1 The name of the file, with optional relative path. - The path stored MUST not contain a drive or - device letter, or a leading slash. All slashes - MUST be forward slashes '/' as opposed to - backwards slashes '\' for compatibility with Amiga - and UNIX file systems etc. If input came from standard - input, there is no file name field. - */ - if (zip->entry.name) { - CLEANUP(zip->entry.name); - } -#ifdef ZIP_RAW_ENTRYNAME - zip->entry.name = STRCLONE(entryname); -#else - zip->entry.name = zip_strrpl(entryname, entrylen, '\\', '/'); -#endif - - if (!zip->entry.name) { - // Cannot parse zip entry name - return ZIP_EINVENTNAME; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode == MZ_ZIP_MODE_READING) { - zip->entry.index = (ssize_t)mz_zip_reader_locate_file( - pzip, zip->entry.name, NULL, - case_sensitive ? MZ_ZIP_FLAG_CASE_SENSITIVE : 0); - if (zip->entry.index < (ssize_t)0) { - err = ZIP_ENOENT; - goto cleanup; - } - - if (!mz_zip_reader_file_stat(pzip, (mz_uint)zip->entry.index, &stats)) { - err = ZIP_ENOENT; - goto cleanup; - } - - zip->entry.comp_size = stats.m_comp_size; - zip->entry.uncomp_size = stats.m_uncomp_size; - zip->entry.uncomp_crc32 = stats.m_crc32; - zip->entry.offset = stats.m_central_dir_ofs; - zip->entry.header_offset = stats.m_local_header_ofs; - zip->entry.method = stats.m_method; - zip->entry.external_attr = stats.m_external_attr; -#ifndef MINIZ_NO_TIME - zip->entry.m_time = stats.m_time; -#endif - - return 0; - } - - level = zip->level & 0xF; - - zip->entry.index = (ssize_t)zip->archive.m_total_files; - zip->entry.comp_size = 0; - zip->entry.uncomp_size = 0; - zip->entry.uncomp_crc32 = MZ_CRC32_INIT; - zip->entry.offset = zip->archive.m_archive_size; - zip->entry.header_offset = zip->archive.m_archive_size; - memset(zip->entry.header, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE * sizeof(mz_uint8)); - zip->entry.method = level ? MZ_DEFLATED : 0; - - // UNIX or APPLE -#if MZ_PLATFORM == 3 || MZ_PLATFORM == 19 - // regular file with rw-r--r-- permissions - zip->entry.external_attr = (mz_uint32)(0100644) << 16; -#else - zip->entry.external_attr = 0; -#endif - - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment(pzip); - - if (!pzip->m_pState || (pzip->m_zip_mode != MZ_ZIP_MODE_WRITING)) { - // Invalid zip mode - err = ZIP_EINVMODE; - goto cleanup; - } - if (zip->level & MZ_ZIP_FLAG_COMPRESSED_DATA) { - // Invalid zip compression level - err = ZIP_EINVLVL; - goto cleanup; - } - - if (!mz_zip_writer_write_zeros(pzip, zip->entry.offset, - num_alignment_padding_bytes)) { - // Cannot memset zip entry header - err = ZIP_EMEMSET; - goto cleanup; - } - local_dir_header_ofs += num_alignment_padding_bytes; - - zip->entry.m_time = time(NULL); -#ifndef MINIZ_NO_TIME - mz_zip_time_t_to_dos_time(zip->entry.m_time, &dos_time, &dos_date); -#endif - - // ZIP64 header with NULL sizes (sizes will be in the data descriptor, just - // after file data) - extra_size = mz_zip_writer_create_zip64_extra_data( - extra_data, NULL, NULL, - (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); - - if (!mz_zip_writer_create_local_dir_header( - pzip, zip->entry.header, (mz_uint16)entrylen, (mz_uint16)extra_size, 0, 0, 0, - zip->entry.method, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 | - MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR, - dos_time, dos_date)) { - // Cannot create zip entry header - err = ZIP_EMEMSET; - goto cleanup; - } - - zip->entry.header_offset = zip->entry.offset + num_alignment_padding_bytes; - - if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.header_offset, - zip->entry.header, - sizeof(zip->entry.header)) != sizeof(zip->entry.header)) { - // Cannot write zip entry header - err = ZIP_EMEMSET; - goto cleanup; - } - - if (pzip->m_file_offset_alignment) { - MZ_ASSERT( - (zip->entry.header_offset & (pzip->m_file_offset_alignment - 1)) == 0); - } - zip->entry.offset += num_alignment_padding_bytes + sizeof(zip->entry.header); - - if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, zip->entry.name, - entrylen) != entrylen) { - // Cannot write data to zip entry - err = ZIP_EWRTENT; - goto cleanup; - } - - zip->entry.offset += entrylen; - - if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, extra_data, - extra_size) != extra_size) { - // Cannot write ZIP64 data to zip entry - err = ZIP_EWRTENT; - goto cleanup; - } - zip->entry.offset += extra_size; - - if (level) { - zip->entry.state.m_pZip = pzip; - zip->entry.state.m_cur_archive_file_ofs = zip->entry.offset; - zip->entry.state.m_comp_size = 0; - - if (tdefl_init(&(zip->entry.comp), mz_zip_writer_add_put_buf_callback, - &(zip->entry.state), - (int)tdefl_create_comp_flags_from_zip_params( - (int)level, -15, MZ_DEFAULT_STRATEGY)) != - TDEFL_STATUS_OKAY) { - // Cannot initialize the zip compressor - err = ZIP_ETDEFLINIT; - goto cleanup; - } - } - - return 0; - -cleanup: - CLEANUP(zip->entry.name); - return err; -} - -int zip_entry_open(struct zip_t* zip, const char* entryname) { - return _zip_entry_open(zip, entryname, 0); -} - -int zip_entry_opencasesensitive(struct zip_t* zip, const char* entryname) { - return _zip_entry_open(zip, entryname, 1); -} - -int zip_entry_openbyindex(struct zip_t* zip, size_t index) { - mz_zip_archive* pZip = NULL; - mz_zip_archive_file_stat stats; - mz_uint namelen; - const mz_uint8* pHeader; - const char* pFilename; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - pZip = &(zip->archive); - if (pZip->m_zip_mode != MZ_ZIP_MODE_READING) { - // open by index requires readonly mode - return ZIP_EINVMODE; - } - - if (index >= (size_t)pZip->m_total_files) { - // index out of range - return ZIP_EINVIDX; - } - - if (!(pHeader = &MZ_ZIP_ARRAY_ELEMENT( - &pZip->m_pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, - mz_uint32, index)))) { - // cannot find header in central directory - return ZIP_ENOHDR; - } - - namelen = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); - pFilename = (const char*)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - - /* - .ZIP File Format Specification Version: 6.3.3 - - 4.4.17.1 The name of the file, with optional relative path. - The path stored MUST not contain a drive or - device letter, or a leading slash. All slashes - MUST be forward slashes '/' as opposed to - backwards slashes '\' for compatibility with Amiga - and UNIX file systems etc. If input came from standard - input, there is no file name field. - */ - if (zip->entry.name) { - CLEANUP(zip->entry.name); - } -#ifdef ZIP_RAW_ENTRYNAME - zip->entry.name = STRCLONE(pFilename); -#else - zip->entry.name = zip_strrpl(pFilename, namelen, '\\', '/'); -#endif - - if (!zip->entry.name) { - // local entry name is NULL - return ZIP_EINVENTNAME; - } - - if (!mz_zip_reader_file_stat(pZip, (mz_uint)index, &stats)) { - return ZIP_ENOENT; - } - - zip->entry.index = (ssize_t)index; - zip->entry.comp_size = stats.m_comp_size; - zip->entry.uncomp_size = stats.m_uncomp_size; - zip->entry.uncomp_crc32 = stats.m_crc32; - zip->entry.offset = stats.m_central_dir_ofs; - zip->entry.header_offset = stats.m_local_header_ofs; - zip->entry.method = stats.m_method; - zip->entry.external_attr = stats.m_external_attr; -#ifndef MINIZ_NO_TIME - zip->entry.m_time = stats.m_time; -#endif - - return 0; -} - -int zip_entry_close(struct zip_t* zip) { - mz_zip_archive* pzip = NULL; - mz_uint level; - tdefl_status done; - mz_uint16 entrylen; - mz_uint16 dos_time = 0, dos_date = 0; - int err = 0; - mz_uint8* pExtra_data = NULL; - mz_uint32 extra_size = 0; - mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; - mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; - mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; - - if (!zip) { - // zip_t handler is not initialized - err = ZIP_ENOINIT; - goto cleanup; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode == MZ_ZIP_MODE_READING) { - goto cleanup; - } - - level = zip->level & 0xF; - if (level) { - done = tdefl_compress_buffer(&(zip->entry.comp), "", 0, TDEFL_FINISH); - if (done != TDEFL_STATUS_DONE && done != TDEFL_STATUS_OKAY) { - // Cannot flush compressed buffer - err = ZIP_ETDEFLBUF; - goto cleanup; - } - zip->entry.comp_size = zip->entry.state.m_comp_size; - zip->entry.offset = zip->entry.state.m_cur_archive_file_ofs; - zip->entry.method = MZ_DEFLATED; - } - - entrylen = (mz_uint16)strlen(zip->entry.name); -#ifndef MINIZ_NO_TIME - mz_zip_time_t_to_dos_time(zip->entry.m_time, &dos_time, &dos_date); -#endif - - MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); - MZ_WRITE_LE32(local_dir_footer + 4, zip->entry.uncomp_crc32); - MZ_WRITE_LE64(local_dir_footer + 8, zip->entry.comp_size); - MZ_WRITE_LE64(local_dir_footer + 16, zip->entry.uncomp_size); - - if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, local_dir_footer, - local_dir_footer_size) != local_dir_footer_size) { - // Cannot write zip entry header - err = ZIP_EWRTHDR; - goto cleanup; - } - zip->entry.offset += local_dir_footer_size; - - pExtra_data = extra_data; - extra_size = mz_zip_writer_create_zip64_extra_data( - extra_data, - (zip->entry.uncomp_size >= MZ_UINT32_MAX) ? &zip->entry.uncomp_size - : NULL, - (zip->entry.comp_size >= MZ_UINT32_MAX) ? &zip->entry.comp_size : NULL, - (zip->entry.header_offset >= MZ_UINT32_MAX) ? &zip->entry.header_offset - : NULL); - - if ((entrylen) && (zip->entry.name[entrylen - 1] == '/') && - !zip->entry.uncomp_size) { - /* Set DOS Subdirectory attribute bit. */ - zip->entry.external_attr |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; - } - - if (!mz_zip_writer_add_to_central_dir( - pzip, zip->entry.name, entrylen, pExtra_data, (mz_uint16)extra_size, - "", 0, zip->entry.uncomp_size, zip->entry.comp_size, - zip->entry.uncomp_crc32, zip->entry.method, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 | - MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR, - dos_time, dos_date, zip->entry.header_offset, - zip->entry.external_attr, NULL, 0)) { - // Cannot write to zip central dir - err = ZIP_EWRTDIR; - goto cleanup; - } - - pzip->m_total_files++; - pzip->m_archive_size = zip->entry.offset; - -cleanup: - if (zip) { - zip->entry.m_time = 0; - CLEANUP(zip->entry.name); - } - return err; -} - -const char* zip_entry_name(struct zip_t* zip) { - if (!zip) { - // zip_t handler is not initialized - return NULL; - } - - return zip->entry.name; -} - -ssize_t zip_entry_index(struct zip_t* zip) { - if (!zip) { - // zip_t handler is not initialized - return (ssize_t)ZIP_ENOINIT; - } - - return zip->entry.index; -} - -int zip_entry_isdir(struct zip_t* zip) { - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - if (zip->entry.index < (ssize_t)0) { - // zip entry is not opened - return ZIP_EINVIDX; - } - - return (int)mz_zip_reader_is_file_a_directory(&zip->archive, - (mz_uint)zip->entry.index); -} - -unsigned long long zip_entry_size(struct zip_t* zip) { - return zip_entry_uncomp_size(zip); -} - -unsigned long long zip_entry_uncomp_size(struct zip_t* zip) { - return zip ? zip->entry.uncomp_size : 0; -} - -unsigned long long zip_entry_comp_size(struct zip_t* zip) { - return zip ? zip->entry.comp_size : 0; -} - -unsigned int zip_entry_crc32(struct zip_t* zip) { - return zip ? zip->entry.uncomp_crc32 : 0; -} - -int zip_entry_write(struct zip_t* zip, const void* buf, size_t bufsize) { - mz_uint level; - mz_zip_archive* pzip = NULL; - tdefl_status status; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - pzip = &(zip->archive); - if (buf && bufsize > 0) { - zip->entry.uncomp_size += bufsize; - zip->entry.uncomp_crc32 = (mz_uint32)mz_crc32( - zip->entry.uncomp_crc32, (const mz_uint8*)buf, bufsize); - - level = zip->level & 0xF; - if (!level) { - if ((pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, buf, - bufsize) != bufsize)) { - // Cannot write buffer - return ZIP_EWRTENT; - } - zip->entry.offset += bufsize; - zip->entry.comp_size += bufsize; - } - else { - status = tdefl_compress_buffer(&(zip->entry.comp), buf, bufsize, - TDEFL_NO_FLUSH); - if (status != TDEFL_STATUS_DONE && status != TDEFL_STATUS_OKAY) { - // Cannot compress buffer - return ZIP_ETDEFLBUF; - } - } - } - - return 0; -} - -int zip_entry_fwrite(struct zip_t* zip, const char* filename) { - int err = 0; - size_t n = 0; - MZ_FILE* stream = NULL; - mz_uint8 buf[MZ_ZIP_MAX_IO_BUF_SIZE]; - struct MZ_FILE_STAT_STRUCT file_stat; - mz_uint16 modes; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - memset(buf, 0, MZ_ZIP_MAX_IO_BUF_SIZE); - memset((void*)&file_stat, 0, sizeof(struct MZ_FILE_STAT_STRUCT)); - if (MZ_FILE_STAT(filename, &file_stat) != 0) { - // problem getting information - check errno - return ZIP_ENOENT; - } - -#if defined(_WIN32) || defined(__WIN32__) || defined(DJGPP) - (void)modes; // unused -#else - /* Initialize with permission bits--which are not implementation-optional */ - modes = file_stat.st_mode & - (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX); - if (S_ISDIR(file_stat.st_mode)) - modes |= UNX_IFDIR; - if (S_ISREG(file_stat.st_mode)) - modes |= UNX_IFREG; - if (S_ISLNK(file_stat.st_mode)) - modes |= UNX_IFLNK; - if (S_ISBLK(file_stat.st_mode)) - modes |= UNX_IFBLK; - if (S_ISCHR(file_stat.st_mode)) - modes |= UNX_IFCHR; - if (S_ISFIFO(file_stat.st_mode)) - modes |= UNX_IFIFO; - if (S_ISSOCK(file_stat.st_mode)) - modes |= UNX_IFSOCK; - zip->entry.external_attr = (modes << 16) | !(file_stat.st_mode & S_IWUSR); - if ((file_stat.st_mode & S_IFMT) == S_IFDIR) { - zip->entry.external_attr |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; - } -#endif - - zip->entry.m_time = file_stat.st_mtime; - - if (!(stream = MZ_FOPEN(filename, "rb"))) { - // Cannot open filename - return ZIP_EOPNFILE; - } - - while ((n = fread(buf, sizeof(mz_uint8), MZ_ZIP_MAX_IO_BUF_SIZE, stream)) > - 0) { - if (zip_entry_write(zip, buf, n) < 0) { - err = ZIP_EWRTENT; - break; - } - } - fclose(stream); - - return err; -} - -ssize_t zip_entry_read(struct zip_t* zip, void** buf, size_t* bufsize) { - mz_zip_archive* pzip = NULL; - mz_uint idx; - size_t size = 0; - - if (!zip) { - // zip_t handler is not initialized - return (ssize_t)ZIP_ENOINIT; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || - zip->entry.index < (ssize_t)0) { - // the entry is not found or we do not have read access - return (ssize_t)ZIP_ENOENT; - } - - idx = (mz_uint)zip->entry.index; - if (mz_zip_reader_is_file_a_directory(pzip, idx)) { - // the entry is a directory - return (ssize_t)ZIP_EINVENTTYPE; - } - - *buf = mz_zip_reader_extract_to_heap(pzip, idx, &size, 0); - if (*buf && bufsize) { - *bufsize = size; - } - return (ssize_t)size; -} - -ssize_t zip_entry_noallocread(struct zip_t* zip, void* buf, size_t bufsize) { - mz_zip_archive* pzip = NULL; - - if (!zip) { - // zip_t handler is not initialized - return (ssize_t)ZIP_ENOINIT; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || - zip->entry.index < (ssize_t)0) { - // the entry is not found or we do not have read access - return (ssize_t)ZIP_ENOENT; - } - - if (!mz_zip_reader_extract_to_mem_no_alloc(pzip, (mz_uint)zip->entry.index, - buf, bufsize, 0, NULL, 0)) { - return (ssize_t)ZIP_EMEMNOALLOC; - } - - return (ssize_t)zip->entry.uncomp_size; -} - -int zip_entry_fread(struct zip_t* zip, const char* filename) { - mz_zip_archive* pzip = NULL; - mz_uint idx; - mz_uint32 xattr = 0; - mz_zip_archive_file_stat info; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - memset((void*)&info, 0, sizeof(mz_zip_archive_file_stat)); - pzip = &(zip->archive); - if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || - zip->entry.index < (ssize_t)0) { - // the entry is not found or we do not have read access - return ZIP_ENOENT; - } - - idx = (mz_uint)zip->entry.index; - if (mz_zip_reader_is_file_a_directory(pzip, idx)) { - // the entry is a directory - return ZIP_EINVENTTYPE; - } - - if (!mz_zip_reader_extract_to_file(pzip, idx, filename, 0)) { - return ZIP_ENOFILE; - } - -#if defined(_MSC_VER) || defined(PS4) - (void)xattr; // unused -#else - if (!mz_zip_reader_file_stat(pzip, idx, &info)) { - // Cannot get information about zip archive; - return ZIP_ENOFILE; - } - - xattr = (info.m_external_attr >> 16) & 0xFFFF; - if (xattr > 0 && xattr <= MZ_UINT16_MAX) { - if (CHMOD(filename, (mode_t)xattr) < 0) { - return ZIP_ENOPERM; - } - } -#endif - - return 0; -} - -int zip_entry_extract(struct zip_t* zip, - size_t(*on_extract)(void* arg, uint64_t offset, - const void* buf, size_t bufsize), - void* arg) { - mz_zip_archive* pzip = NULL; - mz_uint idx; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || - zip->entry.index < (ssize_t)0) { - // the entry is not found or we do not have read access - return ZIP_ENOENT; - } - - idx = (mz_uint)zip->entry.index; - return (mz_zip_reader_extract_to_callback(pzip, idx, on_extract, arg, 0)) - ? 0 - : ZIP_EINVIDX; -} - -ssize_t zip_entries_total(struct zip_t* zip) { - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - return (ssize_t)zip->archive.m_total_files; -} - -ssize_t zip_entries_delete(struct zip_t* zip, char* const entries[], - size_t len) { - ssize_t n = 0; - ssize_t err = 0; - struct zip_entry_mark_t* entry_mark = NULL; - - if (zip == NULL || (entries == NULL && len != 0)) { - return ZIP_ENOINIT; - } - - if (entries == NULL && len == 0) { - return 0; - } - - n = zip_entries_total(zip); - - entry_mark = (struct zip_entry_mark_t*)calloc( - (size_t)n, sizeof(struct zip_entry_mark_t)); - if (!entry_mark) { - return ZIP_EOOMEM; - } - - zip->archive.m_zip_mode = MZ_ZIP_MODE_READING; - - err = zip_entry_set(zip, entry_mark, n, entries, len); - if (err < 0) { - CLEANUP(entry_mark); - return err; - } - - err = zip_entries_delete_mark(zip, entry_mark, (int)n); - CLEANUP(entry_mark); - return err; -} - -int zip_stream_extract(const char* stream, size_t size, const char* dir, - int (*on_extract)(const char* filename, void* arg), - void* arg) { - mz_zip_archive zip_archive; - if (!stream || !dir) { - // Cannot parse zip archive stream - return ZIP_ENOINIT; - } - if (!memset(&zip_archive, 0, sizeof(mz_zip_archive))) { - // Cannot memset zip archive - return ZIP_EMEMSET; - } - if (!mz_zip_reader_init_mem(&zip_archive, stream, size, 0)) { - // Cannot initialize zip_archive reader - return ZIP_ENOINIT; - } - - return zip_archive_extract(&zip_archive, dir, on_extract, arg); -} - -struct zip_t* zip_stream_open(const char* stream, size_t size, int level, - char mode) { - struct zip_t* zip = (struct zip_t*)calloc((size_t)1, sizeof(struct zip_t)); - if (!zip) { - return NULL; - } - - if (level < 0) { - level = MZ_DEFAULT_LEVEL; - } - if ((level & 0xF) > MZ_UBER_COMPRESSION) { - // Wrong compression level - goto cleanup; - } - zip->level = (mz_uint)level; - - if ((stream != NULL) && (size > 0) && (mode == 'r')) { - if (!mz_zip_reader_init_mem(&(zip->archive), stream, size, 0)) { - goto cleanup; - } - } - else if ((stream == NULL) && (size == 0) && (mode == 'w')) { - // Create a new archive. - if (!mz_zip_writer_init_heap(&(zip->archive), 0, 1024)) { - // Cannot initialize zip_archive writer - goto cleanup; - } - } - else { - goto cleanup; - } - return zip; - -cleanup: - CLEANUP(zip); - return NULL; -} - -ssize_t zip_stream_copy(struct zip_t* zip, void** buf, size_t* bufsize) { - size_t n; - - if (!zip) { - return (ssize_t)ZIP_ENOINIT; - } - zip_archive_finalize(&(zip->archive)); - - n = (size_t)zip->archive.m_archive_size; - if (bufsize != NULL) { - *bufsize = n; - } - - *buf = calloc(sizeof(unsigned char), n); - memcpy(*buf, zip->archive.m_pState->m_pMem, n); - - return (ssize_t)n; -} - -void zip_stream_close(struct zip_t* zip) { - if (zip) { - mz_zip_writer_end(&(zip->archive)); - mz_zip_reader_end(&(zip->archive)); - CLEANUP(zip); - } -} - -int zip_create(const char* zipname, const char* filenames[], size_t len) { - int err = 0; - size_t i; - mz_zip_archive zip_archive; - struct MZ_FILE_STAT_STRUCT file_stat; - mz_uint32 ext_attributes = 0; - mz_uint16 modes; - - if (!zipname || strlen(zipname) < 1) { - // zip_t archive name is empty or NULL - return ZIP_EINVZIPNAME; - } - - // Create a new archive. - if (!memset(&(zip_archive), 0, sizeof(zip_archive))) { - // Cannot memset zip archive - return ZIP_EMEMSET; - } - - if (!mz_zip_writer_init_file(&zip_archive, zipname, 0)) { - // Cannot initialize zip_archive writer - return ZIP_ENOINIT; - } - - if (!memset((void*)&file_stat, 0, sizeof(struct MZ_FILE_STAT_STRUCT))) { - return ZIP_EMEMSET; - } - - for (i = 0; i < len; ++i) { - const char* name = filenames[i]; - if (!name) { - err = ZIP_EINVENTNAME; - break; - } - - if (MZ_FILE_STAT(name, &file_stat) != 0) { - // problem getting information - check errno - err = ZIP_ENOFILE; - break; - } - -#if defined(_WIN32) || defined(__WIN32__) || defined(DJGPP) - (void)modes; // unused -#else - - /* Initialize with permission bits--which are not implementation-optional */ - modes = file_stat.st_mode & - (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX); - if (S_ISDIR(file_stat.st_mode)) - modes |= UNX_IFDIR; - if (S_ISREG(file_stat.st_mode)) - modes |= UNX_IFREG; - if (S_ISLNK(file_stat.st_mode)) - modes |= UNX_IFLNK; - if (S_ISBLK(file_stat.st_mode)) - modes |= UNX_IFBLK; - if (S_ISCHR(file_stat.st_mode)) - modes |= UNX_IFCHR; - if (S_ISFIFO(file_stat.st_mode)) - modes |= UNX_IFIFO; - if (S_ISSOCK(file_stat.st_mode)) - modes |= UNX_IFSOCK; - ext_attributes = (modes << 16) | !(file_stat.st_mode & S_IWUSR); - if ((file_stat.st_mode & S_IFMT) == S_IFDIR) { - ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; - } -#endif - - if (!mz_zip_writer_add_file(&zip_archive, zip_basename(name), name, "", 0, - ZIP_DEFAULT_COMPRESSION_LEVEL, - ext_attributes)) { - // Cannot add file to zip_archive - err = ZIP_ENOFILE; - break; - } - } - - mz_zip_writer_finalize_archive(&zip_archive); - mz_zip_writer_end(&zip_archive); - return err; -} - -int zip_extract(const char* zipname, const char* dir, - int (*on_extract)(const char* filename, void* arg), void* arg) { - mz_zip_archive zip_archive; - - if (!zipname || !dir) { - // Cannot parse zip archive name - return ZIP_EINVZIPNAME; - } - - if (!memset(&zip_archive, 0, sizeof(mz_zip_archive))) { - // Cannot memset zip archive - return ZIP_EMEMSET; - } - - // Now try to open the archive. - if (!mz_zip_reader_init_file(&zip_archive, zipname, 0)) { - // Cannot initialize zip_archive reader - return ZIP_ENOINIT; - } - - return zip_archive_extract(&zip_archive, dir, on_extract, arg); -} diff --git a/Update/Zip.h b/Update/Zip.h deleted file mode 100644 index 0b771b6..0000000 --- a/Update/Zip.h +++ /dev/null @@ -1,448 +0,0 @@ -/* - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#ifndef ZIP_H -#define ZIP_H -//#include "public/define.h" -#include -#include -#include - - -#if !defined(_POSIX_C_SOURCE) && defined(_MSC_VER) - // 64-bit Windows is the only mainstream platform - // where sizeof(long) != sizeof(void*) -#ifdef _WIN64 -typedef long long ssize_t; /* byte count or error */ -#else -typedef long ssize_t; /* byte count or error */ -#endif -#endif - -#ifndef MAX_PATH -#define MAX_PATH 1024 /* # chars in a path name including NULL */ -#endif - -/** - * @mainpage - * - * Documenation for @ref zip. - */ - - /** - * @addtogroup zip - * @{ - */ - - /** - * Default zip compression level. - */ -#define ZIP_DEFAULT_COMPRESSION_LEVEL 6 - - /** - * Error codes - */ -#define ZIP_ENOINIT -1 // not initialized -#define ZIP_EINVENTNAME -2 // invalid entry name -#define ZIP_ENOENT -3 // entry not found -#define ZIP_EINVMODE -4 // invalid zip mode -#define ZIP_EINVLVL -5 // invalid compression level -#define ZIP_ENOSUP64 -6 // no zip 64 support -#define ZIP_EMEMSET -7 // memset error -#define ZIP_EWRTENT -8 // cannot write data to entry -#define ZIP_ETDEFLINIT -9 // cannot initialize tdefl compressor -#define ZIP_EINVIDX -10 // invalid index -#define ZIP_ENOHDR -11 // header not found -#define ZIP_ETDEFLBUF -12 // cannot flush tdefl buffer -#define ZIP_ECRTHDR -13 // cannot create entry header -#define ZIP_EWRTHDR -14 // cannot write entry header -#define ZIP_EWRTDIR -15 // cannot write to central dir -#define ZIP_EOPNFILE -16 // cannot open file -#define ZIP_EINVENTTYPE -17 // invalid entry type -#define ZIP_EMEMNOALLOC -18 // extracting data using no memory allocation -#define ZIP_ENOFILE -19 // file not found -#define ZIP_ENOPERM -20 // no permission -#define ZIP_EOOMEM -21 // out of memory -#define ZIP_EINVZIPNAME -22 // invalid zip archive name -#define ZIP_EMKDIR -23 // make dir error -#define ZIP_ESYMLINK -24 // symlink error -#define ZIP_ECLSZIP -25 // close archive error -#define ZIP_ECAPSIZE -26 // capacity size too small -#define ZIP_EFSEEK -27 // fseek error -#define ZIP_EFREAD -28 // fread error -#define ZIP_EFWRITE -29 // fwrite error - - /** - * Looks up the error message string coresponding to an error number. - * @param errnum error number - * @return error message string coresponding to errnum or NULL if error is not - * found. - */ -const char* zip_strerror(int errnum); - -/** - * @struct zip_t - * - * This data structure is used throughout the library to represent zip archive - - * forward declaration. - */ -struct zip_t; - -/** - * Opens zip archive with compression level using the given mode. - * - * @param zipname zip archive file name. - * @param level compression level (0-9 are the standard zlib-style levels). - * @param mode file access mode. - * - 'r': opens a file for reading/extracting (the file must exists). - * - 'w': creates an empty file for writing. - * - 'a': appends to an existing archive. - * - * @return the zip archive handler or NULL on error - */ -struct zip_t* zip_open(const char* zipname, int level, - char mode); - -/** - * Closes the zip archive, releases resources - always finalize. - * - * @param zip zip archive handler. - */ -void zip_close(struct zip_t* zip); - -/** - * Determines if the archive has a zip64 end of central directory headers. - * - * @param zip zip archive handler. - * - * @return the return code - 1 (true), 0 (false), negative number (< 0) on - * error. - */ -int zip_is64(struct zip_t* zip); - -/** - * Opens an entry by name in the zip archive. - * - * For zip archive opened in 'w' or 'a' mode the function will append - * a new entry. In readonly mode the function tries to locate the entry - * in global dictionary. - * - * @param zip zip archive handler. - * @param entryname an entry name in local dictionary. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_entry_open(struct zip_t* zip, const char* entryname); - -/** - * Opens an entry by name in the zip archive. - * - * For zip archive opened in 'w' or 'a' mode the function will append - * a new entry. In readonly mode the function tries to locate the entry - * in global dictionary (case sensitive). - * - * @param zip zip archive handler. - * @param entryname an entry name in local dictionary (case sensitive). - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_entry_opencasesensitive(struct zip_t* zip, - const char* entryname); - -/** - * Opens a new entry by index in the zip archive. - * - * This function is only valid if zip archive was opened in 'r' (readonly) mode. - * - * @param zip zip archive handler. - * @param index index in local dictionary. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_entry_openbyindex(struct zip_t* zip, size_t index); - -/** - * Closes a zip entry, flushes buffer and releases resources. - * - * @param zip zip archive handler. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_entry_close(struct zip_t* zip); - -/** - * Returns a local name of the current zip entry. - * - * The main difference between user's entry name and local entry name - * is optional relative path. - * Following .ZIP File Format Specification - the path stored MUST not contain - * a drive or device letter, or a leading slash. - * All slashes MUST be forward slashes '/' as opposed to backwards slashes '\' - * for compatibility with Amiga and UNIX file systems etc. - * - * @param zip: zip archive handler. - * - * @return the pointer to the current zip entry name, or NULL on error. - */ -const char* zip_entry_name(struct zip_t* zip); - -/** - * Returns an index of the current zip entry. - * - * @param zip zip archive handler. - * - * @return the index on success, negative number (< 0) on error. - */ -ssize_t zip_entry_index(struct zip_t* zip); - -/** - * Determines if the current zip entry is a directory entry. - * - * @param zip zip archive handler. - * - * @return the return code - 1 (true), 0 (false), negative number (< 0) on - * error. - */ -int zip_entry_isdir(struct zip_t* zip); - -/** - * Returns the uncompressed size of the current zip entry. - * Alias for zip_entry_uncomp_size (for backward compatibility). - * - * @param zip zip archive handler. - * - * @return the uncompressed size in bytes. - */ -unsigned long long zip_entry_size(struct zip_t* zip); - -/** - * Returns the uncompressed size of the current zip entry. - * - * @param zip zip archive handler. - * - * @return the uncompressed size in bytes. - */ -unsigned long long zip_entry_uncomp_size(struct zip_t* zip); - -/** - * Returns the compressed size of the current zip entry. - * - * @param zip zip archive handler. - * - * @return the compressed size in bytes. - */ -unsigned long long zip_entry_comp_size(struct zip_t* zip); - -/** - * Returns CRC-32 checksum of the current zip entry. - * - * @param zip zip archive handler. - * - * @return the CRC-32 checksum. - */ -unsigned int zip_entry_crc32(struct zip_t* zip); - -/** - * Compresses an input buffer for the current zip entry. - * - * @param zip zip archive handler. - * @param buf input buffer. - * @param bufsize input buffer size (in bytes). - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_entry_write(struct zip_t* zip, const void* buf, - size_t bufsize); - -/** - * Compresses a file for the current zip entry. - * - * @param zip zip archive handler. - * @param filename input file. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_entry_fwrite(struct zip_t* zip, const char* filename); - -/** - * Extracts the current zip entry into output buffer. - * - * The function allocates sufficient memory for a output buffer. - * - * @param zip zip archive handler. - * @param buf output buffer. - * @param bufsize output buffer size (in bytes). - * - * @note remember to release memory allocated for a output buffer. - * for large entries, please take a look at zip_entry_extract function. - * - * @return the return code - the number of bytes actually read on success. - * Otherwise a negative number (< 0) on error. - */ -ssize_t zip_entry_read(struct zip_t* zip, void** buf, - size_t* bufsize); - -/** - * Extracts the current zip entry into a memory buffer using no memory - * allocation. - * - * @param zip zip archive handler. - * @param buf preallocated output buffer. - * @param bufsize output buffer size (in bytes). - * - * @note ensure supplied output buffer is large enough. - * zip_entry_size function (returns uncompressed size for the current - * entry) can be handy to estimate how big buffer is needed. - * For large entries, please take a look at zip_entry_extract function. - * - * @return the return code - the number of bytes actually read on success. - * Otherwise a negative number (< 0) on error (e.g. bufsize is not large - * enough). - */ -ssize_t zip_entry_noallocread(struct zip_t* zip, void* buf, - size_t bufsize); - -/** - * Extracts the current zip entry into output file. - * - * @param zip zip archive handler. - * @param filename output file. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_entry_fread(struct zip_t* zip, const char* filename); - -/** - * Extracts the current zip entry using a callback function (on_extract). - * - * @param zip zip archive handler. - * @param on_extract callback function. - * @param arg opaque pointer (optional argument, which you can pass to the - * on_extract callback) - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int -zip_entry_extract(struct zip_t* zip, - size_t(*on_extract)(void* arg, uint64_t offset, - const void* data, size_t size), - void* arg); - -/** - * Returns the number of all entries (files and directories) in the zip archive. - * - * @param zip zip archive handler. - * - * @return the return code - the number of entries on success, negative number - * (< 0) on error. - */ -ssize_t zip_entries_total(struct zip_t* zip); - -/** - * Deletes zip archive entries. - * - * @param zip zip archive handler. - * @param entries array of zip archive entries to be deleted. - * @param len the number of entries to be deleted. - * @return the number of deleted entries, or negative number (< 0) on error. - */ -ssize_t zip_entries_delete(struct zip_t* zip, - char* const entries[], size_t len); - -/** - * Extracts a zip archive stream into directory. - * - * If on_extract is not NULL, the callback will be called after - * successfully extracted each zip entry. - * Returning a negative value from the callback will cause abort and return an - * error. The last argument (void *arg) is optional, which you can use to pass - * data to the on_extract callback. - * - * @param stream zip archive stream. - * @param size stream size. - * @param dir output directory. - * @param on_extract on extract callback. - * @param arg opaque pointer. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int -zip_stream_extract(const char* stream, size_t size, const char* dir, - int (*on_extract)(const char* filename, void* arg), - void* arg); - -/** - * Opens zip archive stream into memory. - * - * @param stream zip archive stream. - * @param size stream size. - * - * @return the zip archive handler or NULL on error - */ -struct zip_t* zip_stream_open(const char* stream, size_t size, - int level, char mode); - -/** - * Copy zip archive stream output buffer. - * - * @param zip zip archive handler. - * @param buf output buffer. User should free buf. - * @param bufsize output buffer size (in bytes). - * - * @return copy size - */ -ssize_t zip_stream_copy(struct zip_t* zip, void** buf, - size_t* bufsize); - -/** - * Close zip archive releases resources. - * - * @param zip zip archive handler. - * - * @return - */ -void zip_stream_close(struct zip_t* zip); - -/** - * Creates a new archive and puts files into a single zip archive. - * - * @param zipname zip archive file. - * @param filenames input files. - * @param len: number of input files. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_create(const char* zipname, const char* filenames[], - size_t len); - -/** - * Extracts a zip archive file into directory. - * - * If on_extract_entry is not NULL, the callback will be called after - * successfully extracted each zip entry. - * Returning a negative value from the callback will cause abort and return an - * error. The last argument (void *arg) is optional, which you can use to pass - * data to the on_extract_entry callback. - * - * @param zipname zip archive file. - * @param dir output directory. - * @param on_extract_entry on extract callback. - * @param arg opaque pointer. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -int zip_extract(const char* zipname, const char* dir, - int (*on_extract_entry)(const char* filename, - void* arg), - void* arg); - - -#endif diff --git a/Update/main.cpp b/Update/main.cpp index 0207423..04de33b 100644 --- a/Update/main.cpp +++ b/Update/main.cpp @@ -1,13 +1,120 @@ -#include "Update.h" -#include -#include -#include -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); +#define NOMINMAX - QStringList list_parm = QCoreApplication::arguments(); - Update w; - w.show(); - return a.exec(); +#include + +#include +#include +#include +#include + +#include "Api.h" +#include "Config.h" +#include "UpdateWindow.h" +#include "Utils.h" + +#pragma comment(lib, "shell32.lib") + +namespace { + +void PrintUtf8(const std::wstring& text) { + if (text.empty()) return; + int need = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast(text.size()), + nullptr, 0, nullptr, nullptr); + if (need <= 0) return; + std::string utf8(static_cast(need), '\0'); + WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast(text.size()), + &utf8[0], need, nullptr, nullptr); + fwrite(utf8.data(), 1, utf8.size(), stderr); + fputc('\n', stderr); +} + +std::wstring ArgValue(const std::vector& args, size_t& i, + const wchar_t* longName, const wchar_t* shortName) { + std::wstring arg = args[i]; + size_t eq = arg.find(L'='); + std::wstring name = (eq == std::wstring::npos) ? arg : arg.substr(0, eq); + if (name != longName && name != shortName) return std::wstring(); + + if (eq != std::wstring::npos) return arg.substr(eq + 1); + if (i + 1 < args.size()) { + ++i; + return args[i]; + } + return std::wstring(); +} + +} + +int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE /*prev*/, LPWSTR /*cmdLine*/, int /*show*/) { + int count = 0; + LPWSTR* raw = CommandLineToArgvW(GetCommandLineW(), &count); + + std::vector args; + for (int i = 1; i < count; ++i) args.push_back(raw[i]); + LocalFree(raw); + + // --check-only / -c:静默检查版本,不创建窗口,结果用退出码回传给主程序 + bool checkOnly = false; + for (size_t i = 0; i < args.size(); ) { + if (args[i] == L"--check-only" || args[i] == L"-c") { + checkOnly = true; + args.erase(args.begin() + i); + } else { + ++i; + } + } + + updater::UpdateOptions options; + options.appKey = UPDATER_APP_KEY; + options.targetDir = UPDATER_TARGET_DIR; + + // 无命令行参数 = 完整包更新;有参数则按传入信息检查版本并更新补丁包 + if (args.empty()) { + options.fullMode = true; + } else { + std::vector positional; + for (size_t i = 0; i < args.size(); ++i) { + std::wstring key = updater::Utils::Trim(ArgValue(args, i, L"--app-key", L"-k")); + if (!key.empty()) { options.appKey = key; continue; } + + std::wstring ver = updater::Utils::Trim(ArgValue(args, i, L"--version", L"-v")); + if (!ver.empty()) { options.clientVersion = ver; continue; } + + std::wstring dir = updater::Utils::Trim(ArgValue(args, i, L"--dir", L"-d")); + if (!dir.empty()) { options.targetDir = dir; continue; } + + std::wstring launch = updater::Utils::Trim(ArgValue(args, i, L"--launch", L"-l")); + if (!launch.empty()) { options.launchExe = launch; continue; } + + if (!args[i].empty() && args[i][0] != L'-') positional.push_back(args[i]); + } + + if (positional.size() >= 1) options.appKey = positional[0]; + if (positional.size() >= 2) options.clientVersion = positional[1]; + if (positional.size() >= 3) options.targetDir = positional[2]; + + options.fullMode = options.clientVersion.empty(); + } + + if (checkOnly) { + if (options.appKey.empty() || options.clientVersion.empty()) return UPDATER_EXIT_FAILED; + updater::Api::Result result = + updater::Api::CheckUpdate(options.appKey, options.clientVersion); + if (!result.ok) { + // 命令行下排查用,主程序拉起时看不到 + PrintUtf8(result.error); + // 400 是服务端拒绝了版本参数(版本表里没有这个版本),补丁包无从生成, + // 只能让主程序走完整包重装,跟网络故障区分开 + if (result.httpStatus == 400) return UPDATER_EXIT_BAD_VERSION; + return UPDATER_EXIT_FAILED; + } + return result.info.hasUpdate ? UPDATER_EXIT_HAS_UPDATE : UPDATER_EXIT_NO_UPDATE; + } + + updater::UpdateWindow window; + if (!window.Create(instance, options)) { + MessageBoxW(nullptr, L"无法创建更新窗口", UPDATER_TITLE, MB_ICONERROR | MB_OK); + return 1; + } + return window.MessageLoop(); } diff --git a/Update/resource.h b/Update/resource.h index a77d67d..6313e76 100644 --- a/Update/resource.h +++ b/Update/resource.h @@ -2,11 +2,17 @@ // Microsoft Visual C++ generated include file. // Used by Update.rc +// 更新器自绘资源(GDI+ 从 RCDATA 加载) +#define IDR_BG 101 +#define IDR_CLOSE_NORMAL 102 +#define IDR_CLOSE_HOVER 103 +#define IDR_CLOSE_PRESS 104 + // 新对象的下一组默认值 // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_RESOURCE_VALUE 105 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101