private void reportStatus(int status, int win32ExitCode, int waitHint) { SERVICE_STATUS serviceStatus = new SERVICE_STATUS(); serviceStatus.dwServiceType = WinNT.SERVICE_WIN32_OWN_PROCESS; serviceStatus.dwControlsAccepted = Winsvc.SERVICE_ACCEPT_STOP | Winsvc.SERVICE_ACCEPT_SHUTDOWN; serviceStatus.dwWin32ExitCode = win32ExitCode; serviceStatus.dwWaitHint = waitHint; serviceStatus.dwCurrentState = status; ADVAPI_32.SetServiceStatus(serviceStatusHandle, serviceStatus); }
private boolean isSubscribed() { return subscriptionHandle != null && subscriptionHandle.getPointer() != null; }
private SC_HANDLE openServiceControlManager(String machine, int access) { return ADVAPI_32.OpenSCManager(machine, null, access); }
/** * @param process NiFi Process Reference * @param logger Logger Reference for Debug * @return Returns pid or null in-case pid could not be determined * This method takes {@link Process} and {@link Logger} and returns * the platform specific Handle for Win32 Systems, a.k.a <b>pid</b> * In-case it fails to determine the pid, it will return Null. * Purpose for the Logger is to log any interaction for debugging. */ private static Long getWindowsProcessId(final Process process, final Logger logger) { /* determine the pid on windows plattforms */ try { Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long handl = f.getLong(process); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE handle = new WinNT.HANDLE(); handle.setPointer(Pointer.createConstant(handl)); int ret = kernel.GetProcessId(handle); logger.debug("Detected pid: {}", ret); return Long.valueOf(ret); } catch (final IllegalAccessException | NoSuchFieldException nsfe) { logger.debug("Could not find PID for child process due to {}", nsfe); } return null; }
public boolean stop() { boolean success = false; SC_HANDLE serviceManager = openServiceControlManager(null, WinNT.GENERIC_EXECUTE); if (serviceManager != null) { SC_HANDLE service = Advapi32.INSTANCE.OpenService(serviceManager, serviceName, WinNT.GENERIC_EXECUTE); if (service != null) { SERVICE_STATUS serviceStatus = new SERVICE_STATUS(); success = Advapi32.INSTANCE.ControlService(service, Winsvc.SERVICE_CONTROL_STOP, serviceStatus); Advapi32.INSTANCE.CloseServiceHandle(service); } Advapi32.INSTANCE.CloseServiceHandle(serviceManager); } return success; }
if (eventHandle.getPointer().getInt(0) == WEvtApi.EvtSubscribeErrors.ERROR_EVT_QUERY_RESULT_STALE) { logger.error(MISSING_EVENT_MESSAGE); } else { logger.error(RECEIVED_THE_FOLLOWING_WIN32_ERROR + eventHandle.getPointer().getInt(0)); if (kernel32.GetLastError() == W32Errors.ERROR_INSUFFICIENT_BUFFER) { int newMaxSize = used.getInt(0); int lastError = kernel32.GetLastError(); if (lastError == W32Errors.ERROR_SUCCESS) { int usedBytes = used.getInt(0);
W32API.HBITMAP outputBitmap = GDI.CreateCompatibleBitmap(windowDC, bounds.width, bounds.height); try W32API.HDC blitDC = GDI.CreateCompatibleDC(windowDC); try W32API.HANDLE oldBitmap = GDI.SelectObject(blitDC, outputBitmap); try GDI.SelectObject(blitDC, oldBitmap); GDI.DeleteObject(blitDC); GDI.DeleteObject(outputBitmap);
public String getLastError() { int lastError = kernel32.GetLastError(); return Arrays.stream(WinError.class.getDeclaredFields()).filter(field -> { try { return Modifier.isStatic(field.getModifiers()) && field.getType() == int.class && field.getName().startsWith("ERROR") && (int) field.get(null) == lastError; } catch (IllegalAccessException e) { return false; } }).map(field -> field.getName() + "(" + lastError + ")") .findFirst() .orElse(Integer.toString(lastError)); } }
public boolean start() { boolean success = false; SC_HANDLE serviceManager = openServiceControlManager(null, WinNT.GENERIC_EXECUTE); if (serviceManager != null) { SC_HANDLE service = ADVAPI_32.OpenService(serviceManager, serviceName, WinNT.GENERIC_EXECUTE); if (service != null) { success = ADVAPI_32.StartService(service, 0, null); ADVAPI_32.CloseServiceHandle(service); } ADVAPI_32.CloseServiceHandle(serviceManager); } return success; }
import com.sun.jna.Native; import com.sun.jna.platform.win32.*; import com.sun.jna.win32.W32APIOptions; public class ProcessList { public static void main(String[] args) { WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS); WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); while (winNT.Process32Next(snapshot, processEntry)) { System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile)); } winNT.CloseHandle(snapshot); } }
public boolean uninstall() { boolean success = false; SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS); if (serviceManager != null) { SC_HANDLE service = ADVAPI_32.OpenService(serviceManager, serviceName, Winsvc.SERVICE_ALL_ACCESS); if (service != null) { success = ADVAPI_32.DeleteService(service); ADVAPI_32.CloseServiceHandle(service); } ADVAPI_32.CloseServiceHandle(serviceManager); } return success; }
SERVICE_DESCRIPTION desc = new SERVICE_DESCRIPTION(); desc.lpDescription = description; SC_HANDLE service = ADVAPI_32.CreateService(serviceManager, serviceName, displayName, Winsvc.SERVICE_ALL_ACCESS, WinNT.SERVICE_WIN32_OWN_PROCESS, WinNT.SERVICE_AUTO_START, WinNT.SERVICE_ERROR_NORMAL, success = ADVAPI_32.ChangeServiceConfig2(service, Winsvc.SERVICE_CONFIG_DESCRIPTION, desc); ADVAPI_32.CloseServiceHandle(service); ADVAPI_32.CloseServiceHandle(serviceManager);
/** * Continue an existing authentication conversation with the back-end in resonse to an * authentication request of type AUTH_REQ_GSS_CONT. * * @param msgLength Length of message to read, excluding length word and message type word * @throws SQLException if something wrong happens * @throws IOException if something wrong happens */ public void continueSSPI(int msgLength) throws SQLException, IOException { if (sspiContext == null) { throw new IllegalStateException("Cannot continue SSPI authentication that we didn't begin"); } LOGGER.log(Level.FINEST, "Continuing SSPI negotiation"); /* Read the response token from the server */ byte[] receivedToken = pgStream.receive(msgLength); SecBufferDesc continueToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, receivedToken); sspiContext.initialize(sspiContext.getHandle(), continueToken, targetName); /* * Now send the response token. If negotiation is complete there may be zero bytes to send, in * which case we shouldn't send a reply as the server is not expecting one; see fe-auth.c in * libpq for details. */ byte[] responseToken = sspiContext.getToken(); if (responseToken.length > 0) { sendSSPIResponse(responseToken); LOGGER.log(Level.FINEST, "Sent SSPI negotiation continuation message"); } else { LOGGER.log(Level.FINEST, "SSPI authentication complete, no reply required"); } }
public interface Psapi extends StdCallLibrary { Psapi INSTANCE = (Psapi) Native.loadLibrary("Psapi", Psapi.class); WinDef.DWORD GetModuleBaseNameW(Pointer hProcess, Pointer hModule, byte[] lpBaseName, int nSize); } if (Platform.isWindows()) { final int PROCESS_VM_READ=0x0010; final int PROCESS_QUERY_INFORMATION=0x0400; final User32 user32 = User32.INSTANCE; final Kernel32 kernel32=Kernel32.INSTANCE; final Psapi psapi = Psapi.INSTANCE; WinDef.HWND windowHandle=user32.GetForegroundWindow(); IntByReference pid= new IntByReference(); user32.GetWindowThreadProcessId(windowHandle, pid); WinNT.HANDLE processHandle=kernel32.OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, true, pid.getValue()); byte[] filename = new byte[512]; Psapi.INSTANCE.GetModuleBaseNameW(processHandle.getPointer(), Pointer.NULL, filename, filename.length); String name=new String(filename); System.out.println(name); if (name.endsWith("wwahost.exe")) { // Metro App // There is no stable API to get the current Metro app // But you can guestimate the name form the current directory of the process // To query this, see: // http://stackoverflow.com/questions/16110936/read-other-process-current-directory-in-c-sharp }
public void init() throws URISyntaxException { String path = new File( WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent(); POSIXFactory.getPOSIX().chdir(path); System.setProperty("user.dir", path); serviceMain = new ServiceMain(); SERVICE_TABLE_ENTRY entry = new SERVICE_TABLE_ENTRY(); entry.lpServiceName = serviceName; entry.lpServiceProc = serviceMain; Advapi32.INSTANCE.StartServiceCtrlDispatcher((SERVICE_TABLE_ENTRY[]) entry.toArray(2)); }
break; case LWJGLUtil.PLATFORM_WINDOWS: String savedGamesPath = Shell32Util.getKnownFolderPath(KnownFolders.FOLDERID_SavedGames); if (savedGamesPath == null) { savedGamesPath = Shell32Util.getKnownFolderPath(KnownFolders.FOLDERID_Documents);
connection = new Dispatch("ADODB.Connection"); Dispatch.call(connection, "Open", "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';");
public void callback(int dwArgc, Pointer lpszArgv) { serviceControl = new ServiceControl(); serviceStatusHandle = ADVAPI_32.RegisterServiceCtrlHandlerEx(serviceName, serviceControl, null); reportStatus(Winsvc.SERVICE_START_PENDING, WinError.NO_ERROR, 3000); reportStatus(Winsvc.SERVICE_RUNNING, WinError.NO_ERROR, 0); Thread.currentThread().setContextClassLoader(WindowsService.class.getClassLoader()); run(); try { synchronized (waitObject) { waitObject.wait(); } } catch (InterruptedException ex) { } reportStatus(Winsvc.SERVICE_STOPPED, WinError.NO_ERROR, 0); // Avoid returning from ServiceMain, which will cause a crash // See http://support.microsoft.com/kb/201349, which recommends // having init() wait for this thread. // Waiting on this thread in init() won't fix the crash, though. System.exit(0); }
/** * Constructor that allows injection of JNA interfaces * * @param wEvtApi event api interface * @param kernel32 kernel interface */ public ConsumeWindowsEventLog(WEvtApi wEvtApi, Kernel32 kernel32) { this.wEvtApi = wEvtApi == null ? loadWEvtApi() : wEvtApi; this.kernel32 = kernel32 == null ? loadKernel32() : kernel32; this.errorLookup = new ErrorLookup(this.kernel32); if (this.kernel32 != null) { name = Kernel32Util.getComputerName(); } else { // Won't be able to use the processor anyway because native libraries didn't load name = null; } }
private static int windowsPing(World world) throws UnknownHostException { IPHlpAPI ipHlpAPI = IPHlpAPI.INSTANCE; Pointer ptr = ipHlpAPI.IcmpCreateFile(); InetAddress inetAddress = InetAddress.getByName(world.getAddress()); byte[] address = inetAddress.getAddress(); String dataStr = RUNELITE_PING; int dataLength = dataStr.length() + 1; Pointer data = new Memory(dataLength); data.setString(0L, dataStr); IcmpEchoReply icmpEchoReply = new IcmpEchoReply(new Memory(IcmpEchoReply.SIZE + dataLength)); assert icmpEchoReply.size() == IcmpEchoReply.SIZE; int packed = (address[0] & 0xff) | ((address[1] & 0xff) << 8) | ((address[2] & 0xff) << 16) | ((address[3] & 0xff) << 24); int ret = ipHlpAPI.IcmpSendEcho(ptr, packed, data, (short) (dataLength), Pointer.NULL, icmpEchoReply, IcmpEchoReply.SIZE + dataLength, TIMEOUT); if (ret != 1) { ipHlpAPI.IcmpCloseHandle(ptr); return -1; } int rtt = Math.toIntExact(icmpEchoReply.roundTripTime.longValue()); ipHlpAPI.IcmpCloseHandle(ptr); return rtt; }