updater.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690
  1. /*
  2. * Copyright (c) 2017-2018 Hugh Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include "updater.hpp"
  17. #include <psapi.h>
  18. #include <util/windows/CoTaskMemPtr.hpp>
  19. #include <future>
  20. #include <vector>
  21. #include <string>
  22. #include <mutex>
  23. using namespace std;
  24. /* ----------------------------------------------------------------------- */
  25. HANDLE cancelRequested = nullptr;
  26. HANDLE updateThread = nullptr;
  27. HINSTANCE hinstMain = nullptr;
  28. HWND hwndMain = nullptr;
  29. HCRYPTPROV hProvider = 0;
  30. static bool bExiting = false;
  31. static bool updateFailed = false;
  32. static bool is32bit = false;
  33. static bool downloadThreadFailure = false;
  34. int totalFileSize = 0;
  35. int completedFileSize = 0;
  36. static int completedUpdates = 0;
  37. struct LastError {
  38. DWORD code;
  39. inline LastError() { code = GetLastError(); }
  40. };
  41. void FreeWinHttpHandle(HINTERNET handle)
  42. {
  43. WinHttpCloseHandle(handle);
  44. }
  45. /* ----------------------------------------------------------------------- */
  46. static inline bool is_64bit_windows(void);
  47. static inline bool HasVS2017Redist2()
  48. {
  49. wchar_t base[MAX_PATH];
  50. wchar_t path[MAX_PATH];
  51. WIN32_FIND_DATAW wfd;
  52. HANDLE handle;
  53. int folder = (is32bit && is_64bit_windows()) ? CSIDL_SYSTEMX86
  54. : CSIDL_SYSTEM;
  55. SHGetFolderPathW(NULL, folder, NULL, SHGFP_TYPE_CURRENT, base);
  56. StringCbCopyW(path, sizeof(path), base);
  57. StringCbCatW(path, sizeof(path), L"\\msvcp140.dll");
  58. handle = FindFirstFileW(path, &wfd);
  59. if (handle == INVALID_HANDLE_VALUE) {
  60. return false;
  61. } else {
  62. FindClose(handle);
  63. }
  64. StringCbCopyW(path, sizeof(path), base);
  65. StringCbCatW(path, sizeof(path), L"\\vcruntime140.dll");
  66. handle = FindFirstFileW(path, &wfd);
  67. if (handle == INVALID_HANDLE_VALUE) {
  68. return false;
  69. } else {
  70. FindClose(handle);
  71. }
  72. return true;
  73. }
  74. static bool HasVS2017Redist()
  75. {
  76. PVOID old = nullptr;
  77. bool redirect = !!Wow64DisableWow64FsRedirection(&old);
  78. bool success = HasVS2017Redist2();
  79. if (redirect)
  80. Wow64RevertWow64FsRedirection(old);
  81. return success;
  82. }
  83. static void Status(const wchar_t *fmt, ...)
  84. {
  85. wchar_t str[512];
  86. va_list argptr;
  87. va_start(argptr, fmt);
  88. StringCbVPrintf(str, sizeof(str), fmt, argptr);
  89. SetDlgItemText(hwndMain, IDC_STATUS, str);
  90. va_end(argptr);
  91. }
  92. static void CreateFoldersForPath(const wchar_t *path)
  93. {
  94. wchar_t *p = (wchar_t *)path;
  95. while (*p) {
  96. if (*p == '\\' || *p == '/') {
  97. *p = 0;
  98. CreateDirectory(path, nullptr);
  99. *p = '\\';
  100. }
  101. p++;
  102. }
  103. }
  104. static bool MyCopyFile(const wchar_t *src, const wchar_t *dest)
  105. try {
  106. WinHandle hSrc;
  107. WinHandle hDest;
  108. hSrc = CreateFile(src, GENERIC_READ, 0, nullptr, OPEN_EXISTING,
  109. FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
  110. if (!hSrc.Valid())
  111. throw LastError();
  112. hDest = CreateFile(dest, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0,
  113. nullptr);
  114. if (!hDest.Valid())
  115. throw LastError();
  116. BYTE buf[65536];
  117. DWORD read, wrote;
  118. for (;;) {
  119. if (!ReadFile(hSrc, buf, sizeof(buf), &read, nullptr))
  120. throw LastError();
  121. if (read == 0)
  122. break;
  123. if (!WriteFile(hDest, buf, read, &wrote, nullptr))
  124. throw LastError();
  125. if (wrote != read)
  126. return false;
  127. }
  128. return true;
  129. } catch (LastError error) {
  130. SetLastError(error.code);
  131. return false;
  132. }
  133. static bool IsSafeFilename(const wchar_t *path)
  134. {
  135. const wchar_t *p = path;
  136. if (!*p)
  137. return false;
  138. if (wcsstr(path, L".."))
  139. return false;
  140. if (*p == '/')
  141. return false;
  142. while (*p) {
  143. if (!isalnum(*p) && *p != '.' && *p != '/' && *p != '_' &&
  144. *p != '-')
  145. return false;
  146. p++;
  147. }
  148. return true;
  149. }
  150. static string QuickReadFile(const wchar_t *path)
  151. {
  152. string data;
  153. WinHandle handle = CreateFileW(path, GENERIC_READ, 0, nullptr,
  154. OPEN_EXISTING, 0, nullptr);
  155. if (!handle.Valid()) {
  156. return string();
  157. }
  158. LARGE_INTEGER size;
  159. if (!GetFileSizeEx(handle, &size)) {
  160. return string();
  161. }
  162. data.resize((size_t)size.QuadPart);
  163. DWORD read;
  164. if (!ReadFile(handle, &data[0], (DWORD)data.size(), &read, nullptr)) {
  165. return string();
  166. }
  167. if (read != size.QuadPart) {
  168. return string();
  169. }
  170. return data;
  171. }
  172. /* ----------------------------------------------------------------------- */
  173. enum state_t {
  174. STATE_INVALID,
  175. STATE_PENDING_DOWNLOAD,
  176. STATE_DOWNLOADING,
  177. STATE_DOWNLOADED,
  178. STATE_INSTALL_FAILED,
  179. STATE_INSTALLED,
  180. };
  181. struct update_t {
  182. wstring sourceURL;
  183. wstring outputPath;
  184. wstring tempPath;
  185. wstring previousFile;
  186. wstring basename;
  187. string packageName;
  188. DWORD fileSize = 0;
  189. BYTE hash[BLAKE2_HASH_LENGTH];
  190. BYTE downloadhash[BLAKE2_HASH_LENGTH];
  191. BYTE my_hash[BLAKE2_HASH_LENGTH];
  192. state_t state = STATE_INVALID;
  193. bool has_hash = false;
  194. bool patchable = false;
  195. inline update_t() {}
  196. inline update_t(const update_t &from)
  197. : sourceURL(from.sourceURL),
  198. outputPath(from.outputPath),
  199. tempPath(from.tempPath),
  200. previousFile(from.previousFile),
  201. basename(from.basename),
  202. packageName(from.packageName),
  203. fileSize(from.fileSize),
  204. state(from.state),
  205. has_hash(from.has_hash),
  206. patchable(from.patchable)
  207. {
  208. memcpy(hash, from.hash, sizeof(hash));
  209. memcpy(downloadhash, from.downloadhash, sizeof(downloadhash));
  210. memcpy(my_hash, from.my_hash, sizeof(my_hash));
  211. }
  212. inline update_t(update_t &&from)
  213. : sourceURL(std::move(from.sourceURL)),
  214. outputPath(std::move(from.outputPath)),
  215. tempPath(std::move(from.tempPath)),
  216. previousFile(std::move(from.previousFile)),
  217. basename(std::move(from.basename)),
  218. packageName(std::move(from.packageName)),
  219. fileSize(from.fileSize),
  220. state(from.state),
  221. has_hash(from.has_hash),
  222. patchable(from.patchable)
  223. {
  224. from.state = STATE_INVALID;
  225. memcpy(hash, from.hash, sizeof(hash));
  226. memcpy(downloadhash, from.downloadhash, sizeof(downloadhash));
  227. memcpy(my_hash, from.my_hash, sizeof(my_hash));
  228. }
  229. void CleanPartialUpdate()
  230. {
  231. if (state == STATE_INSTALL_FAILED || state == STATE_INSTALLED) {
  232. if (!previousFile.empty()) {
  233. DeleteFile(outputPath.c_str());
  234. MyCopyFile(previousFile.c_str(),
  235. outputPath.c_str());
  236. DeleteFile(previousFile.c_str());
  237. } else {
  238. DeleteFile(outputPath.c_str());
  239. }
  240. } else if (state == STATE_DOWNLOADED) {
  241. DeleteFile(tempPath.c_str());
  242. }
  243. }
  244. inline update_t &operator=(const update_t &from)
  245. {
  246. sourceURL = from.sourceURL;
  247. outputPath = from.outputPath;
  248. tempPath = from.tempPath;
  249. previousFile = from.previousFile;
  250. basename = from.basename;
  251. packageName = from.packageName;
  252. fileSize = from.fileSize;
  253. state = from.state;
  254. has_hash = from.has_hash;
  255. patchable = from.patchable;
  256. memcpy(hash, from.hash, sizeof(hash));
  257. memcpy(downloadhash, from.downloadhash, sizeof(downloadhash));
  258. memcpy(my_hash, from.my_hash, sizeof(my_hash));
  259. return *this;
  260. }
  261. };
  262. static vector<update_t> updates;
  263. static mutex updateMutex;
  264. static inline void CleanupPartialUpdates()
  265. {
  266. for (update_t &update : updates)
  267. update.CleanPartialUpdate();
  268. }
  269. /* ----------------------------------------------------------------------- */
  270. bool DownloadWorkerThread()
  271. {
  272. const DWORD tlsProtocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
  273. HttpHandle hSession = WinHttpOpen(L"OBS Studio Updater/2.1",
  274. WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
  275. WINHTTP_NO_PROXY_NAME,
  276. WINHTTP_NO_PROXY_BYPASS, 0);
  277. if (!hSession) {
  278. downloadThreadFailure = true;
  279. Status(L"Update failed: Couldn't open obsproject.com");
  280. return false;
  281. }
  282. WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS,
  283. (LPVOID)&tlsProtocols, sizeof(tlsProtocols));
  284. HttpHandle hConnect = WinHttpConnect(hSession,
  285. L"cdn-fastly.obsproject.com",
  286. INTERNET_DEFAULT_HTTPS_PORT, 0);
  287. if (!hConnect) {
  288. downloadThreadFailure = true;
  289. Status(L"Update failed: Couldn't connect to cdn-fastly.obsproject.com");
  290. return false;
  291. }
  292. for (;;) {
  293. bool foundWork = false;
  294. unique_lock<mutex> ulock(updateMutex);
  295. for (update_t &update : updates) {
  296. int responseCode;
  297. DWORD waitResult =
  298. WaitForSingleObject(cancelRequested, 0);
  299. if (waitResult == WAIT_OBJECT_0) {
  300. return false;
  301. }
  302. if (update.state != STATE_PENDING_DOWNLOAD)
  303. continue;
  304. update.state = STATE_DOWNLOADING;
  305. ulock.unlock();
  306. foundWork = true;
  307. if (downloadThreadFailure) {
  308. return false;
  309. }
  310. Status(L"Downloading %s", update.outputPath.c_str());
  311. if (!HTTPGetFile(hConnect, update.sourceURL.c_str(),
  312. update.tempPath.c_str(),
  313. L"Accept-Encoding: gzip",
  314. &responseCode)) {
  315. downloadThreadFailure = true;
  316. DeleteFile(update.tempPath.c_str());
  317. Status(L"Update failed: Could not download "
  318. L"%s (error code %d)",
  319. update.outputPath.c_str(), responseCode);
  320. return 1;
  321. }
  322. if (responseCode != 200) {
  323. downloadThreadFailure = true;
  324. DeleteFile(update.tempPath.c_str());
  325. Status(L"Update failed: Could not download "
  326. L"%s (error code %d)",
  327. update.outputPath.c_str(), responseCode);
  328. return 1;
  329. }
  330. BYTE downloadHash[BLAKE2_HASH_LENGTH];
  331. if (!CalculateFileHash(update.tempPath.c_str(),
  332. downloadHash)) {
  333. downloadThreadFailure = true;
  334. DeleteFile(update.tempPath.c_str());
  335. Status(L"Update failed: Couldn't verify "
  336. L"integrity of %s",
  337. update.outputPath.c_str());
  338. return 1;
  339. }
  340. if (memcmp(update.downloadhash, downloadHash, 20)) {
  341. downloadThreadFailure = true;
  342. DeleteFile(update.tempPath.c_str());
  343. Status(L"Update failed: Integrity check "
  344. L"failed on %s",
  345. update.outputPath.c_str());
  346. return 1;
  347. }
  348. ulock.lock();
  349. update.state = STATE_DOWNLOADED;
  350. completedUpdates++;
  351. }
  352. if (!foundWork) {
  353. break;
  354. }
  355. if (downloadThreadFailure) {
  356. return false;
  357. }
  358. }
  359. return true;
  360. }
  361. static bool RunDownloadWorkers(int num)
  362. try {
  363. vector<future<bool>> thread_success_results;
  364. thread_success_results.resize(num);
  365. for (future<bool> &result : thread_success_results) {
  366. result = async(DownloadWorkerThread);
  367. }
  368. for (future<bool> &result : thread_success_results) {
  369. if (!result.get()) {
  370. return false;
  371. }
  372. }
  373. return true;
  374. } catch (...) {
  375. return false;
  376. }
  377. /* ----------------------------------------------------------------------- */
  378. #define WAITIFOBS_SUCCESS 0
  379. #define WAITIFOBS_WRONG_PROCESS 1
  380. #define WAITIFOBS_CANCELLED 2
  381. static inline DWORD WaitIfOBS(DWORD id, const wchar_t *expected)
  382. {
  383. wchar_t path[MAX_PATH];
  384. wchar_t *name;
  385. *path = 0;
  386. WinHandle proc = OpenProcess(PROCESS_QUERY_INFORMATION |
  387. PROCESS_VM_READ | SYNCHRONIZE,
  388. false, id);
  389. if (!proc.Valid())
  390. return WAITIFOBS_WRONG_PROCESS;
  391. if (!GetProcessImageFileName(proc, path, _countof(path)))
  392. return WAITIFOBS_WRONG_PROCESS;
  393. name = wcsrchr(path, L'\\');
  394. if (name)
  395. name += 1;
  396. else
  397. name = path;
  398. if (_wcsnicmp(name, expected, 5) == 0) {
  399. HANDLE hWait[2];
  400. hWait[0] = proc;
  401. hWait[1] = cancelRequested;
  402. int i = WaitForMultipleObjects(2, hWait, false, INFINITE);
  403. if (i == WAIT_OBJECT_0 + 1)
  404. return WAITIFOBS_CANCELLED;
  405. return WAITIFOBS_SUCCESS;
  406. }
  407. return WAITIFOBS_WRONG_PROCESS;
  408. }
  409. static bool WaitForOBS()
  410. {
  411. DWORD proc_ids[1024], needed, count;
  412. const wchar_t *name = is32bit ? L"obs32" : L"obs64";
  413. if (!EnumProcesses(proc_ids, sizeof(proc_ids), &needed)) {
  414. return true;
  415. }
  416. count = needed / sizeof(DWORD);
  417. for (DWORD i = 0; i < count; i++) {
  418. DWORD id = proc_ids[i];
  419. if (id != 0) {
  420. switch (WaitIfOBS(id, name)) {
  421. case WAITIFOBS_SUCCESS:
  422. return true;
  423. case WAITIFOBS_WRONG_PROCESS:
  424. break;
  425. case WAITIFOBS_CANCELLED:
  426. return false;
  427. }
  428. }
  429. }
  430. return true;
  431. }
  432. /* ----------------------------------------------------------------------- */
  433. static inline bool UTF8ToWide(wchar_t *wide, int wideSize, const char *utf8)
  434. {
  435. return !!MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wide, wideSize);
  436. }
  437. static inline bool WideToUTF8(char *utf8, int utf8Size, const wchar_t *wide)
  438. {
  439. return !!WideCharToMultiByte(CP_UTF8, 0, wide, -1, utf8, utf8Size,
  440. nullptr, nullptr);
  441. }
  442. static inline bool FileExists(const wchar_t *path)
  443. {
  444. WIN32_FIND_DATAW wfd;
  445. HANDLE hFind;
  446. hFind = FindFirstFileW(path, &wfd);
  447. if (hFind != INVALID_HANDLE_VALUE)
  448. FindClose(hFind);
  449. return hFind != INVALID_HANDLE_VALUE;
  450. }
  451. static bool NonCorePackageInstalled(const char *name)
  452. {
  453. if (is32bit) {
  454. if (strcmp(name, "obs-browser") == 0) {
  455. return FileExists(
  456. L"obs-plugins\\32bit\\obs-browser.dll");
  457. } else if (strcmp(name, "realsense") == 0) {
  458. return FileExists(L"obs-plugins\\32bit\\win-ivcam.dll");
  459. }
  460. } else {
  461. if (strcmp(name, "obs-browser") == 0) {
  462. return FileExists(
  463. L"obs-plugins\\64bit\\obs-browser.dll");
  464. } else if (strcmp(name, "realsense") == 0) {
  465. return FileExists(L"obs-plugins\\64bit\\win-ivcam.dll");
  466. }
  467. }
  468. return false;
  469. }
  470. static inline bool is_64bit_windows(void)
  471. {
  472. #ifdef _WIN64
  473. return true;
  474. #else
  475. BOOL x86 = false;
  476. bool success = !!IsWow64Process(GetCurrentProcess(), &x86);
  477. return success && !!x86;
  478. #endif
  479. }
  480. static inline bool is_64bit_file(const char *file)
  481. {
  482. if (!file)
  483. return false;
  484. return strstr(file, "64bit") != nullptr ||
  485. strstr(file, "64.dll") != nullptr ||
  486. strstr(file, "64.exe") != nullptr;
  487. }
  488. static inline bool has_str(const char *file, const char *str)
  489. {
  490. return (file && str) ? (strstr(file, str) != nullptr) : false;
  491. }
  492. #define UTF8ToWideBuf(wide, utf8) UTF8ToWide(wide, _countof(wide), utf8)
  493. #define WideToUTF8Buf(utf8, wide) WideToUTF8(utf8, _countof(utf8), wide)
  494. #define UPDATE_URL L"https://cdn-fastly.obsproject.com/update_studio"
  495. static bool AddPackageUpdateFiles(json_t *root, size_t idx,
  496. const wchar_t *tempPath)
  497. {
  498. json_t *package = json_array_get(root, idx);
  499. json_t *name = json_object_get(package, "name");
  500. json_t *files = json_object_get(package, "files");
  501. bool isWin64 = is_64bit_windows();
  502. if (!json_is_array(files))
  503. return true;
  504. if (!json_is_string(name))
  505. return true;
  506. wchar_t wPackageName[512];
  507. const char *packageName = json_string_value(name);
  508. size_t fileCount = json_array_size(files);
  509. if (!UTF8ToWideBuf(wPackageName, packageName))
  510. return false;
  511. if (strcmp(packageName, "core") != 0 &&
  512. !NonCorePackageInstalled(packageName))
  513. return true;
  514. for (size_t j = 0; j < fileCount; j++) {
  515. json_t *file = json_array_get(files, j);
  516. json_t *fileName = json_object_get(file, "name");
  517. json_t *hash = json_object_get(file, "hash");
  518. json_t *size = json_object_get(file, "size");
  519. if (!json_is_string(fileName))
  520. continue;
  521. if (!json_is_string(hash))
  522. continue;
  523. if (!json_is_integer(size))
  524. continue;
  525. const char *fileUTF8 = json_string_value(fileName);
  526. const char *hashUTF8 = json_string_value(hash);
  527. int fileSize = (int)json_integer_value(size);
  528. if (strlen(hashUTF8) != BLAKE2_HASH_LENGTH * 2)
  529. continue;
  530. if (!isWin64 && is_64bit_file(fileUTF8))
  531. continue;
  532. /* ignore update files of opposite arch to reduce download */
  533. if ((is32bit && has_str(fileUTF8, "/64bit/")) ||
  534. (!is32bit && has_str(fileUTF8, "/32bit/")))
  535. continue;
  536. /* convert strings to wide */
  537. wchar_t sourceURL[1024];
  538. wchar_t updateFileName[MAX_PATH];
  539. wchar_t updateHashStr[BLAKE2_HASH_STR_LENGTH];
  540. wchar_t tempFilePath[MAX_PATH];
  541. if (!UTF8ToWideBuf(updateFileName, fileUTF8))
  542. continue;
  543. if (!UTF8ToWideBuf(updateHashStr, hashUTF8))
  544. continue;
  545. /* make sure paths are safe */
  546. if (!IsSafeFilename(updateFileName)) {
  547. Status(L"Update failed: Unsafe path '%s' found in "
  548. L"manifest",
  549. updateFileName);
  550. return false;
  551. }
  552. StringCbPrintf(sourceURL, sizeof(sourceURL), L"%s/%s/%s",
  553. UPDATE_URL, wPackageName, updateFileName);
  554. StringCbPrintf(tempFilePath, sizeof(tempFilePath), L"%s\\%s",
  555. tempPath, updateHashStr);
  556. /* Check file hash */
  557. BYTE existingHash[BLAKE2_HASH_LENGTH];
  558. wchar_t fileHashStr[BLAKE2_HASH_STR_LENGTH];
  559. bool has_hash;
  560. /* We don't really care if this fails, it's just to avoid
  561. * wasting bandwidth by downloading unmodified files */
  562. if (CalculateFileHash(updateFileName, existingHash)) {
  563. HashToString(existingHash, fileHashStr);
  564. if (wcscmp(fileHashStr, updateHashStr) == 0)
  565. continue;
  566. has_hash = true;
  567. } else {
  568. has_hash = false;
  569. }
  570. /* Add update file */
  571. update_t update;
  572. update.fileSize = fileSize;
  573. update.basename = updateFileName;
  574. update.outputPath = updateFileName;
  575. update.tempPath = tempFilePath;
  576. update.sourceURL = sourceURL;
  577. update.packageName = packageName;
  578. update.state = STATE_PENDING_DOWNLOAD;
  579. update.patchable = false;
  580. StringToHash(updateHashStr, update.downloadhash);
  581. memcpy(update.hash, update.downloadhash, sizeof(update.hash));
  582. update.has_hash = has_hash;
  583. if (has_hash)
  584. StringToHash(fileHashStr, update.my_hash);
  585. updates.push_back(move(update));
  586. totalFileSize += fileSize;
  587. }
  588. return true;
  589. }
  590. static void UpdateWithPatchIfAvailable(const char *name, const char *hash,
  591. const char *source, int size)
  592. {
  593. wchar_t widePatchableFilename[MAX_PATH];
  594. wchar_t widePatchHash[MAX_PATH];
  595. wchar_t sourceURL[1024];
  596. wchar_t patchHashStr[BLAKE2_HASH_STR_LENGTH];
  597. if (strncmp(source, "https://cdn-fastly.obsproject.com/", 34) != 0)
  598. return;
  599. string patchPackageName = name;
  600. const char *slash = strchr(name, '/');
  601. if (!slash)
  602. return;
  603. patchPackageName.resize(slash - name);
  604. name = slash + 1;
  605. if (!UTF8ToWideBuf(widePatchableFilename, name))
  606. return;
  607. if (!UTF8ToWideBuf(widePatchHash, hash))
  608. return;
  609. if (!UTF8ToWideBuf(sourceURL, source))
  610. return;
  611. if (!UTF8ToWideBuf(patchHashStr, hash))
  612. return;
  613. for (update_t &update : updates) {
  614. if (update.packageName != patchPackageName)
  615. continue;
  616. if (update.basename != widePatchableFilename)
  617. continue;
  618. StringToHash(patchHashStr, update.downloadhash);
  619. /* Replace the source URL with the patch file, mark it as
  620. * patchable, and re-calculate download size */
  621. totalFileSize -= (update.fileSize - size);
  622. update.sourceURL = sourceURL;
  623. update.fileSize = size;
  624. update.patchable = true;
  625. break;
  626. }
  627. }
  628. static bool UpdateFile(update_t &file)
  629. {
  630. wchar_t oldFileRenamedPath[MAX_PATH];
  631. if (file.patchable)
  632. Status(L"Updating %s...", file.outputPath.c_str());
  633. else
  634. Status(L"Installing %s...", file.outputPath.c_str());
  635. /* Check if we're replacing an existing file or just installing a new
  636. * one */
  637. DWORD attribs = GetFileAttributes(file.outputPath.c_str());
  638. if (attribs != INVALID_FILE_ATTRIBUTES) {
  639. wchar_t *curFileName = nullptr;
  640. wchar_t baseName[MAX_PATH];
  641. StringCbCopy(baseName, sizeof(baseName),
  642. file.outputPath.c_str());
  643. curFileName = wcsrchr(baseName, '/');
  644. if (curFileName) {
  645. curFileName[0] = '\0';
  646. curFileName++;
  647. } else
  648. curFileName = baseName;
  649. /* Backup the existing file in case a rollback is needed */
  650. StringCbCopy(oldFileRenamedPath, sizeof(oldFileRenamedPath),
  651. file.outputPath.c_str());
  652. StringCbCat(oldFileRenamedPath, sizeof(oldFileRenamedPath),
  653. L".old");
  654. if (!MyCopyFile(file.outputPath.c_str(), oldFileRenamedPath)) {
  655. int is_sharing_violation =
  656. (GetLastError() == ERROR_SHARING_VIOLATION);
  657. if (is_sharing_violation)
  658. Status(L"Update failed: %s is still in use. "
  659. L"Close all programs and try again.",
  660. curFileName);
  661. else
  662. Status(L"Update failed: Couldn't backup %s "
  663. L"(error %d)",
  664. curFileName, GetLastError());
  665. return false;
  666. }
  667. file.previousFile = oldFileRenamedPath;
  668. int error_code;
  669. bool installed_ok;
  670. if (file.patchable) {
  671. error_code = ApplyPatch(file.tempPath.c_str(),
  672. file.outputPath.c_str());
  673. installed_ok = (error_code == 0);
  674. if (installed_ok) {
  675. BYTE patchedFileHash[BLAKE2_HASH_LENGTH];
  676. if (!CalculateFileHash(file.outputPath.c_str(),
  677. patchedFileHash)) {
  678. Status(L"Update failed: Couldn't "
  679. L"verify integrity of patched %s",
  680. curFileName);
  681. file.state = STATE_INSTALL_FAILED;
  682. return false;
  683. }
  684. if (memcmp(file.hash, patchedFileHash,
  685. BLAKE2_HASH_LENGTH) != 0) {
  686. Status(L"Update failed: Integrity "
  687. L"check of patched "
  688. L"%s failed",
  689. curFileName);
  690. file.state = STATE_INSTALL_FAILED;
  691. return false;
  692. }
  693. }
  694. } else {
  695. installed_ok = MyCopyFile(file.tempPath.c_str(),
  696. file.outputPath.c_str());
  697. error_code = GetLastError();
  698. }
  699. if (!installed_ok) {
  700. int is_sharing_violation =
  701. (error_code == ERROR_SHARING_VIOLATION);
  702. if (is_sharing_violation)
  703. Status(L"Update failed: %s is still in use. "
  704. L"Close all "
  705. L"programs and try again.",
  706. curFileName);
  707. else
  708. Status(L"Update failed: Couldn't update %s "
  709. L"(error %d)",
  710. curFileName, GetLastError());
  711. file.state = STATE_INSTALL_FAILED;
  712. return false;
  713. }
  714. file.state = STATE_INSTALLED;
  715. } else {
  716. if (file.patchable) {
  717. /* Uh oh, we thought we could patch something but it's
  718. * no longer there! */
  719. Status(L"Update failed: Source file %s not found",
  720. file.outputPath.c_str());
  721. return false;
  722. }
  723. /* We may be installing into new folders,
  724. * make sure they exist */
  725. CreateFoldersForPath(file.outputPath.c_str());
  726. file.previousFile = L"";
  727. bool success = !!MyCopyFile(file.tempPath.c_str(),
  728. file.outputPath.c_str());
  729. if (!success) {
  730. Status(L"Update failed: Couldn't install %s (error %d)",
  731. file.outputPath.c_str(), GetLastError());
  732. file.state = STATE_INSTALL_FAILED;
  733. return false;
  734. }
  735. file.state = STATE_INSTALLED;
  736. }
  737. return true;
  738. }
  739. static wchar_t tempPath[MAX_PATH] = {};
  740. #define PATCH_MANIFEST_URL \
  741. L"https://obsproject.com/update_studio/getpatchmanifest"
  742. #define HASH_NULL L"0000000000000000000000000000000000000000"
  743. static bool UpdateVS2017Redists(json_t *root)
  744. {
  745. /* ------------------------------------------ *
  746. * Initialize session */
  747. const DWORD tlsProtocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
  748. HttpHandle hSession = WinHttpOpen(L"OBS Studio Updater/2.1",
  749. WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
  750. WINHTTP_NO_PROXY_NAME,
  751. WINHTTP_NO_PROXY_BYPASS, 0);
  752. if (!hSession) {
  753. Status(L"Update failed: Couldn't open obsproject.com");
  754. return false;
  755. }
  756. WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS,
  757. (LPVOID)&tlsProtocols, sizeof(tlsProtocols));
  758. HttpHandle hConnect = WinHttpConnect(hSession,
  759. L"cdn-fastly.obsproject.com",
  760. INTERNET_DEFAULT_HTTPS_PORT, 0);
  761. if (!hConnect) {
  762. Status(L"Update failed: Couldn't connect to cdn-fastly.obsproject.com");
  763. return false;
  764. }
  765. int responseCode;
  766. DWORD waitResult = WaitForSingleObject(cancelRequested, 0);
  767. if (waitResult == WAIT_OBJECT_0) {
  768. return false;
  769. }
  770. /* ------------------------------------------ *
  771. * Download redist */
  772. Status(L"Downloading %s", L"Visual C++ 2017 Redistributable");
  773. const wchar_t *file = (is32bit) ? L"vc2017redist_x86.exe"
  774. : L"vc2017redist_x64.exe";
  775. wstring sourceURL;
  776. sourceURL += L"https://cdn-fastly.obsproject.com/downloads/";
  777. sourceURL += file;
  778. wstring destPath;
  779. destPath += tempPath;
  780. destPath += L"\\";
  781. destPath += file;
  782. if (!HTTPGetFile(hConnect, sourceURL.c_str(), destPath.c_str(),
  783. L"Accept-Encoding: gzip", &responseCode)) {
  784. DeleteFile(destPath.c_str());
  785. Status(L"Update failed: Could not download "
  786. L"%s (error code %d)",
  787. L"Visual C++ 2017 Redistributable", responseCode);
  788. return false;
  789. }
  790. /* ------------------------------------------ *
  791. * Get expected hash */
  792. json_t *redistJson = json_object_get(
  793. root, is32bit ? "vc2017_redist_x86" : "vc2017_redist_x64");
  794. if (!redistJson) {
  795. Status(L"Update failed: Could not parse VC2017 redist json");
  796. return false;
  797. }
  798. const char *expectedHashUTF8 = json_string_value(redistJson);
  799. wchar_t expectedHashWide[BLAKE2_HASH_STR_LENGTH];
  800. BYTE expectedHash[BLAKE2_HASH_LENGTH];
  801. if (!UTF8ToWideBuf(expectedHashWide, expectedHashUTF8)) {
  802. DeleteFile(destPath.c_str());
  803. Status(L"Update failed: Couldn't convert Json for redist hash");
  804. return false;
  805. }
  806. StringToHash(expectedHashWide, expectedHash);
  807. wchar_t downloadHashWide[BLAKE2_HASH_STR_LENGTH];
  808. BYTE downloadHash[BLAKE2_HASH_LENGTH];
  809. /* ------------------------------------------ *
  810. * Get download hash */
  811. if (!CalculateFileHash(destPath.c_str(), downloadHash)) {
  812. DeleteFile(destPath.c_str());
  813. Status(L"Update failed: Couldn't verify integrity of %s",
  814. L"Visual C++ 2017 Redistributable");
  815. return false;
  816. }
  817. /* ------------------------------------------ *
  818. * If hashes do not match, integrity failed */
  819. HashToString(downloadHash, downloadHashWide);
  820. if (wcscmp(expectedHashWide, downloadHashWide) != 0) {
  821. DeleteFile(destPath.c_str());
  822. Status(L"Update failed: Couldn't verify integrity of %s",
  823. L"Visual C++ 2017 Redistributable");
  824. return false;
  825. }
  826. /* ------------------------------------------ *
  827. * If hashes match, install redist */
  828. wchar_t commandline[MAX_PATH + MAX_PATH];
  829. StringCbPrintf(commandline, sizeof(commandline),
  830. L"%s /install /quiet /norestart", destPath.c_str());
  831. PROCESS_INFORMATION pi = {};
  832. STARTUPINFO si = {};
  833. si.cb = sizeof(si);
  834. bool success = !!CreateProcessW(destPath.c_str(), commandline, nullptr,
  835. nullptr, false, CREATE_NO_WINDOW,
  836. nullptr, nullptr, &si, &pi);
  837. if (success) {
  838. Status(L"Installing %s...", L"Visual C++ 2017 Redistributable");
  839. CloseHandle(pi.hThread);
  840. WaitForSingleObject(pi.hProcess, INFINITE);
  841. CloseHandle(pi.hProcess);
  842. } else {
  843. Status(L"Update failed: Could not execute "
  844. L"%s (error code %d)",
  845. L"Visual C++ 2017 Redistributable", (int)GetLastError());
  846. }
  847. DeleteFile(destPath.c_str());
  848. waitResult = WaitForSingleObject(cancelRequested, 0);
  849. if (waitResult == WAIT_OBJECT_0) {
  850. return false;
  851. }
  852. return success;
  853. }
  854. extern "C" void UpdateHookFiles(void);
  855. static bool Update(wchar_t *cmdLine)
  856. {
  857. /* ------------------------------------- *
  858. * Check to make sure OBS isn't running */
  859. HANDLE hObsUpdateMutex =
  860. OpenMutexW(SYNCHRONIZE, false, L"OBSStudioUpdateMutex");
  861. if (hObsUpdateMutex) {
  862. HANDLE hWait[2];
  863. hWait[0] = hObsUpdateMutex;
  864. hWait[1] = cancelRequested;
  865. int i = WaitForMultipleObjects(2, hWait, false, INFINITE);
  866. if (i == WAIT_OBJECT_0)
  867. ReleaseMutex(hObsUpdateMutex);
  868. CloseHandle(hObsUpdateMutex);
  869. if (i == WAIT_OBJECT_0 + 1)
  870. return false;
  871. }
  872. if (!WaitForOBS())
  873. return false;
  874. /* ------------------------------------- *
  875. * Init crypt stuff */
  876. CryptProvider hProvider;
  877. if (!CryptAcquireContext(&hProvider, nullptr, MS_ENH_RSA_AES_PROV,
  878. PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
  879. SetDlgItemTextW(hwndMain, IDC_STATUS,
  880. L"Update failed: CryptAcquireContext failure");
  881. return false;
  882. }
  883. ::hProvider = hProvider;
  884. /* ------------------------------------- */
  885. SetDlgItemTextW(hwndMain, IDC_STATUS,
  886. L"Searching for available updates...");
  887. HWND hProgress = GetDlgItem(hwndMain, IDC_PROGRESS);
  888. LONG_PTR style = GetWindowLongPtr(hProgress, GWL_STYLE);
  889. SetWindowLongPtr(hProgress, GWL_STYLE, style | PBS_MARQUEE);
  890. SendDlgItemMessage(hwndMain, IDC_PROGRESS, PBM_SETMARQUEE, 1, 0);
  891. /* ------------------------------------- *
  892. * Check if updating portable build */
  893. bool bIsPortable = false;
  894. if (cmdLine[0]) {
  895. int argc;
  896. LPWSTR *argv = CommandLineToArgvW(cmdLine, &argc);
  897. if (argv) {
  898. for (int i = 0; i < argc; i++) {
  899. if (wcscmp(argv[i], L"Portable") == 0) {
  900. bIsPortable = true;
  901. }
  902. }
  903. LocalFree((HLOCAL)argv);
  904. }
  905. }
  906. /* ------------------------------------- *
  907. * Get config path */
  908. wchar_t lpAppDataPath[MAX_PATH];
  909. lpAppDataPath[0] = 0;
  910. if (bIsPortable) {
  911. GetCurrentDirectory(_countof(lpAppDataPath), lpAppDataPath);
  912. StringCbCat(lpAppDataPath, sizeof(lpAppDataPath), L"\\config");
  913. } else {
  914. CoTaskMemPtr<wchar_t> pOut;
  915. HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData,
  916. KF_FLAG_DEFAULT, nullptr,
  917. &pOut);
  918. if (hr != S_OK) {
  919. Status(L"Update failed: Could not determine AppData "
  920. L"location");
  921. return false;
  922. }
  923. StringCbCopy(lpAppDataPath, sizeof(lpAppDataPath), pOut);
  924. }
  925. StringCbCat(lpAppDataPath, sizeof(lpAppDataPath), L"\\obs-studio");
  926. /* ------------------------------------- *
  927. * Get download path */
  928. wchar_t manifestPath[MAX_PATH];
  929. wchar_t tempDirName[MAX_PATH];
  930. manifestPath[0] = 0;
  931. tempDirName[0] = 0;
  932. StringCbPrintf(manifestPath, sizeof(manifestPath),
  933. L"%s\\updates\\manifest.json", lpAppDataPath);
  934. if (!GetTempPathW(_countof(tempDirName), tempDirName)) {
  935. Status(L"Update failed: Failed to get temp path: %ld",
  936. GetLastError());
  937. return false;
  938. }
  939. if (!GetTempFileNameW(tempDirName, L"obs-studio", 0, tempPath)) {
  940. Status(L"Update failed: Failed to create temp dir name: %ld",
  941. GetLastError());
  942. return false;
  943. }
  944. DeleteFile(tempPath);
  945. CreateDirectory(tempPath, nullptr);
  946. /* ------------------------------------- *
  947. * Load manifest file */
  948. Json root;
  949. {
  950. string manifestFile = QuickReadFile(manifestPath);
  951. if (manifestFile.empty()) {
  952. Status(L"Update failed: Couldn't load manifest file");
  953. return false;
  954. }
  955. json_error_t error;
  956. root = json_loads(manifestFile.c_str(), 0, &error);
  957. if (!root) {
  958. Status(L"Update failed: Couldn't parse update "
  959. L"manifest: %S",
  960. error.text);
  961. return false;
  962. }
  963. }
  964. if (!json_is_object(root.get())) {
  965. Status(L"Update failed: Invalid update manifest");
  966. return false;
  967. }
  968. /* ------------------------------------- *
  969. * Parse current manifest update files */
  970. json_t *packages = json_object_get(root, "packages");
  971. size_t packageCount = json_array_size(packages);
  972. for (size_t i = 0; i < packageCount; i++) {
  973. if (!AddPackageUpdateFiles(packages, i, tempPath)) {
  974. Status(L"Update failed: Failed to process update packages");
  975. return false;
  976. }
  977. }
  978. SendDlgItemMessage(hwndMain, IDC_PROGRESS, PBM_SETMARQUEE, 0, 0);
  979. SetWindowLongPtr(hProgress, GWL_STYLE, style);
  980. /* ------------------------------------- *
  981. * Exit if updates already installed */
  982. if (!updates.size()) {
  983. Status(L"All available updates are already installed.");
  984. SetDlgItemText(hwndMain, IDC_BUTTON, L"Launch OBS");
  985. return true;
  986. }
  987. /* ------------------------------------- *
  988. * Check for VS2017 redistributables */
  989. if (!HasVS2017Redist()) {
  990. if (!UpdateVS2017Redists(root)) {
  991. return false;
  992. }
  993. }
  994. /* ------------------------------------- *
  995. * Generate file hash json */
  996. Json files(json_array());
  997. for (update_t &update : updates) {
  998. wchar_t whash_string[BLAKE2_HASH_STR_LENGTH];
  999. char hash_string[BLAKE2_HASH_STR_LENGTH];
  1000. char outputPath[MAX_PATH];
  1001. if (!update.has_hash)
  1002. continue;
  1003. /* check hash */
  1004. HashToString(update.my_hash, whash_string);
  1005. if (wcscmp(whash_string, HASH_NULL) == 0)
  1006. continue;
  1007. if (!WideToUTF8Buf(hash_string, whash_string))
  1008. continue;
  1009. if (!WideToUTF8Buf(outputPath, update.basename.c_str()))
  1010. continue;
  1011. string package_path;
  1012. package_path = update.packageName;
  1013. package_path += "/";
  1014. package_path += outputPath;
  1015. json_t *obj = json_object();
  1016. json_object_set(obj, "name", json_string(package_path.c_str()));
  1017. json_object_set(obj, "hash", json_string(hash_string));
  1018. json_array_append_new(files, obj);
  1019. }
  1020. /* ------------------------------------- *
  1021. * Send file hashes */
  1022. string newManifest;
  1023. if (json_array_size(files) > 0) {
  1024. char *post_body = json_dumps(files, JSON_COMPACT);
  1025. int responseCode;
  1026. int len = (int)strlen(post_body);
  1027. uLong compressSize = compressBound(len);
  1028. string compressedJson;
  1029. compressedJson.resize(compressSize);
  1030. compress2((Bytef *)&compressedJson[0], &compressSize,
  1031. (const Bytef *)post_body, len, Z_BEST_COMPRESSION);
  1032. compressedJson.resize(compressSize);
  1033. bool success = !!HTTPPostData(PATCH_MANIFEST_URL,
  1034. (BYTE *)&compressedJson[0],
  1035. (int)compressedJson.size(),
  1036. L"Accept-Encoding: gzip",
  1037. &responseCode, newManifest);
  1038. free(post_body);
  1039. if (!success)
  1040. return false;
  1041. if (responseCode != 200) {
  1042. Status(L"Update failed: HTTP/%d while trying to "
  1043. L"download patch manifest",
  1044. responseCode);
  1045. return false;
  1046. }
  1047. } else {
  1048. newManifest = "[]";
  1049. }
  1050. /* ------------------------------------- *
  1051. * Parse new manifest */
  1052. json_error_t error;
  1053. root = json_loads(newManifest.c_str(), 0, &error);
  1054. if (!root) {
  1055. Status(L"Update failed: Couldn't parse patch manifest: %S",
  1056. error.text);
  1057. return false;
  1058. }
  1059. if (!json_is_array(root.get())) {
  1060. Status(L"Update failed: Invalid patch manifest");
  1061. return false;
  1062. }
  1063. packageCount = json_array_size(root);
  1064. for (size_t i = 0; i < packageCount; i++) {
  1065. json_t *patch = json_array_get(root, i);
  1066. if (!json_is_object(patch)) {
  1067. Status(L"Update failed: Invalid patch manifest");
  1068. return false;
  1069. }
  1070. json_t *name_json = json_object_get(patch, "name");
  1071. json_t *hash_json = json_object_get(patch, "hash");
  1072. json_t *source_json = json_object_get(patch, "source");
  1073. json_t *size_json = json_object_get(patch, "size");
  1074. if (!json_is_string(name_json))
  1075. continue;
  1076. if (!json_is_string(hash_json))
  1077. continue;
  1078. if (!json_is_string(source_json))
  1079. continue;
  1080. if (!json_is_integer(size_json))
  1081. continue;
  1082. const char *name = json_string_value(name_json);
  1083. const char *hash = json_string_value(hash_json);
  1084. const char *source = json_string_value(source_json);
  1085. int size = (int)json_integer_value(size_json);
  1086. UpdateWithPatchIfAvailable(name, hash, source, size);
  1087. }
  1088. /* ------------------------------------- *
  1089. * Download Updates */
  1090. if (!RunDownloadWorkers(2))
  1091. return false;
  1092. if ((size_t)completedUpdates != updates.size()) {
  1093. Status(L"Update failed to download all files.");
  1094. return false;
  1095. }
  1096. /* ------------------------------------- *
  1097. * Install updates */
  1098. int updatesInstalled = 0;
  1099. int lastPosition = 0;
  1100. SendDlgItemMessage(hwndMain, IDC_PROGRESS, PBM_SETPOS, 0, 0);
  1101. for (update_t &update : updates) {
  1102. if (!UpdateFile(update)) {
  1103. return false;
  1104. } else {
  1105. updatesInstalled++;
  1106. int position = (int)(((float)updatesInstalled /
  1107. (float)completedUpdates) *
  1108. 100.0f);
  1109. if (position > lastPosition) {
  1110. lastPosition = position;
  1111. SendDlgItemMessage(hwndMain, IDC_PROGRESS,
  1112. PBM_SETPOS, position, 0);
  1113. }
  1114. }
  1115. }
  1116. /* ------------------------------------- *
  1117. * Update hook files and vulkan registry */
  1118. UpdateHookFiles();
  1119. /* ------------------------------------- *
  1120. * Finish */
  1121. /* If we get here, all updates installed successfully so we can purge
  1122. * the old versions */
  1123. for (update_t &update : updates) {
  1124. if (!update.previousFile.empty())
  1125. DeleteFile(update.previousFile.c_str());
  1126. /* We delete here not above in case of duplicate hashes */
  1127. if (!update.tempPath.empty())
  1128. DeleteFile(update.tempPath.c_str());
  1129. }
  1130. SendDlgItemMessage(hwndMain, IDC_PROGRESS, PBM_SETPOS, 100, 0);
  1131. Status(L"Update complete.");
  1132. SetDlgItemText(hwndMain, IDC_BUTTON, L"Launch OBS");
  1133. return true;
  1134. }
  1135. static DWORD WINAPI UpdateThread(void *arg)
  1136. {
  1137. wchar_t *cmdLine = (wchar_t *)arg;
  1138. bool success = Update(cmdLine);
  1139. if (!success) {
  1140. /* This handles deleting temp files and rolling back and
  1141. * partially installed updates */
  1142. CleanupPartialUpdates();
  1143. if (tempPath[0])
  1144. RemoveDirectory(tempPath);
  1145. if (WaitForSingleObject(cancelRequested, 0) == WAIT_OBJECT_0)
  1146. Status(L"Update aborted.");
  1147. HWND hProgress = GetDlgItem(hwndMain, IDC_PROGRESS);
  1148. LONG_PTR style = GetWindowLongPtr(hProgress, GWL_STYLE);
  1149. SetWindowLongPtr(hProgress, GWL_STYLE, style & ~PBS_MARQUEE);
  1150. SendMessage(hProgress, PBM_SETSTATE, PBST_ERROR, 0);
  1151. SetDlgItemText(hwndMain, IDC_BUTTON, L"Exit");
  1152. EnableWindow(GetDlgItem(hwndMain, IDC_BUTTON), true);
  1153. updateFailed = true;
  1154. } else {
  1155. if (tempPath[0])
  1156. RemoveDirectory(tempPath);
  1157. }
  1158. if (bExiting)
  1159. ExitProcess(success);
  1160. return 0;
  1161. }
  1162. static void CancelUpdate(bool quit)
  1163. {
  1164. if (WaitForSingleObject(updateThread, 0) != WAIT_OBJECT_0) {
  1165. bExiting = quit;
  1166. SetEvent(cancelRequested);
  1167. } else {
  1168. PostQuitMessage(0);
  1169. }
  1170. }
  1171. static void LaunchOBS()
  1172. {
  1173. wchar_t cwd[MAX_PATH];
  1174. wchar_t newCwd[MAX_PATH];
  1175. wchar_t obsPath[MAX_PATH];
  1176. GetCurrentDirectory(_countof(cwd) - 1, cwd);
  1177. StringCbCopy(obsPath, sizeof(obsPath), cwd);
  1178. StringCbCat(obsPath, sizeof(obsPath),
  1179. is32bit ? L"\\bin\\32bit" : L"\\bin\\64bit");
  1180. SetCurrentDirectory(obsPath);
  1181. StringCbCopy(newCwd, sizeof(newCwd), obsPath);
  1182. StringCbCat(obsPath, sizeof(obsPath),
  1183. is32bit ? L"\\obs32.exe" : L"\\obs64.exe");
  1184. if (!FileExists(obsPath)) {
  1185. StringCbCopy(obsPath, sizeof(obsPath), cwd);
  1186. StringCbCat(obsPath, sizeof(obsPath), L"\\bin\\32bit");
  1187. SetCurrentDirectory(obsPath);
  1188. StringCbCopy(newCwd, sizeof(newCwd), obsPath);
  1189. StringCbCat(obsPath, sizeof(obsPath), L"\\obs32.exe");
  1190. if (!FileExists(obsPath)) {
  1191. /* TODO: give user a message maybe? */
  1192. return;
  1193. }
  1194. }
  1195. SHELLEXECUTEINFO execInfo;
  1196. ZeroMemory(&execInfo, sizeof(execInfo));
  1197. execInfo.cbSize = sizeof(execInfo);
  1198. execInfo.lpFile = obsPath;
  1199. execInfo.lpDirectory = newCwd;
  1200. execInfo.nShow = SW_SHOWNORMAL;
  1201. ShellExecuteEx(&execInfo);
  1202. }
  1203. static INT_PTR CALLBACK UpdateDialogProc(HWND hwnd, UINT message, WPARAM wParam,
  1204. LPARAM lParam)
  1205. {
  1206. switch (message) {
  1207. case WM_INITDIALOG: {
  1208. static HICON hMainIcon =
  1209. LoadIcon(hinstMain, MAKEINTRESOURCE(IDI_ICON1));
  1210. SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hMainIcon);
  1211. SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hMainIcon);
  1212. return true;
  1213. }
  1214. case WM_COMMAND:
  1215. if (LOWORD(wParam) == IDC_BUTTON) {
  1216. if (HIWORD(wParam) == BN_CLICKED) {
  1217. DWORD result =
  1218. WaitForSingleObject(updateThread, 0);
  1219. if (result == WAIT_OBJECT_0) {
  1220. if (updateFailed)
  1221. PostQuitMessage(0);
  1222. else
  1223. PostQuitMessage(1);
  1224. } else {
  1225. EnableWindow((HWND)lParam, false);
  1226. CancelUpdate(false);
  1227. }
  1228. }
  1229. }
  1230. return true;
  1231. case WM_CLOSE:
  1232. CancelUpdate(true);
  1233. return true;
  1234. }
  1235. return false;
  1236. }
  1237. static void RestartAsAdmin(LPWSTR lpCmdLine)
  1238. {
  1239. wchar_t myPath[MAX_PATH];
  1240. if (!GetModuleFileNameW(nullptr, myPath, _countof(myPath) - 1)) {
  1241. return;
  1242. }
  1243. wchar_t cwd[MAX_PATH];
  1244. GetCurrentDirectoryW(_countof(cwd) - 1, cwd);
  1245. SHELLEXECUTEINFO shExInfo = {0};
  1246. shExInfo.cbSize = sizeof(shExInfo);
  1247. shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  1248. shExInfo.hwnd = 0;
  1249. shExInfo.lpVerb = L"runas"; /* Operation to perform */
  1250. shExInfo.lpFile = myPath; /* Application to start */
  1251. shExInfo.lpParameters = lpCmdLine; /* Additional parameters */
  1252. shExInfo.lpDirectory = cwd;
  1253. shExInfo.nShow = SW_NORMAL;
  1254. shExInfo.hInstApp = 0;
  1255. /* annoyingly the actual elevated updater will disappear behind other
  1256. * windows :( */
  1257. AllowSetForegroundWindow(ASFW_ANY);
  1258. if (ShellExecuteEx(&shExInfo)) {
  1259. DWORD exitCode;
  1260. if (GetExitCodeProcess(shExInfo.hProcess, &exitCode)) {
  1261. if (exitCode == 1) {
  1262. LaunchOBS();
  1263. }
  1264. }
  1265. CloseHandle(shExInfo.hProcess);
  1266. }
  1267. }
  1268. static bool HasElevation()
  1269. {
  1270. SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY;
  1271. PSID sid = nullptr;
  1272. BOOL elevated = false;
  1273. BOOL success;
  1274. success = AllocateAndInitializeSid(&sia, 2, SECURITY_BUILTIN_DOMAIN_RID,
  1275. DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0,
  1276. 0, 0, &sid);
  1277. if (success && sid) {
  1278. CheckTokenMembership(nullptr, sid, &elevated);
  1279. FreeSid(sid);
  1280. }
  1281. return elevated;
  1282. }
  1283. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int)
  1284. {
  1285. INITCOMMONCONTROLSEX icce;
  1286. if (!HasElevation()) {
  1287. HANDLE hLowMutex = CreateMutexW(
  1288. nullptr, true, L"OBSUpdaterRunningAsNonAdminUser");
  1289. RestartAsAdmin(lpCmdLine);
  1290. if (hLowMutex) {
  1291. ReleaseMutex(hLowMutex);
  1292. CloseHandle(hLowMutex);
  1293. }
  1294. return 0;
  1295. } else {
  1296. {
  1297. wchar_t cwd[MAX_PATH];
  1298. wchar_t newPath[MAX_PATH];
  1299. GetCurrentDirectoryW(_countof(cwd) - 1, cwd);
  1300. is32bit = wcsstr(cwd, L"bin\\32bit") != nullptr;
  1301. StringCbCat(cwd, sizeof(cwd), L"\\..\\..");
  1302. GetFullPathName(cwd, _countof(newPath), newPath,
  1303. nullptr);
  1304. SetCurrentDirectory(newPath);
  1305. }
  1306. hinstMain = hInstance;
  1307. icce.dwSize = sizeof(icce);
  1308. icce.dwICC = ICC_PROGRESS_CLASS;
  1309. InitCommonControlsEx(&icce);
  1310. hwndMain = CreateDialog(hInstance,
  1311. MAKEINTRESOURCE(IDD_UPDATEDIALOG),
  1312. nullptr, UpdateDialogProc);
  1313. if (!hwndMain) {
  1314. return -1;
  1315. }
  1316. ShowWindow(hwndMain, SW_SHOWNORMAL);
  1317. SetForegroundWindow(hwndMain);
  1318. cancelRequested = CreateEvent(nullptr, true, false, nullptr);
  1319. updateThread = CreateThread(nullptr, 0, UpdateThread, lpCmdLine,
  1320. 0, nullptr);
  1321. MSG msg;
  1322. while (GetMessage(&msg, nullptr, 0, 0)) {
  1323. if (!IsDialogMessage(hwndMain, &msg)) {
  1324. TranslateMessage(&msg);
  1325. DispatchMessage(&msg);
  1326. }
  1327. }
  1328. /* there is no non-elevated process waiting for us if UAC is
  1329. * disabled */
  1330. WinHandle hMutex = OpenMutex(
  1331. SYNCHRONIZE, false, L"OBSUpdaterRunningAsNonAdminUser");
  1332. if (msg.wParam == 1 && !hMutex) {
  1333. LaunchOBS();
  1334. }
  1335. return (int)msg.wParam;
  1336. }
  1337. }