bool CWin32PowerStateWorker::PowerManagement(PowerState State) { static bool gotShutdownPrivileges = false; if (!gotShutdownPrivileges) { HANDLE hToken; // Get a token for this process. if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { // Get the LUID for the shutdown privilege. TOKEN_PRIVILEGES tkp = {}; if (LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid)) { tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get the shutdown privilege for this process. if (AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0)) gotShutdownPrivileges = true; } CloseHandle(hToken); } if (!gotShutdownPrivileges) return false; } switch (State) { case POWERSTATE_HIBERNATE: CLog::Log(LOGINFO, "Asking Windows to hibernate..."); return SetSuspendState(true, true, false) == TRUE; case POWERSTATE_SUSPEND: CLog::Log(LOGINFO, "Asking Windows to suspend..."); return SetSuspendState(false, true, false) == TRUE; case POWERSTATE_SHUTDOWN: CLog::Log(LOGINFO, "Shutdown Windows..."); if (g_sysinfo.IsWindowsVersionAtLeast(CSysInfo::WindowsVersionWin8)) return InitiateShutdownW(NULL, NULL, 0, SHUTDOWN_HYBRID | SHUTDOWN_INSTALL_UPDATES | SHUTDOWN_POWEROFF, SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED) == ERROR_SUCCESS; return InitiateShutdownW(NULL, NULL, 0, SHUTDOWN_INSTALL_UPDATES | SHUTDOWN_POWEROFF, SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED) == ERROR_SUCCESS; case POWERSTATE_REBOOT: CLog::Log(LOGINFO, "Rebooting Windows..."); if (g_sysinfo.IsWindowsVersionAtLeast(CSysInfo::WindowsVersionWin8)) return InitiateShutdownW(NULL, NULL, 0, SHUTDOWN_INSTALL_UPDATES | SHUTDOWN_RESTART, SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED) == ERROR_SUCCESS; return InitiateShutdownW(NULL, NULL, 0, SHUTDOWN_INSTALL_UPDATES | SHUTDOWN_RESTART, SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED) == ERROR_SUCCESS; default: CLog::Log(LOGERROR, "Unknown PowerState called."); return false; } }
void PerformanceMonitor::OnTrafficSleep(UINT /*notify_code*/, int /*id*/, CWindow /*control*/) { if (block_) { sleep_ = !sleep_; } else { sleep_ = false; SetSuspendState(FALSE, FALSE, FALSE); } }
void QMPlay2CoreClass::suspend() { #if defined Q_OS_LINUX Q_UNUSED(system("systemctl suspend > /dev/null 2>&1 &")); #elif defined Q_OS_WIN SetSuspendState(false, false, false); #elif defined Q_OS_MACOS Q_UNUSED(system("pmset sleepnow > /dev/null 2>&1 &")); #endif }
static DWORD WINAPI do_suspend(LPVOID opaque) { GuestSuspendMode *mode = opaque; DWORD ret = 0; if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) { slog("failed to suspend guest, %s", GetLastError()); ret = -1; } g_free(mode); return ret; }
void Shutdown(POWER_MODE Mode) { HANDLE hToken; TOKEN_PRIVILEGES tkp; if (OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken)) { LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken,FALSE,&tkp,0,(PTOKEN_PRIVILEGES)NULL,0); } if (Mode==POWERMODE_OFF) ExitWindowsEx(EWX_SHUTDOWN|EWX_FORCE,SHTDN_REASON_FLAG_PLANNED); if (Mode==POWERMODE_SLEEP) SetSuspendState(FALSE,FALSE,FALSE); if (Mode==POWERMODE_HIBERNATE) SetSuspendState(TRUE,FALSE,FALSE); if (Mode==POWERMODE_RESTART) ExitWindowsEx(EWX_REBOOT|EWX_FORCE,SHTDN_REASON_FLAG_PLANNED); }
void PerformanceMonitor::OnTimer(UINT_PTR /*timer_id*/) { std::vector<double> cpu; if (cpu_counter_->Next(&cpu) && !cpu.empty()) { auto max = std::max_element(cpu.begin(), cpu.end()); if (*max > cpu_usage_threshold_) cpu_time_ = 0; else ++cpu_time_; } std::vector<double> disk; if (disk_counter_->Next(&disk) && !disk.empty()) { auto max = std::max_element(disk.begin(), disk.end()); if (*max > disk_usage_threshold_) disk_time_ = 0; else ++disk_time_; } std::vector<double> traffic; if (traffic_counter_->Next(&traffic) && !traffic.empty()) { auto total = std::accumulate(traffic.begin(), traffic.end(), 0.0); if (total > traffic_threshold_) traffic_time_ = 0; else ++traffic_time_; } if (!enabled_) return; auto would_block = monitor_cpu_ && cpu_time_ < cpu_time_threshold_ || monitor_disk_ && disk_time_ < disk_time_threshold_ || monitor_traffic_ && traffic_time_ < traffic_time_threshold_; if (block_ && !would_block) { UnblockShutdown(); if (sleep_) { sleep_ = false; SetSuspendState(FALSE, FALSE, FALSE); } } else if (!block_ && would_block) { BlockShutdown(); } }
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { if (!lpCmdLine) return 1; if (!*lpCmdLine) { DWORD ppid = getppid(); HANDLE pproc = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ppid); if (pproc) { WaitForSingleObject(pproc, INFINITE); SetSuspendState(TRUE, FALSE, FALSE); } } else { run(__argv[0], FALSE); run(lpCmdLine, TRUE); } return 0; }
bool SystemSleep(bool hibernate) { if (!GetSeShutdownNamePrivelege()) { std::string msg = Utilities::MakeString() << __FUNCTION__": GetSeShutdownNamePrivelege() failed."; BOOST_LOG_SEV(logger(), error) << msg; return false; } const bool force = true; if (!SetSuspendState(hibernate, force, false) ) { DWORD last_error = GetLastError(); std::string msg = Utilities::MakeString() << __FUNCTION__": SetSuspendState(" << hibernate << ", " << force << ", " << false << ") failed. Reason: " << last_error; BOOST_LOG_SEV(logger(), error) << msg; return false; } return true; }
int __cdecl main(int argc,char **argv) { int i, now = 0; for(i = 1; i < argc; i++){ if(!_stricmp(argv[i],"now")) now = 1; } if(now == 0){ show_help(); return EXIT_SUCCESS; } printf("Hibernate for Windows - a command line tool for Windows hibernation.\n"); printf("Copyright (c) UltraDefrag Development Team, 2009-2013.\n\n"); if(winx_init_library() < 0){ fprintf(stderr,"Initialization failed!\n"); return EXIT_FAILURE; } if(winx_enable_privilege(SE_SHUTDOWN_PRIVILEGE) < 0){ fprintf(stderr,"Cannot enable shutdown privilege!\n" "Use DbgView program to get more information.\n"); return EXIT_FAILURE; } /* hibernate, request permission from apps and drivers */ if(!SetSuspendState(TRUE,FALSE,FALSE)){ letrace("cannot hibernate the computer"); fprintf(stderr,"Cannot hibernate the computer!\n" "Use DbgView program to get more information.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; }
void Utils::Misc::shutdownComputer(const ShutdownDialogAction &action) { #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) && defined(QT_DBUS_LIB) // Use dbus to power off / suspend the system if (action != ShutdownDialogAction::Shutdown) { // Some recent systems use systemd's logind QDBusInterface login1Iface("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus()); if (login1Iface.isValid()) { if (action == ShutdownDialogAction::Suspend) login1Iface.call("Suspend", false); else login1Iface.call("Hibernate", false); return; } // Else, other recent systems use UPower QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", QDBusConnection::systemBus()); if (upowerIface.isValid()) { if (action == ShutdownDialogAction::Suspend) upowerIface.call("Suspend"); else upowerIface.call("Hibernate"); return; } // HAL (older systems) QDBusInterface halIface("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer", "org.freedesktop.Hal.Device.SystemPowerManagement", QDBusConnection::systemBus()); if (action == ShutdownDialogAction::Suspend) halIface.call("Suspend", 5); else halIface.call("Hibernate"); } else { // Some recent systems use systemd's logind QDBusInterface login1Iface("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus()); if (login1Iface.isValid()) { login1Iface.call("PowerOff", false); return; } // Else, other recent systems use ConsoleKit QDBusInterface consolekitIface("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager", "org.freedesktop.ConsoleKit.Manager", QDBusConnection::systemBus()); if (consolekitIface.isValid()) { consolekitIface.call("Stop"); return; } // HAL (older systems) QDBusInterface halIface("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer", "org.freedesktop.Hal.Device.SystemPowerManagement", QDBusConnection::systemBus()); halIface.call("Shutdown"); } #endif #ifdef Q_OS_MAC AEEventID EventToSend; if (action != ShutdownDialogAction::Shutdown) EventToSend = kAESleep; else EventToSend = kAEShutDown; AEAddressDesc targetDesc; static const ProcessSerialNumber kPSNOfSystemProcess = { 0, kSystemProcess }; AppleEvent eventReply = {typeNull, NULL}; AppleEvent appleEventToSend = {typeNull, NULL}; OSStatus error = AECreateDesc(typeProcessSerialNumber, &kPSNOfSystemProcess, sizeof(kPSNOfSystemProcess), &targetDesc); if (error != noErr) return; error = AECreateAppleEvent(kCoreEventClass, EventToSend, &targetDesc, kAutoGenerateReturnID, kAnyTransactionID, &appleEventToSend); AEDisposeDesc(&targetDesc); if (error != noErr) return; error = AESend(&appleEventToSend, &eventReply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, NULL, NULL); AEDisposeDesc(&appleEventToSend); if (error != noErr) return; AEDisposeDesc(&eventReply); #endif #ifdef Q_OS_WIN HANDLE hToken; // handle to process token TOKEN_PRIVILEGES tkp; // pointer to token structure if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return; // Get the LUID for shutdown privilege. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get shutdown privilege for this process. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0); // Cannot test the return value of AdjustTokenPrivileges. if (GetLastError() != ERROR_SUCCESS) return; if (action == ShutdownDialogAction::Suspend) SetSuspendState(false, false, false); else if (action == ShutdownDialogAction::Hibernate) SetSuspendState(true, false, false); else InitiateSystemShutdownA(0, QCoreApplication::translate("misc", "qBittorrent will shutdown the computer now because all downloads are complete.").toLocal8Bit().data(), 10, true, false); // Disable shutdown privilege. tkp.Privileges[0].Attributes = 0; AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0); #endif }
/* Main entry for program */ int wmain(int argc, WCHAR *argv[]) { DWORD error = ERROR_SUCCESS; struct CommandLineOptions opts; if (argc == 1) /* i.e. no commandline arguments given */ { PrintResourceString(IDS_USAGE); return EXIT_SUCCESS; } error = ParseArguments(&opts, argc, argv); if (error != ERROR_SUCCESS) { DisplayError(error); return EXIT_FAILURE; } /* If the user wants to abort a shutdown */ if (opts.abort) { /* First, the program has to determine if the shutdown/restart is local or remote. This is done since each one requires separate privileges. */ if (opts.remote_system == NULL) EnablePrivilege(SE_SHUTDOWN_NAME, TRUE); else EnablePrivilege(SE_REMOTE_SHUTDOWN_NAME, TRUE); /* Abort the delayed system shutdown specified. */ if (!AbortSystemShutdownW(opts.remote_system)) { PrintResourceString(IDS_ERROR_ABORT); DisplayError(GetLastError()); return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } /* * If the user wants to hibernate the computer. Assume * that the user wants to wake the computer up from * hibernation and it should not force it on the system. */ if (opts.hibernate) { if (IsPwrHibernateAllowed()) { EnablePrivilege(SE_SHUTDOWN_NAME, TRUE); /* The shutdown utility cannot hibernate remote systems */ if (opts.remote_system != NULL) { return EXIT_FAILURE; } if (!SetSuspendState(TRUE, FALSE, FALSE)) { PrintResourceString(IDS_ERROR_HIBERNATE); DisplayError(GetLastError()); return EXIT_FAILURE; } else { PrintResourceString(IDS_ERROR_HIBERNATE_ENABLED); return EXIT_SUCCESS; } } else { return EXIT_FAILURE; } } /* Both shutdown and restart flags cannot both be true */ if (opts.shutdown && opts.restart) { PrintResourceString(IDS_ERROR_SHUTDOWN_REBOOT); return EXIT_FAILURE; } /* Ensure that the timout amount is not too high or a negative number */ if ((opts.shutdown_delay < 0) || (opts.shutdown_delay > MAX_TIMEOUT)) { PrintResourceString(IDS_ERROR_TIMEOUT, opts.shutdown_delay); return EXIT_FAILURE; } /* If the user wants a GUI environment */ if (opts.show_gui) { if (ShutdownGuiMain(opts)) return EXIT_SUCCESS; else return EXIT_FAILURE; } if (opts.logoff && (opts.remote_system == NULL)) { /* * NOTE: Sometimes, shutdown and logoff are used together. If the logoff * flag is used by itself, then simply logoff. But if used with shutdown, * then skip logging off of the computer and eventually go to the action * for shutdown. */ if (!opts.shutdown && !opts.restart) { EnablePrivilege(SE_SHUTDOWN_NAME, TRUE); if (ExitWindowsEx(EWX_LOGOFF, opts.reason)) { return EXIT_SUCCESS; } else { PrintResourceString(IDS_ERROR_LOGOFF); DisplayError(GetLastError()); return EXIT_FAILURE; } } } /* * Since both shutting down the system and restarting calls the exact same * function, all we need to know is if we wanted to restart or shutdown. */ if (opts.shutdown || opts.restart) { /* * First, the program has to determine if the shutdown/restart is local * or remote. This is done since each one requires separate privileges. */ if (opts.remote_system == NULL) { EnablePrivilege(SE_SHUTDOWN_NAME, TRUE); } else { /* TODO: Remote shutdown is not supported yet */ // EnablePrivilege(SE_REMOTE_SHUTDOWN_NAME, TRUE); return EXIT_SUCCESS; } /** ** HACK: When InitiateSystemShutdownExW will become really implemented, ** activate this line and delete the other... ** if(!InitiateSystemShutdownExW(opts.remote_system, opts.message, opts.shutdown_delay, opts.force, opts.restart, opts.reason)) ***/ if (!ExitWindowsEx((opts.shutdown ? EWX_SHUTDOWN : EWX_REBOOT) | (opts.force ? EWX_FORCE : 0), opts.reason)) { /* * If there is an error, give the proper output depending * on whether the user wanted to shutdown or restart. */ if (opts.restart) PrintResourceString(IDS_ERROR_RESTART); else PrintResourceString(IDS_ERROR_SHUTDOWN); DisplayError(GetLastError()); return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } return EXIT_SUCCESS; }
//====================================================================== //lockdown monitor main function int main(int argc, char *argv[]){ HANDLE drvh; DWORD bytes, rxbytes; int i; TMemoryCmd MemCmd; if(argc < 2){ printf("\ninsufficient arguments: specify either 'true' or 'unte'"); exit(0); } if(!strcmp(argv[1], "true")) ldn_trusted_environment=1; else ldn_trusted_environment=0; if(ldn_trusted_environment){ #if defined (LDNVNET) printf("\nOpening device..."); drvh = CreateFile ( "\\\\.\\LDNVNET", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(drvh == INVALID_HANDLE_VALUE){ printf("\nFATAL: could not open handle to virtual ethernet driver!"); return -1; } printf("\nOpened ldnvnet successfully."); #endif } if(ldn_trusted_environment){ #if defined(LDNVNET) #if defined(SSLPA) //initialize sslpa ssl_pa_init(); #endif #endif } //printf("\npress any key to quit..."); while(1){ printf("\nWaiting for lockdown device command..."); //set the LED for this environment if(ldn_trusted_environment) ldn_verifier_setstate(GREEN_LED); else ldn_verifier_setstate(RED_LED); while(!ldn_verifier_checkbuttonstatus()){ if(ldn_trusted_environment){ #if defined (LDNVNET) memset(packetbuffer, 0, sizeof(packetbuffer)); memset(rxpacketbuffer, 0, sizeof(rxpacketbuffer)); if(!DeviceIoControl(drvh, IOCTL_LDNVNET_READ_DATA, NULL, 0, &packetbuffer, sizeof(packetbuffer), &bytes, NULL)){ printf("\nFATAL: could not send IOCTL!\n"); return -1; } if(bytes){ int j; //printf("\nTX: %u bytes successfully (dump follows):\n", bytes); //for(j=0; j < bytes; j++) // printf("0x%02x ", packetbuffer[j]); //first send a vendor request confirming size of TX packet MemCmd.dwAddress = 0x0; MemCmd.dwLength = bytes; i = usb_control_msg(hdl, BM_REQUEST_TYPE, 0xE0, 0, 0, (char *)&MemCmd, sizeof(MemCmd), 1000); if (i < 0){ printf("%s: usb_control_msg failed %d\n", __FUNCTION__, i); return -1; } //pass packet through analyzer #if defined(SSLPA) ssl_pa_analyze((unsigned char *)&packetbuffer, bytes); #endif //now write out the TX packet i = usb_bulk_write(hdl, NETIF_SEND_EP, (char *)&packetbuffer, bytes, 2000); if (i < 0) { printf("\nFATAL: usb_bulk_write failed %d", i); return -1; } } //see if we have any RX packets to receive bytes=ldnvf_read_packet(&rxpacketbuffer, hdl); if(bytes){ int j; //printf("\nRX: %u bytes, dump follows:\n", bytes); //for(j=0; j < packetlength; j++) // printf("0x%02x ", packetbuffer[j]); //pass packet through analyzer #if defined(SSLPA) ssl_pa_analyze((unsigned char *)&rxpacketbuffer, bytes); #endif if(!DeviceIoControl(drvh, IOCTL_LDNVNET_WRITE_DATA, &rxpacketbuffer, bytes, NULL, 0, &rxbytes, NULL)){ printf("\nFATAL: could not send IOCTL!\n"); return -1; } } #endif // LDNVNET } } printf("\ngot button press"); if(ldn_trusted_environment){ if(!CopyFile("e:\\grub\\menu_ue.lst", "e:\\grub\\menu.lst", FALSE)){ printf("\nfailed to set destination environment!"); exit(1); } }else{ if(!CopyFile("e:\\grub\\menu_te.lst", "e:\\grub\\menu.lst", FALSE)){ printf("\nfailed to set destination environment!"); exit(1); } } SetSuspendState(TRUE, FALSE,FALSE); printf("\ngot awake..."); } if(ldn_trusted_environment){ #if defined (LDNVNET) CloseHandle(drvh); #endif } return 0; }
bool PowerComponentWin::Suspend() { return SetSuspendState(false, true, false) == TRUE; }
bool Sleep() { return SetSuspendState(false, true, false) != 0; }
bool Hibernate() { return SetSuspendState(true, true, false) != 0; }
JNIEXPORT void JNICALL Java_keccs_hitTheHay_core_NativeInterface_hibernate(JNIEnv *env, jclass c) { SetSuspendState(1, 1, 0); }