// the bits the stub and the installer both need. header only and everything // is inline, so whichever of the two doesnt call a function doesnt get told // off about it. // // nothing in here logs. it leaves GetLastError alone for the caller to report. #pragma once #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0A00 #endif #ifndef NOMINMAX #define NOMINMAX #endif #include #include #include #include namespace garage { inline std::wstring widen(const std::string& s) { if (s.empty()) return L""; int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0); if (n <= 0) return L""; std::wstring w((size_t)n, L'\0'); MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), &w[0], n); return w; } inline std::string narrow(const std::wstring& w) { if (w.empty()) return ""; int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), nullptr, 0, nullptr, nullptr); if (n <= 0) return ""; std::string s((size_t)n, '\0'); WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), &s[0], n, nullptr, nullptr); return s; } inline std::wstring num(long long v) { return std::to_wstring(v); } // "5 Access is denied". winhttp keeps its own messages in its dll inline std::wstring win_error(DWORD code) { wchar_t buf[512]; DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; HMODULE from = nullptr; if (code >= 12000 && code < 12200) { from = GetModuleHandleW(L"winhttp.dll"); if (from) flags |= FORMAT_MESSAGE_FROM_HMODULE; } DWORD n = FormatMessageW(flags, from, code, 0, buf, ARRAYSIZE(buf), nullptr); while (n > 0 && (buf[n - 1] == L'\r' || buf[n - 1] == L'\n' || buf[n - 1] == L' ' || buf[n - 1] == L'.')) n--; std::wstring out = num(code); if (n > 0) { out += L" "; out.append(buf, n); } return out; } // ---- paths ---- // only long ones get the prefix. with it on nothing is normalised any more, // so short paths are better off without inline std::wstring lp(const std::wstring& p) { if (p.size() < 240) return p; if (p.compare(0, 4, L"\\\\?\\") == 0) return p; if (p.compare(0, 2, L"\\\\") == 0) return L"\\\\?\\UNC\\" + p.substr(2); if (p.size() > 2 && p[1] == L':') return L"\\\\?\\" + p; return p; } inline std::wstring join(const std::wstring& a, const std::wstring& b) { if (a.empty()) return b; wchar_t last = a[a.size() - 1]; if (last == L'\\' || last == L'/') return a + b; return a + L"\\" + b; } inline std::wstring parent(const std::wstring& p) { size_t at = p.find_last_of(L"\\/"); if (at == std::wstring::npos) return L""; return p.substr(0, at); } inline std::wstring leaf(const std::wstring& p) { size_t at = p.find_last_of(L"\\/"); if (at == std::wstring::npos) return p; return p.substr(at + 1); } inline bool exists(const std::wstring& p) { return GetFileAttributesW(lp(p).c_str()) != INVALID_FILE_ATTRIBUTES; } inline bool is_dir(const std::wstring& p) { DWORD a = GetFileAttributesW(lp(p).c_str()); return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY) != 0; } inline std::wstring absolute(const std::wstring& p) { DWORD need = GetFullPathNameW(p.c_str(), 0, nullptr, nullptr); if (need == 0) return p; std::wstring out((size_t)need, L'\0'); DWORD got = GetFullPathNameW(p.c_str(), need, &out[0], nullptr); if (got == 0 || got >= need) return p; out.resize(got); return out; } inline long long file_size(const std::wstring& p) { WIN32_FILE_ATTRIBUTE_DATA info; if (!GetFileAttributesExW(lp(p).c_str(), GetFileExInfoStandard, &info)) return -1; return ((long long)info.nFileSizeHigh << 32) | (long long)info.nFileSizeLow; } inline bool same_text(const std::wstring& a, const std::wstring& b) { return CompareStringOrdinal(a.data(), (int)a.size(), b.data(), (int)b.size(), TRUE) == CSTR_EQUAL; } inline bool starts_with(const std::wstring& s, const std::wstring& prefix) { if (s.size() < prefix.size()) return false; return CompareStringOrdinal(s.data(), (int)prefix.size(), prefix.data(), (int)prefix.size(), TRUE) == CSTR_EQUAL; } inline bool is_ascii(const std::wstring& s) { for (size_t i = 0; i < s.size(); i++) { if (s[i] > 126 || s[i] < 32) return false; } return true; } // deletes a folder and whats in it. keeps going past things it cant delete // and hands back the first error, the caller says what to do about it inline bool remove_tree(const std::wstring& dir, DWORD* firstError) { bool clean = true; WIN32_FIND_DATAW fd; HANDLE find = FindFirstFileW(lp(join(dir, L"*")).c_str(), &fd); if (find != INVALID_HANDLE_VALUE) { do { std::wstring name = fd.cFileName; if (name == L"." || name == L"..") continue; std::wstring full = join(dir, name); bool isDir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; bool isLink = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0; if (isDir && !isLink) { if (!remove_tree(full, firstError)) clean = false; continue; } if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) { SetFileAttributesW(lp(full).c_str(), fd.dwFileAttributes & ~(DWORD)FILE_ATTRIBUTE_READONLY); } // a junction is taken away as a folder, never walked in to BOOL gone = isDir ? RemoveDirectoryW(lp(full).c_str()) : DeleteFileW(lp(full).c_str()); if (!gone) { if (firstError && *firstError == 0) *firstError = GetLastError(); clean = false; } } while (FindNextFileW(find, &fd)); FindClose(find); } if (!RemoveDirectoryW(lp(dir).c_str())) { DWORD err = GetLastError(); if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND) { if (firstError && *firstError == 0) *firstError = err; clean = false; } } return clean; } inline bool read_file(const std::wstring& path, std::string& out, size_t cap) { out.clear(); HANDLE h = INVALID_HANDLE_VALUE; // the other side may be half way through swapping it for (int i = 0; i < 10; i++) { h = CreateFileW(lp(path).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h != INVALID_HANDLE_VALUE) break; if (GetLastError() != ERROR_SHARING_VIOLATION) return false; Sleep(20); } if (h == INVALID_HANDLE_VALUE) return false; char chunk[4096]; DWORD got = 0; bool ok = true; for (;;) { if (!ReadFile(h, chunk, sizeof(chunk), &got, nullptr)) { ok = false; break; } if (got == 0) break; out.append(chunk, got); if (out.size() > cap) break; } DWORD err = GetLastError(); CloseHandle(h); SetLastError(err); return ok; } // temp file beside it, then swapped in. a reader sees the old one or the new // one and never half of either inline bool write_atomic(const std::wstring& path, const std::string& bytes) { std::wstring tmp = path + L".tmp" + num((long long)GetCurrentProcessId()); HANDLE h = CreateFileW(lp(tmp).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_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) && wrote == (DWORD)bytes.size(); if (ok) FlushFileBuffers(h); DWORD err = GetLastError(); CloseHandle(h); if (!ok) { DeleteFileW(lp(tmp).c_str()); SetLastError(err); return false; } for (int i = 0; i < 20; i++) { if (MoveFileExW(lp(tmp).c_str(), lp(path).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { return true; } err = GetLastError(); // somebody has it open to read. they wont for long if (err != ERROR_SHARING_VIOLATION && err != ERROR_ACCESS_DENIED) break; Sleep(25); } DeleteFileW(lp(tmp).c_str()); SetLastError(err); return false; } // ---- json ---- // small, but a real parser. objects, arrays, strings, whole numbers, the // three words. a number with a fraction keeps the part before the dot. struct JVal { enum Kind { Null, Bool, Num, Str, Arr, Obj }; Kind kind = Null; bool b = false; long long n = 0; std::string s; std::vector keys; std::vector items; const JVal* get(const char* key) const { if (kind != Obj) return nullptr; for (size_t i = 0; i < keys.size(); i++) { if (keys[i] == key) return &items[i]; } return nullptr; } std::string str(const char* key) const { const JVal* v = get(key); return v && v->kind == Str ? v->s : std::string(); } long long number(const char* key, long long fallback) const { const JVal* v = get(key); return v && v->kind == Num ? v->n : fallback; } }; struct JParser { const char* p; const char* end; int depth; }; inline void j_ws(JParser& j) { while (j.p < j.end && (*j.p == ' ' || *j.p == '\t' || *j.p == '\r' || *j.p == '\n')) j.p++; } inline void j_utf8(std::string& out, unsigned long cp) { if (cp < 0x80) { out += (char)cp; } else if (cp < 0x800) { out += (char)(0xC0 | (cp >> 6)); out += (char)(0x80 | (cp & 0x3F)); } else if (cp < 0x10000) { out += (char)(0xE0 | (cp >> 12)); out += (char)(0x80 | ((cp >> 6) & 0x3F)); out += (char)(0x80 | (cp & 0x3F)); } else { out += (char)(0xF0 | (cp >> 18)); out += (char)(0x80 | ((cp >> 12) & 0x3F)); out += (char)(0x80 | ((cp >> 6) & 0x3F)); out += (char)(0x80 | (cp & 0x3F)); } } inline bool j_hex4(JParser& j, unsigned long& out) { if (j.end - j.p < 4) return false; out = 0; for (int i = 0; i < 4; i++) { char c = *j.p++; out <<= 4; if (c >= '0' && c <= '9') out |= (unsigned long)(c - '0'); else if (c >= 'a' && c <= 'f') out |= (unsigned long)(c - 'a' + 10); else if (c >= 'A' && c <= 'F') out |= (unsigned long)(c - 'A' + 10); else return false; } return true; } inline bool j_string(JParser& j, std::string& out) { if (j.p >= j.end || *j.p != '"') return false; j.p++; while (j.p < j.end) { char c = *j.p++; if (c == '"') return true; if (c != '\\') { out += c; continue; } if (j.p >= j.end) return false; char e = *j.p++; switch (e) { case 'n': out += '\n'; break; case 't': out += '\t'; break; case 'r': out += '\r'; break; case 'b': out += '\b'; break; case 'f': out += '\f'; break; case 'u': { unsigned long cp = 0; if (!j_hex4(j, cp)) return false; // two of them make one character above the bmp if (cp >= 0xD800 && cp < 0xDC00 && j.end - j.p >= 6 && j.p[0] == '\\' && j.p[1] == 'u') { JParser look = j; look.p += 2; unsigned long low = 0; if (j_hex4(look, low) && low >= 0xDC00 && low < 0xE000) { cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00); j.p = look.p; } } j_utf8(out, cp); break; } default: out += e; break; } } return false; } inline bool j_word(JParser& j, const char* word) { size_t n = strlen(word); if ((size_t)(j.end - j.p) < n || strncmp(j.p, word, n) != 0) return false; j.p += n; return true; } inline bool j_value(JParser& j, JVal& out) { j_ws(j); if (j.p >= j.end) return false; char c = *j.p; if (c == '"') { out.kind = JVal::Str; return j_string(j, out.s); } if (c == '{' || c == '[') { bool isObj = c == '{'; char close = isObj ? '}' : ']'; out.kind = isObj ? JVal::Obj : JVal::Arr; if (++j.depth > 32) return false; j.p++; j_ws(j); if (j.p < j.end && *j.p == close) { j.p++; j.depth--; return true; } for (;;) { if (isObj) { j_ws(j); std::string key; if (!j_string(j, key)) return false; j_ws(j); if (j.p >= j.end || *j.p != ':') return false; j.p++; out.keys.push_back(key); } out.items.push_back(JVal()); if (!j_value(j, out.items.back())) return false; j_ws(j); if (j.p >= j.end) return false; if (*j.p == ',') { j.p++; continue; } if (*j.p == close) { j.p++; j.depth--; return true; } return false; } } if (c == '-' || (c >= '0' && c <= '9')) { bool neg = c == '-'; if (neg) j.p++; if (j.p >= j.end || *j.p < '0' || *j.p > '9') return false; long long v = 0; while (j.p < j.end && *j.p >= '0' && *j.p <= '9') { if (v < 900000000000000000LL) v = v * 10 + (*j.p - '0'); j.p++; } // whatever comes after the whole part is stepped over while (j.p < j.end && (*j.p == '.' || *j.p == 'e' || *j.p == 'E' || *j.p == '+' || *j.p == '-' || (*j.p >= '0' && *j.p <= '9'))) { j.p++; } out.kind = JVal::Num; out.n = neg ? -v : v; return true; } if (j_word(j, "true")) { out.kind = JVal::Bool; out.b = true; return true; } if (j_word(j, "false")) { out.kind = JVal::Bool; out.b = false; return true; } if (j_word(j, "null")) { out.kind = JVal::Null; return true; } return false; } inline bool json_parse(const std::string& text, JVal& out) { JParser j; j.p = text.data(); j.end = text.data() + text.size(); j.depth = 0; // some editors put a bom on the front if (text.size() >= 3 && (unsigned char)text[0] == 0xEF && (unsigned char)text[1] == 0xBB && (unsigned char)text[2] == 0xBF) { j.p += 3; } if (!j_value(j, out)) return false; j_ws(j); return j.p == j.end; } inline std::string json_quote(const std::string& s) { static const char hex[] = "0123456789abcdef"; std::string out = "\""; for (size_t i = 0; i < s.size(); i++) { unsigned char c = (unsigned char)s[i]; if (c == '"' || c == '\\') { out += '\\'; out += (char)c; } else if (c < 0x20) { out += "\\u00"; out += hex[c >> 4]; out += hex[c & 15]; } else { out += (char)c; } } out += '"'; return out; } inline std::string json_print(const JVal& v) { switch (v.kind) { case JVal::Null: return "null"; case JVal::Bool: return v.b ? "true" : "false"; case JVal::Num: return std::to_string(v.n); case JVal::Str: return json_quote(v.s); default: break; } bool isObj = v.kind == JVal::Obj; std::string out = isObj ? "{" : "["; for (size_t i = 0; i < v.items.size(); i++) { if (i > 0) out += ", "; if (isObj) out += json_quote(v.keys[i]) + ": "; out += json_print(v.items[i]); } out += isObj ? "}" : "]"; return out; } // ---- garage_updates.json ---- struct State { std::wstring exe; long long current = -1; // -1 is "there isnt one" long long previous = -1; long long failedStarts = 0; std::vector blocked; // anything else thats in the file (the dart side keeps app_id in there). // not ours, so it goes back out the way it came in std::vector extraKeys; std::vector extraVals; std::wstring extra(const char* key) const { for (size_t i = 0; i < extraKeys.size(); i++) { if (extraKeys[i] == key && extraVals[i].kind == JVal::Str) return widen(extraVals[i].s); } return L""; } void set_extra(const char* key, const std::wstring& value) { JVal v; v.kind = JVal::Str; v.s = narrow(value); for (size_t i = 0; i < extraKeys.size(); i++) { if (extraKeys[i] == key) { extraVals[i] = v; return; } } extraKeys.push_back(key); extraVals.push_back(v); } bool is_blocked(long long build) const { for (size_t i = 0; i < blocked.size(); i++) { if (blocked[i] == build) return true; } return false; } }; inline bool parse_state(const std::string& text, State& st) { JVal root; if (!json_parse(text, root) || root.kind != JVal::Obj) return false; st = State(); st.exe = widen(root.str("exe")); st.current = root.number("current", -1); st.previous = root.number("previous", -1); st.failedStarts = root.number("failed_starts", 0); if (st.failedStarts < 0) st.failedStarts = 0; 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) st.blocked.push_back(blocked->items[i].n); } } for (size_t i = 0; i < root.keys.size(); i++) { const std::string& k = root.keys[i]; if (k == "exe" || k == "current" || k == "previous" || k == "failed_starts" || k == "blocked") continue; st.extraKeys.push_back(k); st.extraVals.push_back(root.items[i]); } return true; } inline std::string print_build(long long build) { return build > 0 ? std::to_string(build) : std::string("null"); } inline std::string print_state(const State& st) { std::string out = "{\n"; out += " \"exe\": " + json_quote(narrow(st.exe)) + ",\n"; out += " \"current\": " + print_build(st.current) + ",\n"; out += " \"previous\": " + print_build(st.previous) + ",\n"; out += " \"failed_starts\": " + std::to_string(st.failedStarts) + ",\n"; out += " \"blocked\": ["; for (size_t i = 0; i < st.blocked.size(); i++) { if (i > 0) out += ", "; out += std::to_string(st.blocked[i]); } out += "]"; for (size_t i = 0; i < st.extraKeys.size(); i++) { out += ",\n " + json_quote(st.extraKeys[i]) + ": " + json_print(st.extraVals[i]); } out += "\n}\n"; return out; } inline std::wstring state_path(const std::wstring& root) { return join(root, L"garage_updates.json"); } inline std::wstring version_dir(const std::wstring& root, long long build) { return join(root, L"app-" + num(build)); } // "app-12" and nothing else. a half unpacked folder has a different name on // purpose so it never gets past this inline bool parse_version_name(const std::wstring& name, long long& build) { if (name.size() < 5 || name.size() > 4 + 17) return false; if (name.compare(0, 4, L"app-") != 0) return false; long long v = 0; for (size_t i = 4; i < name.size(); i++) { if (name[i] < L'0' || name[i] > L'9') return false; v = v * 10 + (name[i] - L'0'); } if (v <= 0) return false; build = v; return true; } inline std::vector list_versions(const std::wstring& root) { std::vector out; WIN32_FIND_DATAW fd; HANDLE find = FindFirstFileW(lp(join(root, L"app-*")).c_str(), &fd); if (find == INVALID_HANDLE_VALUE) return out; do { long long build = 0; if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && parse_version_name(fd.cFileName, build)) { out.push_back(build); } } while (FindNextFileW(find, &fd)); FindClose(find); return out; } // ---- processes ---- // one argument, quoted so that CommandLineToArgvW on the other end gives // back exactly this inline std::wstring quote_arg(const std::wstring& arg) { if (!arg.empty() && arg.find_first_of(L" \t\"") == std::wstring::npos) return arg; std::wstring out = L"\""; size_t slashes = 0; for (size_t i = 0; i < arg.size(); i++) { wchar_t c = arg[i]; if (c == L'\\') { slashes++; continue; } if (c == L'"') { out.append(slashes * 2 + 1, L'\\'); } else { out.append(slashes, L'\\'); } slashes = 0; out += c; } // the ones at the very end sit in front of our closing quote out.append(slashes * 2, L'\\'); out += L"\""; return out; } // runs something with no window and waits for it. `output` (may be null) gets // its stdout and stderr and has to be an inheritable handle inline bool run_wait(const std::wstring& exe, const std::wstring& args, const std::wstring& cwd, HANDLE output, DWORD& exitCode) { std::wstring cmd = quote_arg(exe); if (!args.empty()) cmd += L" " + args; STARTUPINFOW si = {}; si.cb = sizeof(si); if (output) { si.dwFlags |= STARTF_USESTDHANDLES; si.hStdOutput = output; si.hStdError = output; } PROCESS_INFORMATION pi = {}; if (!CreateProcessW(exe.c_str(), &cmd[0], nullptr, nullptr, output ? TRUE : FALSE, CREATE_NO_WINDOW, nullptr, cwd.empty() ? nullptr : cwd.c_str(), &si, &pi)) { return false; } WaitForSingleObject(pi.hProcess, INFINITE); exitCode = 1; GetExitCodeProcess(pi.hProcess, &exitCode); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return true; } } // namespace garage