/** * Starts the upgrade process for update of the service if it is * already installed. * * @param installDir the installation directory where * maintenanceservice_installer.exe is located. * @return TRUE if successful */ BOOL StartServiceUpdate(LPCWSTR installDir) { // Get a handle to the local computer SCM database SC_HANDLE manager = OpenSCManager(nullptr, nullptr, SC_MANAGER_ALL_ACCESS); if (!manager) { return FALSE; } // Open the service SC_HANDLE svc = OpenServiceW(manager, SVC_NAME, SERVICE_ALL_ACCESS); if (!svc) { CloseServiceHandle(manager); return FALSE; } // If we reach here, then the service is installed, so // proceed with upgrading it. CloseServiceHandle(manager); // The service exists and we opened it, get the config bytes needed DWORD bytesNeeded; if (!QueryServiceConfigW(svc, nullptr, 0, &bytesNeeded) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { CloseServiceHandle(svc); return FALSE; } // Get the service config information, in particular we want the binary // path of the service. mozilla::ScopedDeleteArray<char> serviceConfigBuffer(new char[bytesNeeded]); if (!QueryServiceConfigW(svc, reinterpret_cast<QUERY_SERVICE_CONFIGW*>(serviceConfigBuffer.get()), bytesNeeded, &bytesNeeded)) { CloseServiceHandle(svc); return FALSE; } CloseServiceHandle(svc); QUERY_SERVICE_CONFIGW &serviceConfig = *reinterpret_cast<QUERY_SERVICE_CONFIGW*>(serviceConfigBuffer.get()); PathUnquoteSpacesW(serviceConfig.lpBinaryPathName); // Obtain the temp path of the maintenance service binary WCHAR tmpService[MAX_PATH + 1] = { L'\0' }; if (!PathGetSiblingFilePath(tmpService, serviceConfig.lpBinaryPathName, L"maintenanceservice_tmp.exe")) { return FALSE; } // Get the new maintenance service path from the install dir WCHAR newMaintServicePath[MAX_PATH + 1] = { L'\0' }; wcsncpy(newMaintServicePath, installDir, MAX_PATH); PathAppendSafe(newMaintServicePath, L"maintenanceservice.exe"); // Copy the temp file in alongside the maintenace service. // This is a requirement for maintenance service upgrades. if (!CopyFileW(newMaintServicePath, tmpService, FALSE)) { return FALSE; } // Start the upgrade comparison process STARTUPINFOW si = {0}; si.cb = sizeof(STARTUPINFOW); // No particular desktop because no UI si.lpDesktop = L""; PROCESS_INFORMATION pi = {0}; WCHAR cmdLine[64] = { '\0' }; wcsncpy(cmdLine, L"dummyparam.exe upgrade", sizeof(cmdLine) / sizeof(cmdLine[0]) - 1); BOOL svcUpdateProcessStarted = CreateProcessW(tmpService, cmdLine, nullptr, nullptr, FALSE, 0, nullptr, installDir, &si, &pi); if (svcUpdateProcessStarted) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } return svcUpdateProcessStarted; }
/** * Installs or upgrades the SVC_NAME service. * If an existing service is already installed, we replace it with the * currently running process. * * @param action The action to perform. * @return TRUE if the service was installed/upgraded */ BOOL SvcInstall(SvcInstallAction action) { // Get a handle to the local computer SCM database with full access rights. nsAutoServiceHandle schSCManager(OpenSCManager(nullptr, nullptr, SC_MANAGER_ALL_ACCESS)); if (!schSCManager) { LOG_WARN(("Could not open service manager. (%d)", GetLastError())); return FALSE; } WCHAR newServiceBinaryPath[MAX_PATH + 1]; if (!GetModuleFileNameW(nullptr, newServiceBinaryPath, sizeof(newServiceBinaryPath) / sizeof(newServiceBinaryPath[0]))) { LOG_WARN(("Could not obtain module filename when attempting to " "install service. (%d)", GetLastError())); return FALSE; } // Check if we already have the service installed. nsAutoServiceHandle schService(OpenServiceW(schSCManager, SVC_NAME, SERVICE_ALL_ACCESS)); DWORD lastError = GetLastError(); if (!schService && ERROR_SERVICE_DOES_NOT_EXIST != lastError) { // The service exists but we couldn't open it LOG_WARN(("Could not open service. (%d)", GetLastError())); return FALSE; } if (schService) { // The service exists but it may not have the correct permissions. // This could happen if the permissions were not set correctly originally // or have been changed after the installation. This will reset the // permissions back to allow limited user accounts. if (!SetUserAccessServiceDACL(schService)) { LOG_WARN(("Could not reset security ACE on service handle. It might not be " "possible to start the service. This error should never " "happen. (%d)", GetLastError())); } // The service exists and we opened it DWORD bytesNeeded; if (!QueryServiceConfigW(schService, nullptr, 0, &bytesNeeded) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { LOG_WARN(("Could not determine buffer size for query service config. (%d)", GetLastError())); return FALSE; } // Get the service config information, in particular we want the binary // path of the service. mozilla::UniquePtr<char[]> serviceConfigBuffer(new char[bytesNeeded]); if (!QueryServiceConfigW(schService, reinterpret_cast<QUERY_SERVICE_CONFIGW*>(serviceConfigBuffer.get()), bytesNeeded, &bytesNeeded)) { LOG_WARN(("Could open service but could not query service config. (%d)", GetLastError())); return FALSE; } QUERY_SERVICE_CONFIGW &serviceConfig = *reinterpret_cast<QUERY_SERVICE_CONFIGW*>(serviceConfigBuffer.get()); // Check if we need to fix the service path BOOL servicePathWasWrong; static BOOL alreadyCheckedFixServicePath = FALSE; if (!alreadyCheckedFixServicePath) { if (!FixServicePath(schService, serviceConfig.lpBinaryPathName, servicePathWasWrong)) { LOG_WARN(("Could not fix service path. This should never happen. (%d)", GetLastError())); // True is returned because the service is pointing to // maintenanceservice_tmp.exe so it actually was upgraded to the // newest installed service. return TRUE; } else if (servicePathWasWrong) { // Now that the path is fixed we should re-attempt the install. // This current process' image path is maintenanceservice_tmp.exe. // The service used to point to maintenanceservice_tmp.exe. // The service was just fixed to point to maintenanceservice.exe. // Re-attempting an install from scratch will work as normal. alreadyCheckedFixServicePath = TRUE; LOG(("Restarting install action: %d", action)); return SvcInstall(action); } } // Ensure the service path is not quoted. We own this memory and know it to // be large enough for the quoted path, so it is large enough for the // unquoted path. This function cannot fail. PathUnquoteSpacesW(serviceConfig.lpBinaryPathName); // Obtain the existing maintenanceservice file's version number and // the new file's version number. Versions are in the format of // A.B.C.D. DWORD existingA, existingB, existingC, existingD; DWORD newA, newB, newC, newD; BOOL obtainedExistingVersionInfo = GetVersionNumberFromPath(serviceConfig.lpBinaryPathName, existingA, existingB, existingC, existingD); if (!GetVersionNumberFromPath(newServiceBinaryPath, newA, newB, newC, newD)) { LOG_WARN(("Could not obtain version number from new path")); return FALSE; } // Check if we need to replace the old binary with the new one // If we couldn't get the old version info then we assume we should // replace it. if (ForceInstallSvc == action || !obtainedExistingVersionInfo || (existingA < newA) || (existingA == newA && existingB < newB) || (existingA == newA && existingB == newB && existingC < newC) || (existingA == newA && existingB == newB && existingC == newC && existingD < newD)) { // We have a newer updater, so update the description from the INI file. UpdateServiceDescription(schService); schService.reset(); if (!StopService()) { return FALSE; } if (!wcscmp(newServiceBinaryPath, serviceConfig.lpBinaryPathName)) { LOG(("File is already in the correct location, no action needed for " "upgrade. The path is: \"%ls\"", newServiceBinaryPath)); return TRUE; } BOOL result = TRUE; // Attempt to copy the new binary over top the existing binary. // If there is an error we try to move it out of the way and then // copy it in. First try the safest / easiest way to overwrite the file. if (!CopyFileW(newServiceBinaryPath, serviceConfig.lpBinaryPathName, FALSE)) { LOG_WARN(("Could not overwrite old service binary file. " "This should never happen, but if it does the next " "upgrade will fix it, the service is not a critical " "component that needs to be installed for upgrades " "to work. (%d)", GetLastError())); // We rename the last 3 filename chars in an unsafe way. Manually // verify there are more than 3 chars for safe failure in MoveFileExW. const size_t len = wcslen(serviceConfig.lpBinaryPathName); if (len > 3) { // Calculate the temp file path that we're moving the file to. This // is the same as the proper service path but with a .old extension. LPWSTR oldServiceBinaryTempPath = new WCHAR[len + 1]; memset(oldServiceBinaryTempPath, 0, (len + 1) * sizeof (WCHAR)); wcsncpy(oldServiceBinaryTempPath, serviceConfig.lpBinaryPathName, len); // Rename the last 3 chars to 'old' wcsncpy(oldServiceBinaryTempPath + len - 3, L"old", 3); // Move the current (old) service file to the temp path. if (MoveFileExW(serviceConfig.lpBinaryPathName, oldServiceBinaryTempPath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { // The old binary is moved out of the way, copy in the new one. if (!CopyFileW(newServiceBinaryPath, serviceConfig.lpBinaryPathName, FALSE)) { // It is best to leave the old service binary in this condition. LOG_WARN(("The new service binary could not be copied in." " The service will not be upgraded.")); result = FALSE; } else { LOG(("The new service binary was copied in by first moving the" " old one out of the way.")); } // Attempt to get rid of the old service temp path. if (DeleteFileW(oldServiceBinaryTempPath)) { LOG(("The old temp service path was deleted: %ls.", oldServiceBinaryTempPath)); } else { // The old temp path could not be removed. It will be removed // the next time the user can't copy the binary in or on uninstall. LOG_WARN(("The old temp service path was not deleted.")); } } else { // It is best to leave the old service binary in this condition. LOG_WARN(("Could not move old service file out of the way from:" " \"%ls\" to \"%ls\". Service will not be upgraded. (%d)", serviceConfig.lpBinaryPathName, oldServiceBinaryTempPath, GetLastError())); result = FALSE; } delete[] oldServiceBinaryTempPath; } else { // It is best to leave the old service binary in this condition. LOG_WARN(("Service binary path was less than 3, service will" " not be updated. This should never happen.")); result = FALSE; } } else { LOG(("The new service binary was copied in.")); } // We made a copy of ourselves to the existing location. // The tmp file (the process of which we are executing right now) will be // left over. Attempt to delete the file on the next reboot. if (MoveFileExW(newServiceBinaryPath, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT)) { LOG(("Deleting the old file path on the next reboot: %ls.", newServiceBinaryPath)); } else { LOG_WARN(("Call to delete the old file path failed: %ls.", newServiceBinaryPath)); } return result; } // We don't need to copy ourselves to the existing location. // The tmp file (the process of which we are executing right now) will be // left over. Attempt to delete the file on the next reboot. MoveFileExW(newServiceBinaryPath, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT); // nothing to do, we already have a newer service installed return TRUE; } // If the service does not exist and we are upgrading, don't install it. if (UpgradeSvc == action) { // The service does not exist and we are upgrading, so don't install it return TRUE; } // Quote the path only if it contains spaces. PathQuoteSpacesW(newServiceBinaryPath); // The service does not already exist so create the service as on demand schService.own(CreateServiceW(schSCManager, SVC_NAME, SVC_DISPLAY_NAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, newServiceBinaryPath, nullptr, nullptr, nullptr, nullptr, nullptr)); if (!schService) { LOG_WARN(("Could not create Windows service. " "This error should never happen since a service install " "should only be called when elevated. (%d)", GetLastError())); return FALSE; } if (!SetUserAccessServiceDACL(schService)) { LOG_WARN(("Could not set security ACE on service handle, the service will not " "be able to be started from unelevated processes. " "This error should never happen. (%d)", GetLastError())); } UpdateServiceDescription(schService); return TRUE; }