updater.cpp 40 KB

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