// the stub. shortcuts, the uninstall entry and start-at-login all point at // this, and it lives in under the apps own exe name. // // \.exe us. every build carries a garage_stub.exe and // apply swaps us for it when its a different one // \app-\... a whole build of the app // \garage_updates.json which build to start. the dart side writes it too // // when is program files the person starting the app cant write that // file, so the count of starts is kept for them in // %LOCALAPPDATA%\\garage_updates.json instead. // // no flags start the current build, count the start, fall back to // the previous build when this one keeps dying // --garage-exec start some other exe out of the current build // --garage-apply unpack a zip as a new build and make it current // --garage-uninstall take the whole install away // // anything else on the command line belongs to the app and goes through as it // came. there is no window and nothing waits on the app once its started. #include "garage_common.h" #include #include using namespace garage; // what the dart side sees. 0 is the only good one enum ExitCode { kOk = 0, kBadArgs = 10, kNoSelf = 11, // couldnt work out where we are kNoVersion = 12, // no app- folder that can be started kNoExe = 13, // dont know which exe in the folder is the app kCantStart = 14, kExecMissing = 15, // --garage-exec asked for something that isnt there, or isnt inside the folder kNotWritable = 20, // apply needs to be run elevated kZipMissing = 21, kNoTar = 22, kTarFailed = 23, kBadPackage = 24, // unpacked fine but the apps exe isnt in it kCantPlace = 25, // couldnt move the folder in to place kStateWrite = 26, kBusy = 27, // another apply is running kNoTemp = 28, kCancelled = 30, kNoElevation = 31, kLeftovers = 32, // uninstall couldnt remove everything kNotAnInstall = 33, }; static std::wstring g_self; static std::wstring g_root; // %LOCALAPPDATA%\\ is where the log goes when is read only static std::wstring g_appId; // ---- the log ---- static std::wstring env(const wchar_t* name) { DWORD need = GetEnvironmentVariableW(name, nullptr, 0); if (need == 0) return L""; std::wstring out((size_t)need, L'\0'); DWORD got = GetEnvironmentVariableW(name, &out[0], need); if (got == 0 || got >= need) return L""; out.resize(got); return out; } static std::wstring local_dir() { std::wstring local = env(L"LOCALAPPDATA"); if (local.empty()) return L""; return join(local, g_appId.empty() ? leaf(g_root) : g_appId); } static bool append_to(const std::wstring& path, const std::string& bytes) { // it only ever gets failures, but a machine that fails every start // shouldnt fill the disk with them if (file_size(path) > 256 * 1024) { MoveFileExW(lp(path).c_str(), lp(path + L".old").c_str(), MOVEFILE_REPLACE_EXISTING); } HANDLE h = CreateFileW(lp(path).c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) return false; DWORD wrote = 0; BOOL ok = WriteFile(h, bytes.data(), (DWORD)bytes.size(), &wrote, nullptr); CloseHandle(h); return ok != FALSE; } static void log_line(const std::wstring& msg) { SYSTEMTIME t; GetLocalTime(&t); wchar_t stamp[64]; wsprintfW(stamp, L"%04d-%02d-%02d %02d:%02d:%02d [%lu] ", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, GetCurrentProcessId()); std::wstring line = stamp + msg; OutputDebugStringW((L"garage_stub: " + line + L"\n").c_str()); std::string bytes = narrow(line) + "\r\n"; // whoever started us with a pipe (the dart side does) gets it as well HANDLE err = GetStdHandle(STD_ERROR_HANDLE); if (err && err != INVALID_HANDLE_VALUE) { DWORD wrote = 0; WriteFile(err, bytes.data(), (DWORD)bytes.size(), &wrote, nullptr); } if (!g_root.empty() && append_to(join(g_root, L"garage_updates.log"), bytes)) return; // program files. the user cant write there, so it goes beside their own stuff std::wstring dir = local_dir(); if (dir.empty()) return; CreateDirectoryW(lp(dir).c_str(), nullptr); if (!append_to(join(dir, L"garage_updates.log"), bytes)) { OutputDebugStringW(L"garage_stub: and the log couldnt be written either\n"); } } static void log_fail(const std::wstring& what, DWORD err) { log_line(what + L" (win32 " + win_error(err) + L")"); } // ---- the command line ---- // read off the raw string, not argv. what the app is owed has to reach it // exactly as it was typed, and re-quoting an argv never quite manages that. static bool is_space(wchar_t c) { return c == L' ' || c == L'\t'; } // the program name has its own rule: a quoted one ends at the next quote and // backslashes mean nothing static const wchar_t* skip_program(const wchar_t* p) { if (*p == L'"') { p++; while (*p && *p != L'"') p++; if (*p) p++; } else { while (*p && !is_space(*p)) p++; } while (is_space(*p)) p++; return p; } // one argument, read the way the c runtime reads it. leaves p on the next one static bool next_arg(const wchar_t*& p, std::wstring& out) { out.clear(); while (is_space(*p)) p++; if (!*p) return false; bool quoted = false; for (;;) { size_t slashes = 0; while (*p == L'\\') { p++; slashes++; } if (*p == L'"') { out.append(slashes / 2, L'\\'); if (slashes % 2) { out += L'"'; p++; } else if (quoted && p[1] == L'"') { out += L'"'; p += 2; } else { quoted = !quoted; p++; } continue; } out.append(slashes, L'\\'); if (!*p || (!quoted && is_space(*p))) break; out += *p++; } while (is_space(*p)) p++; return true; } // ---- locks ---- // two of us can be started at once (a double click, a login item and a // shortcut). a mutex named after the root keeps them off the state file // together. theres nowhere to put a lock file when root is read only. static HANDLE lock_named(const wchar_t* what, DWORD waitMs) { std::wstring lower = g_root; if (!lower.empty()) CharLowerBuffW(&lower[0], (DWORD)lower.size()); unsigned long long h = 1469598103934665603ULL; for (size_t i = 0; i < lower.size(); i++) { h ^= (unsigned long long)lower[i]; h *= 1099511628211ULL; } wchar_t name[96]; wsprintfW(name, L"Local\\garage_updates-%s-%08x%08x", what, (unsigned)(h >> 32), (unsigned)(h & 0xffffffffULL)); HANDLE m = CreateMutexW(nullptr, FALSE, name); if (!m) { log_fail(std::wstring(L"couldnt make the ") + what + L" lock", GetLastError()); return nullptr; } DWORD got = WaitForSingleObject(m, waitMs); // abandoned is the last holder dying with it. its ours now all the same if (got == WAIT_OBJECT_0 || got == WAIT_ABANDONED) return m; log_fail(std::wstring(L"gave up waiting for the ") + what + L" lock", got == WAIT_TIMEOUT ? (DWORD)WAIT_TIMEOUT : GetLastError()); CloseHandle(m); return nullptr; } static void unlock(HANDLE m) { if (!m) return; ReleaseMutex(m); CloseHandle(m); } // ---- state ---- static bool safe_exe_name(const std::wstring& name) { if (name.empty()) return false; return name.find_first_of(L"\\/:") == std::wstring::npos && name != L"." && name != L".."; } static bool can_start(const State& st, long long build) { if (build <= 0) return false; std::wstring dir = version_dir(g_root, build); if (!is_dir(dir)) return false; return st.exe.empty() || exists(join(dir, st.exe)); } // for when the state file doesnt say. our own name first, the stub is put in // root under the apps exe name. failing that, the only exe in there static std::wstring guess_exe(const std::wstring& dir) { std::wstring mine = leaf(g_self); if (!same_text(mine, L"garage_stub.exe") && exists(join(dir, mine))) return mine; std::wstring only; int count = 0; WIN32_FIND_DATAW fd; HANDLE find = FindFirstFileW(lp(join(dir, L"*.exe")).c_str(), &fd); if (find == INVALID_HANDLE_VALUE) return L""; do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; if (same_text(fd.cFileName, L"garage_stub.exe")) continue; only = fd.cFileName; count++; } while (FindNextFileW(find, &fd)); FindClose(find); return count == 1 ? only : L""; } static bool read_state(State& st) { std::wstring path = state_path(g_root); std::string text; if (!read_file(path, text, 1024 * 1024)) { DWORD err = GetLastError(); if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND) log_fail(L"couldnt read " + path, err); st = State(); return false; } if (!parse_state(text, st)) { log_line(path + L" isnt json we understand, going by the folders instead"); st = State(); return false; } if (!st.exe.empty() && !safe_exe_name(st.exe)) { log_line(L"the exe in the state file has a path in it, ignoring it: " + st.exe); st.exe.clear(); } return true; } static bool save_state(const State& st) { return write_atomic(state_path(g_root), print_state(st)); } // makes the state agree with whats on disk: a current that can be started and // an exe name. `quiet` is for apply on a first install, where having nothing // yet is the normal case static int settle(State& st, bool quiet) { if (!can_start(st, st.current)) { long long was = st.current; long long pick = -1; if (st.previous != st.current && can_start(st, st.previous)) { pick = st.previous; } else { std::vector have = list_versions(g_root); for (size_t i = 0; i < have.size(); i++) { if (have[i] > pick && !st.is_blocked(have[i]) && can_start(st, have[i])) pick = have[i]; } } if (pick <= 0) { if (!quiet) log_line(L"theres no app- folder in " + g_root + L" that can be started"); return kNoVersion; } if (!quiet) { log_line(L"the state file says build " + num(was) + L" which isnt there, using build " + num(pick)); } st.current = pick; st.failedStarts = 0; } if (st.previous == st.current) st.previous = -1; if (st.exe.empty()) { st.exe = guess_exe(version_dir(g_root, st.current)); if (st.exe.empty()) { if (!quiet) log_line(L"dont know which exe in " + version_dir(g_root, st.current) + L" is the app"); return kNoExe; } } return kOk; } // ---- the users own half ---- // nobody but an admin can write to an install in program files, so the count // of starts cant go in the state file there. it goes in a file of the users // own, and falling back is "start the previous build for this user" rather // than changing what current is for everybody. struct UserState { long long failedStarts = 0; std::vector blocked; long long forCurrent = -1; // the current the count was made against long long runInstead = -1; // started for this user in place of current bool is_blocked(long long build) const { for (size_t i = 0; i < blocked.size(); i++) { if (blocked[i] == build) return true; } return false; } }; static std::wstring user_state_path() { std::wstring dir = local_dir(); if (dir.empty()) return L""; return join(dir, L"garage_updates.json"); } // a missing one or one that wont parse is the same as a new one static void read_user_state(UserState& us) { us = UserState(); std::wstring path = user_state_path(); std::string text; if (!read_file(path, text, 1024 * 1024)) { DWORD err = GetLastError(); if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND) log_fail(L"couldnt read " + path, err); return; } JVal root; if (!json_parse(text, root) || root.kind != JVal::Obj) { log_line(path + L" isnt json we understand, starting it again"); return; } us.failedStarts = root.number("failed_starts", 0); if (us.failedStarts < 0) us.failedStarts = 0; us.forCurrent = root.number("for_current", -1); us.runInstead = root.number("run_instead", -1); const JVal* blocked = root.get("blocked"); if (blocked && blocked->kind == JVal::Arr) { for (size_t i = 0; i < blocked->items.size(); i++) { if (blocked->items[i].kind == JVal::Num && !us.is_blocked(blocked->items[i].n)) { us.blocked.push_back(blocked->items[i].n); } } } } static bool save_user_state(const UserState& us) { std::wstring dir = local_dir(); if (!CreateDirectoryW(lp(dir).c_str(), nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) return false; std::string out = "{\n"; out += " \"failed_starts\": " + std::to_string(us.failedStarts) + ",\n"; out += " \"blocked\": ["; for (size_t i = 0; i < us.blocked.size(); i++) { if (i > 0) out += ", "; out += std::to_string(us.blocked[i]); } out += "],\n"; out += " \"for_current\": " + print_build(us.forCurrent) + ",\n"; out += " \"run_instead\": " + print_build(us.runInstead) + "\n}\n"; return write_atomic(user_state_path(), out); } // counts a start for this user, root being somewhere they cant write. hands // back the build to start, which isnt current once current has failed them // three times. the dart side reads the same file by the same rules static long long count_for_user(const State& st) { if (local_dir().empty()) { log_line(L"theres no LOCALAPPDATA to count starts in, this start isnt counted"); return st.current; } UserState us; read_user_state(us); if (us.forCurrent != st.current) { // an update went in since. what was counted was the build before it us.forCurrent = st.current; us.failedStarts = 0; us.runInstead = -1; } if (us.runInstead > 0) { // nothing is counted while on this one, theres no further back to go if (us.runInstead != st.current && can_start(st, us.runInstead)) return us.runInstead; log_line(L"build " + num(us.runInstead) + L" that this user was put back on isnt there any more, starting build " + num(st.current)); us.runInstead = -1; us.failedStarts = 0; } long long run = st.current; if (us.failedStarts >= 3) { // a previous that allready failed this user is no better bool back = st.previous > 0 && st.previous != st.current && !us.is_blocked(st.previous) && can_start(st, st.previous); if (back) { log_line(L"build " + num(st.current) + L" didnt stay up " + num(us.failedStarts) + L" times in a row for this user, blocking it for them and starting build " + num(st.previous)); if (!us.is_blocked(st.current)) us.blocked.push_back(st.current); us.runInstead = st.previous; us.failedStarts = 0; run = st.previous; } else { log_line(L"build " + num(st.current) + L" keeps failing to start for this user and theres nothing to go back to"); } } if (run == st.current && us.failedStarts < 1000) us.failedStarts++; if (!save_user_state(us)) { log_fail(L"couldnt write " + user_state_path() + L", this start isnt counted", GetLastError()); } return run; } // ---- whats running ---- struct Running { DWORD pid; std::wstring path; }; // every process we are allowed to ask the path of. the ones we arent belong // to the system or somebody else, and none of those are the app static std::vector running() { std::vector out; HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snap == INVALID_HANDLE_VALUE) { log_fail(L"couldnt list whats running", GetLastError()); return out; } PROCESSENTRY32W pe = {}; pe.dwSize = sizeof(pe); if (Process32FirstW(snap, &pe)) { do { if (pe.th32ProcessID == 0 || pe.th32ProcessID == GetCurrentProcessId()) continue; HANDLE proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe.th32ProcessID); if (!proc) continue; wchar_t image[2048]; DWORD len = ARRAYSIZE(image); if (QueryFullProcessImageNameW(proc, 0, image, &len)) { Running r; r.pid = pe.th32ProcessID; r.path.assign(image, len); out.push_back(r); } CloseHandle(proc); } while (Process32NextW(snap, &pe)); } CloseHandle(snap); return out; } static bool is_running(const std::wstring& exe) { std::vector all = running(); for (size_t i = 0; i < all.size(); i++) { if (same_text(all[i].path, exe)) return true; } return false; } // ---- starting things ---- static bool usable(HANDLE h) { return h != nullptr && h != INVALID_HANDLE_VALUE; } // `rest` is the raw tail of our own command line and is passed on as it is static bool start_child(const std::wstring& exe, const std::wstring& cwd, const wchar_t* rest) { std::wstring cmd = quote_arg(exe); if (rest && *rest) { cmd += L" "; cmd += rest; } // so the app can find its way back without counting folders SetEnvironmentVariableW(L"GARAGE_UPDATES_ROOT", g_root.c_str()); SetEnvironmentVariableW(L"GARAGE_UPDATES_STUB", g_self.c_str()); STARTUPINFOW mine = {}; mine.cb = sizeof(mine); GetStartupInfoW(&mine); STARTUPINFOW si = {}; si.cb = sizeof(si); // a shortcut set to "run minimised" means the app, not us if (mine.dwFlags & STARTF_USESHOWWINDOW) { si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = mine.wShowWindow; } HANDLE in = GetStdHandle(STD_INPUT_HANDLE); HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); HANDLE err = GetStdHandle(STD_ERROR_HANDLE); BOOL inherit = FALSE; if (usable(in) || usable(out) || usable(err)) { // started with pipes. theyre the childs pipes really si.dwFlags |= STARTF_USESTDHANDLES; si.hStdInput = in; si.hStdOutput = out; si.hStdError = err; inherit = TRUE; } PROCESS_INFORMATION pi = {}; if (CreateProcessW(exe.c_str(), &cmd[0], nullptr, nullptr, inherit, 0, nullptr, cwd.c_str(), &si, &pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return true; } DWORD why = GetLastError(); if (why != ERROR_ELEVATION_REQUIRED) { SetLastError(why); return false; } // the apps manifest wants admin. CreateProcess wont ask, the shell will SHELLEXECUTEINFOW sx = {}; sx.cbSize = sizeof(sx); sx.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI; sx.lpFile = exe.c_str(); sx.lpParameters = rest; sx.lpDirectory = cwd.c_str(); sx.nShow = (mine.dwFlags & STARTF_USESHOWWINDOW) ? mine.wShowWindow : SW_SHOWNORMAL; return ShellExecuteExW(&sx) != FALSE; } static void tell_user(const std::wstring& text) { std::wstring title = leaf(g_root); if (title.empty()) title = L"Garage"; MessageBoxW(nullptr, text.c_str(), title.c_str(), MB_OK | MB_ICONERROR | MB_SETFOREGROUND); } // apply swaps the stub by renaming the running one out of the way, and a // running exe cant be deleted. so what it leaves gets cleared up by whoever // comes along next static void sweep_old_stubs() { std::wstring prefix = leaf(g_self) + L".old"; WIN32_FIND_DATAW fd; HANDLE find = FindFirstFileW(lp(join(g_root, prefix + L"*")).c_str(), &fd); if (find == INVALID_HANDLE_VALUE) return; do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; if (!starts_with(fd.cFileName, prefix)) continue; std::wstring full = join(g_root, fd.cFileName); if (!DeleteFileW(lp(full).c_str())) log_fail(L"couldnt delete the old stub " + full, GetLastError()); } while (FindNextFileW(find, &fd)); FindClose(find); } static int run_app(const wchar_t* rest) { HANDLE lock = lock_named(L"state", 5000); // no lock is not a reason to leave somebody with a dead shortcut State st; bool hadFile = read_state(st); int rc = settle(st, false); if (rc != kOk) { unlock(lock); tell_user(L"This app could not be started because its files are missing. Installing it again will fix that."); return rc; } // a second click on the shortcut while the app is up. that one hands over // to the window thats allready there and goes away without ever saying // its healthy, so counting it would walk a perfectly good build on to // the block list bool allreadyUp = is_running(join(version_dir(g_root, st.current), st.exe)); const State asRead = st; long long run = st.current; if (!allreadyUp && st.failedStarts >= 3) { if (st.previous > 0 && st.previous != st.current && can_start(st, st.previous)) { log_line(L"build " + num(st.current) + L" didnt stay up " + num(st.failedStarts) + L" times in a row, blocking it and going back to build " + num(st.previous)); if (!st.is_blocked(st.current)) st.blocked.push_back(st.current); st.current = st.previous; st.previous = -1; st.failedStarts = 0; } else { log_line(L"build " + num(st.current) + L" keeps failing to start and theres nothing to go back to"); } } if (!allreadyUp) { if (st.failedStarts < 1000) st.failedStarts++; if (save_state(st)) { run = st.current; sweep_old_stubs(); } else { // program files, for anybody who isnt elevated. nothing above // happened then, and the start is counted for the user instead DWORD err = GetLastError(); if (err != ERROR_ACCESS_DENIED) { log_fail(hadFile ? L"couldnt write the state file, counting this start for the user instead" : L"couldnt write a new state file, counting this start for the user instead", err); } st = asRead; run = count_for_user(st); } } unlock(lock); std::wstring dir = version_dir(g_root, run); std::wstring exe = join(dir, st.exe); if (start_child(exe, dir, rest)) return kOk; DWORD err = GetLastError(); log_fail(L"couldnt start " + exe, err); // not counted as three strikes, it may only be a virus scanner holding the // file. the count above still goes up, so a build that is truely broken // gets blocked the normal way long long other = run == st.current ? st.previous : st.current; if (other > 0 && other != run && can_start(st, other)) { std::wstring oldDir = version_dir(g_root, other); std::wstring oldExe = join(oldDir, st.exe); if (start_child(oldExe, oldDir, rest)) { log_line(L"started build " + num(other) + L" for now instead"); return kOk; } log_fail(L"couldnt start " + oldExe + L" either", GetLastError()); } tell_user(L"This app could not be started (" + win_error(err) + L")."); return kCantStart; } static int run_exec(const wchar_t* p) { std::wstring rel; if (!next_arg(p, rel) || rel.empty()) { log_line(L"--garage-exec needs the exe to start"); return kBadArgs; } for (size_t i = 0; i < rel.size(); i++) { if (rel[i] == L'/') rel[i] = L'\\'; } // it has to stay inside the version folder bool inside = rel[0] != L'\\' && rel.find(L':') == std::wstring::npos; size_t from = 0; while (inside && from <= rel.size()) { size_t to = rel.find(L'\\', from); if (to == std::wstring::npos) to = rel.size(); if (rel.compare(from, to - from, L"..") == 0) inside = false; from = to + 1; } if (!inside) { log_line(L"--garage-exec was given a path that leaves the version folder: " + rel); return kExecMissing; } State st; read_state(st); int rc = settle(st, false); // not knowing the apps own exe doesnt matter here, we were told which one if (rc != kOk && rc != kNoExe) return rc; std::wstring dir = version_dir(g_root, st.current); std::wstring exe = join(dir, rel); if (!exists(exe)) { log_fail(L"--garage-exec: no " + exe, GetLastError()); return kExecMissing; } if (!start_child(exe, dir, p)) { log_fail(L"--garage-exec: couldnt start " + exe, GetLastError()); return kCantStart; } return kOk; } // ---- apply ---- static bool move_retry(const std::wstring& from, const std::wstring& to) { DWORD err = 0; // a scanner likes to open everything thats just been written for (int i = 0; i < 15; i++) { if (MoveFileExW(lp(from).c_str(), lp(to).c_str(), 0)) return true; err = GetLastError(); if (err != ERROR_ACCESS_DENIED && err != ERROR_SHARING_VIOLATION) break; Sleep(200); } SetLastError(err); return false; } // things a run that died left in root. they all start with a dot static void sweep_leftovers() { WIN32_FIND_DATAW fd; HANDLE find = FindFirstFileW(lp(join(g_root, L".*")).c_str(), &fd); if (find == INVALID_HANDLE_VALUE) return; do { std::wstring name = fd.cFileName; if (name.compare(0, 8, L".unpack-") != 0 && name.compare(0, 7, L".trash-") != 0) continue; std::wstring full = join(g_root, name); if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { DWORD err = 0; if (!remove_tree(full, &err)) log_fail(L"couldnt clear out " + full, err); } else if (!DeleteFileW(lp(full).c_str())) { log_fail(L"couldnt delete " + full, GetLastError()); } } while (FindNextFileW(find, &fd)); FindClose(find); } // renamed first, deleted second. the rename is the test: it fails when // anything inside is still running, and then nothing has been touched static bool discard_dir(const std::wstring& dir, const std::wstring& tag) { std::wstring trash = join(g_root, L".trash-" + tag + L"-" + num((long long)GetTickCount())); if (!MoveFileExW(lp(dir).c_str(), lp(trash).c_str(), 0)) return false; DWORD err = 0; if (!remove_tree(trash, &err)) { // its out of the way at least. the next apply sweeps it log_fail(L"couldnt finish deleting " + trash, err); } return true; } // tar.exe takes its arguments in the ansi code page, so a path with anything // else in it turns to question marks. this finds a way to say the zip in // plain ascii: relative to root, or through a hard link in root static std::wstring zip_for_tar(const std::wstring& zip, std::wstring& link) { link.clear(); std::wstring prefix = g_root + L"\\"; if (starts_with(zip, prefix) && is_ascii(zip.substr(prefix.size()))) return zip.substr(prefix.size()); if (is_ascii(zip)) return zip; std::wstring name = L".unpack-" + num((long long)GetCurrentProcessId()) + L".zip"; if (CreateHardLinkW(lp(join(g_root, name)).c_str(), lp(zip).c_str(), nullptr)) { link = join(g_root, name); return name; } log_fail(L"couldnt link " + zip + L" in to root, handing tar the real path and hoping", GetLastError()); return zip; } static int unpack(const std::wstring& zip, const std::wstring& tmpName) { wchar_t sys[MAX_PATH]; UINT n = GetSystemDirectoryW(sys, ARRAYSIZE(sys)); if (n == 0 || n >= ARRAYSIZE(sys)) { log_fail(L"couldnt find the system folder", GetLastError()); return kNoTar; } std::wstring tar = join(sys, L"tar.exe"); if (!exists(tar)) { log_fail(L"theres no " + tar + L". it comes with windows 10 1803 and later, this one is older", GetLastError()); return kNoTar; } // what tar has to say goes in a file, and from there in to the log std::wstring notes = join(g_root, tmpName + L".txt"); SECURITY_ATTRIBUTES sa = {}; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; HANDLE out = CreateFileW(lp(notes).c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (out == INVALID_HANDLE_VALUE) { log_fail(L"couldnt make " + notes + L", unpacking without tars output", GetLastError()); out = nullptr; } std::wstring link; std::wstring args = L"-xf " + quote_arg(zip_for_tar(zip, link)) + L" -C " + tmpName; DWORD code = 1; // run from root, so the folder to unpack in to is a bare ascii name bool ran = run_wait(tar, args, g_root, out, code); DWORD err = GetLastError(); if (out) CloseHandle(out); if (!link.empty()) DeleteFileW(lp(link).c_str()); std::string said; read_file(notes, said, 4000); DeleteFileW(lp(notes).c_str()); if (!ran) { log_fail(L"couldnt run " + tar, err); return kTarFailed; } if (code != 0) { log_line(L"tar couldnt unpack " + zip + L", it exited " + num((long long)code) + L": " + widen(said)); return kTarFailed; } return kOk; } // a zip of the Release folder itself has everything one level down, and how // many levels depends on what made it. follow single folders untill theres // something beside them static std::wstring content_dir(const std::wstring& top) { std::wstring dir = top; for (int depth = 0; depth < 8; depth++) { std::wstring only; int dirs = 0, files = 0; WIN32_FIND_DATAW fd; HANDLE find = FindFirstFileW(lp(join(dir, L"*")).c_str(), &fd); if (find == INVALID_HANDLE_VALUE) break; do { std::wstring name = fd.cFileName; if (name == L"." || name == L"..") continue; if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { dirs++; only = name; } else { files++; } } while (FindNextFileW(find, &fd)); FindClose(find); if (files != 0 || dirs != 1) break; dir = join(dir, only); } return dir; } static void remove_old_versions(const State& st) { std::vector have = list_versions(g_root); for (size_t i = 0; i < have.size(); i++) { if (have[i] == st.current || have[i] == st.previous) continue; std::wstring dir = version_dir(g_root, have[i]); if (!discard_dir(dir, num(have[i]))) { // something out of it is still running. it goes next time log_fail(L"left " + dir + L" where it is, its in use", GetLastError()); } } } // every build has the stub it was built with in it, as garage_stub.exe. when // thats not the one in root any more, root gets it. we are the one in root // and a running exe cant be written over, but it can be renamed static void refresh_stub(long long build) { std::wstring fresh = join(version_dir(g_root, build), L"garage_stub.exe"); if (!exists(fresh)) return; std::string theirs, ours; const size_t cap = 64 * 1024 * 1024; if (!read_file(fresh, theirs, cap)) { log_fail(L"couldnt read " + fresh + L", keeping the stub thats here", GetLastError()); return; } if (!read_file(g_self, ours, cap)) { log_fail(L"couldnt read " + g_self + L" to compare it, keeping the stub thats here", GetLastError()); return; } if (theirs == ours) return; // half a file in root would be the end of the install if (theirs.size() < 1024 || theirs.size() > cap || theirs[0] != 'M' || theirs[1] != 'Z') { log_line(fresh + L" doesnt look like an exe, keeping the stub thats here"); return; } std::wstring old = g_self + L".old"; if (exists(old) && !DeleteFileW(lp(old).c_str())) { log_fail(L"couldnt delete " + old + L", using another name", GetLastError()); old += L"-" + num((long long)GetCurrentProcessId()) + L"-" + num((long long)GetTickCount()); } if (!move_retry(g_self, old)) { log_fail(L"couldnt move the stub out of the way, keeping it", GetLastError()); return; } if (!CopyFileW(lp(fresh).c_str(), lp(g_self).c_str(), TRUE)) { log_fail(L"couldnt copy " + fresh + L" to " + g_self + L", putting the old stub back", GetLastError()); if (!MoveFileExW(lp(old).c_str(), lp(g_self).c_str(), MOVEFILE_REPLACE_EXISTING)) { log_fail(L"and the old stub wouldnt go back. it is at " + old + L" and has to be renamed by hand", GetLastError()); } return; } // `old` is us and stays till the next start log_line(L"the stub is now the one out of build " + num(build)); } static int apply_locked(const std::wstring& zip, long long build) { sweep_leftovers(); sweep_old_stubs(); std::wstring tmpName = L".unpack-" + num(build) + L"-" + num((long long)GetCurrentProcessId()); std::wstring tmp = join(g_root, tmpName); if (!CreateDirectoryW(lp(tmp).c_str(), nullptr)) { DWORD err = GetLastError(); log_fail(L"couldnt make " + tmp, err); return err == ERROR_ACCESS_DENIED ? kNotWritable : kNoTemp; } State st; read_state(st); bool installed = settle(st, true) == kOk; std::wstring target = version_dir(g_root, build); if (installed && st.current == build) { // asked twice, or the installer run again over itself. the folder is // the one thats running so it stays as it is RemoveDirectoryW(lp(tmp).c_str()); st.failedStarts = 0; if (!save_state(st)) { log_fail(L"build " + num(build) + L" is allready current but the state file couldnt be written", GetLastError()); return kStateWrite; } return kOk; } if (exists(target) && !discard_dir(target, num(build))) { log_fail(L"theres an old " + target + L" in the way and it wont move", GetLastError()); RemoveDirectoryW(lp(tmp).c_str()); return kCantPlace; } int rc = unpack(zip, tmpName); DWORD cleanErr = 0; if (rc != kOk) { if (!remove_tree(tmp, &cleanErr)) log_fail(L"couldnt clear out " + tmp, cleanErr); return rc; } std::wstring content = content_dir(tmp); std::wstring exe = st.exe.empty() ? guess_exe(content) : st.exe; if (exe.empty() || !exists(join(content, exe))) { log_line(L"unpacked " + zip + L" but " + (exe.empty() ? std::wstring(L"an app exe") : exe) + L" isnt in it, so its not a build of this app"); if (!remove_tree(tmp, &cleanErr)) log_fail(L"couldnt clear out " + tmp, cleanErr); return exe.empty() ? kNoExe : kBadPackage; } if (!move_retry(content, target)) { log_fail(L"couldnt move " + content + L" to " + target, GetLastError()); if (!remove_tree(tmp, &cleanErr)) log_fail(L"couldnt clear out " + tmp, cleanErr); return kCantPlace; } // whats left is the shell of folders the build was sitting inside if (content != tmp && !remove_tree(tmp, &cleanErr)) log_fail(L"couldnt clear out " + tmp, cleanErr); HANDLE lock = lock_named(L"state", 5000); // read again, the app may have written to it while tar was busy State now; read_state(now); bool hadCurrent = settle(now, true) == kOk && now.current != build; now.exe = exe; now.previous = hadCurrent ? now.current : -1; now.current = build; now.failedStarts = 0; // being told to install it outranks an old block for (size_t i = 0; i < now.blocked.size();) { if (now.blocked[i] == build) now.blocked.erase(now.blocked.begin() + (ptrdiff_t)i); else i++; } bool saved = save_state(now); DWORD saveErr = GetLastError(); unlock(lock); if (!saved) { log_fail(L"build " + num(build) + L" is unpacked but the state file couldnt be written", saveErr); return kStateWrite; } // never a reason to fail, the build is in either way refresh_stub(build); remove_old_versions(now); log_line(L"build " + num(build) + L" is in, previous is " + (now.previous > 0 ? num(now.previous) : std::wstring(L"none"))); return kOk; } static int run_apply(const wchar_t* p) { std::wstring zipArg, buildArg; if (!next_arg(p, zipArg) || !next_arg(p, buildArg)) { log_line(L"--garage-apply needs a zip and a build number"); return kBadArgs; } long long build = 0; if (!parse_version_name(L"app-" + buildArg, build)) { log_line(L"--garage-apply: \"" + buildArg + L"\" isnt a build number"); return kBadArgs; } std::wstring zip = absolute(zipArg); if (file_size(zip) < 0) { log_fail(L"--garage-apply: no " + zip, GetLastError()); return kZipMissing; } // one at a time. the second one in waits for the first, it doesnt race it HANDLE lock = lock_named(L"apply", 120000); if (!lock) return kBusy; int rc = apply_locked(zip, build); unlock(lock); return rc; } // ---- uninstall ---- // the installer leaves what it made in the uninstall entry: the shortcuts as // GarageShortcuts. so the entry is found by its InstallLocation being us, and // it says the rest. static const wchar_t* kUninstallKey = L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; struct Entry { bool found = false; HKEY hive = nullptr; std::wstring key; std::wstring name; std::vector shortcuts; }; static std::wstring reg_text(HKEY key, const wchar_t* sub, const wchar_t* value, DWORD kind) { DWORD bytes = 0; if (RegGetValueW(key, sub, value, kind, nullptr, nullptr, &bytes) != ERROR_SUCCESS || bytes < sizeof(wchar_t)) { return L""; } std::wstring out(bytes / sizeof(wchar_t) + 1, L'\0'); bytes = (DWORD)(out.size() * sizeof(wchar_t)); if (RegGetValueW(key, sub, value, kind, nullptr, &out[0], &bytes) != ERROR_SUCCESS) return L""; out.resize(bytes / sizeof(wchar_t)); return out; } static std::wstring trim_slash(std::wstring p) { while (!p.empty() && (p[p.size() - 1] == L'\\' || p[p.size() - 1] == L'/' || p[p.size() - 1] == L'\0')) { p.resize(p.size() - 1); } return p; } static bool find_entry(HKEY hive, Entry& out) { HKEY all = nullptr; LSTATUS rc = RegOpenKeyExW(hive, kUninstallKey, 0, KEY_READ | KEY_WOW64_64KEY, &all); if (rc != ERROR_SUCCESS) { if (rc != ERROR_FILE_NOT_FOUND) log_fail(L"couldnt open the uninstall list", (DWORD)rc); return false; } wchar_t sub[256]; for (DWORD i = 0;; i++) { DWORD len = ARRAYSIZE(sub); rc = RegEnumKeyExW(all, i, sub, &len, nullptr, nullptr, nullptr, nullptr); if (rc == ERROR_NO_MORE_ITEMS) break; if (rc != ERROR_SUCCESS) continue; std::wstring where = trim_slash(reg_text(all, sub, L"InstallLocation", RRF_RT_REG_SZ)); if (where.empty() || !same_text(where, g_root)) continue; out.found = true; out.hive = hive; out.key = std::wstring(kUninstallKey) + L"\\" + sub; out.name = trim_slash(reg_text(all, sub, L"DisplayName", RRF_RT_REG_SZ)); std::wstring multi = reg_text(all, sub, L"GarageShortcuts", RRF_RT_REG_MULTI_SZ); size_t from = 0; while (from < multi.size()) { size_t to = multi.find(L'\0', from); if (to == std::wstring::npos) to = multi.size(); if (to > from) out.shortcuts.push_back(multi.substr(from, to - from)); from = to + 1; } break; } RegCloseKey(all); return out.found; } static bool root_writable() { std::wstring probe = join(g_root, L".probe-" + num((long long)GetCurrentProcessId())); HANDLE h = CreateFileW(lp(probe).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); if (h == INVALID_HANDLE_VALUE) return false; CloseHandle(h); return true; } static bool can_delete_entry(const Entry& entry) { if (!entry.found) return true; HKEY k = nullptr; if (RegOpenKeyExW(entry.hive, entry.key.c_str(), 0, DELETE | KEY_SET_VALUE | KEY_WOW64_64KEY, &k) != ERROR_SUCCESS) { return false; } RegCloseKey(k); return true; } // anything running out of root has its files locked, and the stash agent has // no window for anybody to close. so theyre stopped static void stop_running() { std::wstring prefix = g_root + L"\\"; std::vector all = running(); for (size_t i = 0; i < all.size(); i++) { // the one thing in root itself is the stub, which may be the // un-elevated us waiting on the elevated us if (!starts_with(all[i].path, prefix) || same_text(all[i].path, g_self)) continue; HANDLE proc = OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE, FALSE, all[i].pid); if (!proc) { log_fail(L"couldnt open " + all[i].path + L" to stop it", GetLastError()); continue; } if (!TerminateProcess(proc, 1)) { log_fail(L"couldnt stop " + all[i].path, GetLastError()); } else { WaitForSingleObject(proc, 5000); } CloseHandle(proc); } } // we cant delete ourselves while running. cmd waits a couple of seconds and // does it, then takes root away if its empty by then. the paths go through // the environment so nothing in them (a %, an &) gets read as part of the // command static void delete_self_later() { wchar_t sys[MAX_PATH]; UINT n = GetSystemDirectoryW(sys, ARRAYSIZE(sys)); if (n == 0 || n >= ARRAYSIZE(sys)) { log_fail(L"couldnt find the system folder, the stub is left behind", GetLastError()); return; } SetEnvironmentVariableW(L"GARAGE_RM_EXE", g_self.c_str()); SetEnvironmentVariableW(L"GARAGE_RM_DIR", g_root.c_str()); std::wstring cmd = join(sys, L"cmd.exe"); std::wstring line = quote_arg(cmd) + L" /d /s /c \"ping -n 3 127.0.0.1 >nul" L" & del /f /q \"%GARAGE_RM_EXE%\" >nul 2>&1" L" & ping -n 4 127.0.0.1 >nul" L" & (if exist \"%GARAGE_RM_EXE%\" del /f /q \"%GARAGE_RM_EXE%\" >nul 2>&1)" L" & rd \"%GARAGE_RM_DIR%\" >nul 2>&1\""; STARTUPINFOW si = {}; si.cb = sizeof(si); PROCESS_INFORMATION pi = {}; // started in system32. if it sat in root, root could never be removed if (!CreateProcessW(cmd.c_str(), &line[0], nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, sys, &si, &pi)) { log_fail(L"couldnt start cmd to remove the stub, its left behind", GetLastError()); return; } CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } static int run_uninstall(const wchar_t* p) { bool quiet = false, elevated = false; std::wstring a; while (next_arg(p, a)) { if (a == L"--quiet") quiet = true; if (a == L"--elevated") elevated = true; } Entry entry; if (!find_entry(HKEY_CURRENT_USER, entry)) find_entry(HKEY_LOCAL_MACHINE, entry); // a copy of the stub run from the desktop mustnt go deleting whats around it if (!entry.found && !exists(state_path(g_root))) { log_line(L"--garage-uninstall: " + g_root + L" isnt an install, not touching it"); return kNotAnInstall; } std::wstring name = entry.name.empty() ? leaf(g_root) : entry.name; if (!quiet) { std::wstring ask = L"Remove " + name + L" and all of its files from this PC?"; if (MessageBoxW(nullptr, ask.c_str(), name.c_str(), MB_YESNO | MB_ICONQUESTION | MB_SETFOREGROUND) != IDYES) { return kCancelled; } } if (!root_writable() || !can_delete_entry(entry)) { if (elevated) { log_fail(L"--garage-uninstall: elevated and still cant write to " + g_root, GetLastError()); return kNoElevation; } // an "everyone" install. settings starts the uninstaller as the user SHELLEXECUTEINFOW sx = {}; sx.cbSize = sizeof(sx); sx.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC; sx.lpVerb = L"runas"; sx.lpFile = g_self.c_str(); sx.lpParameters = L"--garage-uninstall --quiet --elevated"; sx.nShow = SW_HIDE; if (!ShellExecuteExW(&sx) || !sx.hProcess) { DWORD err = GetLastError(); log_fail(L"--garage-uninstall: couldnt get administrator permission", err); return err == ERROR_CANCELLED ? kCancelled : kNoElevation; } WaitForSingleObject(sx.hProcess, INFINITE); DWORD code = (DWORD)kNoElevation; GetExitCodeProcess(sx.hProcess, &code); CloseHandle(sx.hProcess); if (code != 0 && !quiet) { tell_user(name + L" could not be removed completely. Close it and try again."); } return (int)code; } stop_running(); // the files first. if some wont go, the entry and the shortcuts stay so // it can be tried again from the same place bool clean = true; std::vector have = list_versions(g_root); for (size_t i = 0; i < have.size(); i++) { std::wstring dir = version_dir(g_root, have[i]); DWORD err = 0; if (!remove_tree(dir, &err)) { log_fail(L"--garage-uninstall: couldnt remove " + dir, err); clean = false; } } if (!clean) { if (!quiet) tell_user(name + L" could not be removed completely. Close it and try again."); return kLeftovers; } sweep_leftovers(); sweep_old_stubs(); State st; read_state(st); std::wstring appId = st.extra("app_id"); std::wstring staging = join(g_root, L"staging"); DWORD err = 0; if (exists(staging) && !remove_tree(staging, &err)) log_fail(L"--garage-uninstall: couldnt remove " + staging, err); // downloads for an "everyone" install go here instead. only that folder, // whatever else the app keeps beside it is the users std::wstring local = env(L"LOCALAPPDATA"); if (!local.empty()) { std::wstring mine = join(local, appId.empty() ? leaf(g_root) : appId); std::wstring theirs = join(mine, L"staging"); err = 0; if (exists(theirs) && !remove_tree(theirs, &err)) log_fail(L"--garage-uninstall: couldnt remove " + theirs, err); DeleteFileW(lp(join(mine, L"garage_updates.log")).c_str()); DeleteFileW(lp(join(mine, L"garage_updates.log.old")).c_str()); // the count of starts, when it was kept out here std::wstring counts = join(mine, L"garage_updates.json"); if (exists(counts) && !DeleteFileW(lp(counts).c_str())) { log_fail(L"--garage-uninstall: couldnt delete " + counts, GetLastError()); } // only goes if that left it empty RemoveDirectoryW(lp(mine).c_str()); } for (size_t i = 0; i < entry.shortcuts.size(); i++) { const std::wstring& lnk = entry.shortcuts[i]; // its a list out of the registry. only ever delete a shortcut off it if (lnk.size() < 5 || !same_text(lnk.substr(lnk.size() - 4), L".lnk")) continue; if (!DeleteFileW(lp(lnk).c_str())) { DWORD why = GetLastError(); if (why != ERROR_FILE_NOT_FOUND && why != ERROR_PATH_NOT_FOUND) { log_fail(L"--garage-uninstall: couldnt delete " + lnk, why); clean = false; } } } if (entry.found) { LSTATUS rc = RegDeleteKeyExW(entry.hive, entry.key.c_str(), KEY_WOW64_64KEY, 0); if (rc != ERROR_SUCCESS && rc != ERROR_FILE_NOT_FOUND) { log_fail(L"--garage-uninstall: couldnt remove the uninstall entry", (DWORD)rc); clean = false; } } std::wstring statePath = state_path(g_root); if (exists(statePath) && !DeleteFileW(lp(statePath).c_str())) { log_fail(L"--garage-uninstall: couldnt delete " + statePath, GetLastError()); clean = false; } // the log goes last and only when theres nothing in it worth keeping if (clean) { DeleteFileW(lp(join(g_root, L"garage_updates.log")).c_str()); DeleteFileW(lp(join(g_root, L"garage_updates.log.old")).c_str()); } delete_self_later(); return clean ? kOk : kLeftovers; } static bool find_self() { std::wstring buf(512, L'\0'); for (;;) { DWORD n = GetModuleFileNameW(nullptr, &buf[0], (DWORD)buf.size()); if (n == 0) return false; if (n < buf.size()) { buf.resize(n); break; } if (buf.size() > 40000) return false; buf.resize(buf.size() * 2); } // started through a \\?\ path. nothing after us wants the prefix if (buf.compare(0, 8, L"\\\\?\\UNC\\") == 0) buf = L"\\\\" + buf.substr(8); else if (buf.compare(0, 4, L"\\\\?\\") == 0) buf = buf.substr(4); g_self = buf; g_root = parent(buf); return !g_root.empty(); } int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) { if (!find_self()) { log_fail(L"couldnt work out where the stub is", GetLastError()); return kNoSelf; } // only for where the fallback log goes, so a state file that wont read is // not worth a word here. whoever needs it properly says so std::string text; State peek; if (read_file(state_path(g_root), text, 1024 * 1024) && parse_state(text, peek)) g_appId = peek.extra("app_id"); if (g_appId.find_first_of(L"\\/:*?\"<>|") != std::wstring::npos) g_appId.clear(); const wchar_t* rest = skip_program(GetCommandLineW()); const wchar_t* after = rest; std::wstring first; if (next_arg(after, first)) { if (first == L"--garage-exec") return run_exec(after); if (first == L"--garage-apply") return run_apply(after); if (first == L"--garage-uninstall") return run_uninstall(after); } return run_app(rest); }