updater.cpp 40 KB

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