updater.cpp 44 KB

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