updater.cpp 41 KB

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