public Integer invoke(File f, VirtualChannel channel) throws IOException { int mode = -1; try { mode = NativeUtils.getInstance().mode(f); } catch (NativeAccessException ex) { LOGGER.log(Level.WARNING, "Native function mod failed ({0})", NativeUtils.getInstance().getLastUnixError()); } return mode; } });
/** * Gets the {@link ProcessTree} of the current system * that JVM runs in, or in the worst case return the default one * that's not capable of killing descendants at all. * * @return ProcessTree of the current system. */ public static ProcessTree get() { return get(NativeUtils.getInstance()); }
public FormValidation doTest() { try { String message = NativeUtils.getInstance().checkPamAuthentication(); if (message.startsWith("Error:")) { return FormValidation.error(message.replaceFirst("Error:", "")); } else { return FormValidation.ok(message); } } catch (NativeAccessException exc) { return FormValidation.error("Native Support for PAM Authentication not available."); } } }
public boolean isRoot() { try { return NativeUtils.getInstance().getEuid() == 0; } catch (NativeAccessException exc) { LOGGER.log(Level.INFO, "Native Support to find EUID failed - {0}", exc.getLocalizedMessage()); return false; } }
/** * Resolves symlink, if the given file is a symlink. Otherwise return null. * <p> * If the resolution fails, report an error. * * @param listener * If we rely on an external command to resolve symlink, this is it. * (TODO: try readlink(1) available on some platforms) */ public static String resolveSymlink(File link, TaskListener listener) { if (Functions.isWindows()) { return null; } try { return NativeUtils.getInstance().resolveSymlink(link); } catch (NativeAccessException exc) { listener.getLogger().print("Native function resolveSymlink failed " + NativeUtils.getInstance().getLastUnixError()); } return null; }
@Override public GroupDetails loadGroupByGroupname(final String groupname) throws UsernameNotFoundException, DataAccessException { try { if (!NativeUtils.getInstance().checkUnixGroup(groupname)) { throw new UsernameNotFoundException("No such Unix group: " + groupname); } } catch (NativeAccessException exc) { throw new DataAccessException("Failed to find Unix Group", exc) { }; } return new GroupDetails() { @Override public String getName() { return groupname; } }; }
@Override public void restart() throws IOException, InterruptedException { Hudson h = Hudson.getInstance(); if (h != null) { h.cleanUp(); } try { NativeUtils.getInstance().restartJavaProcess(null, false); } catch (NativeAccessException exc) { //TODO: Rethrow as IOException to avoid adding NativeExecutionException in throws clause throw new IOException(exc); } }
final NativeUtils nativeUtils = NativeUtils.getInstance();
/** * Run chmod natively if we can, otherwise fall back to Ant. */ public static void chmod(File f, int mask, boolean tryNative) { if (Functions.isWindows()) { return; // noop } if (tryNative) { try { NativeUtils.getInstance().chmod(f, mask); } catch (NativeAccessException exc) { LOGGER.log(Level.WARNING, "Native function chmod failed ({0}). Using Ant''s chmod task instead.", NativeUtils.getInstance().getLastUnixError()); _chmodAnt(f, mask); } } else { _chmodAnt(f, mask); } }
private static String computeHudsonFileSystemName(NativeZfsFileSystem top) { try { NativeUtils nativeUtils = NativeUtils.getInstance(); if(!nativeUtils.zfsExists(top.getName()+"/hudson")) return top.getName()+"/hudson"; for( int i = 2; ; i++ ) { String name = top.getName() + "/hudson" + i; if(!nativeUtils.zfsExists(name)) return name; } } catch (NativeAccessException ex) { Logger.getLogger(ZFSInstaller.class.getName()).log(Level.SEVERE, null, ex); } return null; }
/** * If <tt>hudson.exe</tt> is old compared to our copy, * schedule an overwrite (except that since it's currently running, * we can only do it when Hudson restarts next time.) */ private void updateHudsonExeIfNeeded() { try { File rootDir = Hudson.getInstance().getRootDir(); URL exe = getClass().getResource("/windows-service/hudson.exe"); String ourCopy = Util.getDigestOf(exe.openStream()); File currentCopy = new File(rootDir,"hudson.exe"); if(!currentCopy.exists()) return; String curCopy = new FilePath(currentCopy).digest(); if(ourCopy.equals(curCopy)) return; // identical File stage = new File(rootDir,"hudson.exe.new"); FileUtils.copyURLToFile(exe, stage); NativeUtils.getInstance().windowsMoveFile(stage, currentCopy); LOGGER.info("Scheduled a replacement of hudson.exe"); } catch (NativeAccessException exc) { LOGGER.log(Level.SEVERE, "Failed to replace hudson.exe", exc); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Failed to replace hudson.exe",e); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "Failed to replace hudson.exe",e); } }
@Override public void kill(final Map<String,String> modelEnvVars) throws IOException, InterruptedException { getChannel().call(new KillTask(modelEnvVars, NativeUtils.getInstance())); }
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { try { if (!NativeUtils.getInstance().checkUnixUser(username)) { throw new UsernameNotFoundException("No such Unix user: " + username); } } catch (NativeAccessException exc) { throw new DataAccessException("Failed to find Unix User", exc) { }; } // return some dummy instance return new User(username, "", true, true, true, true, new GrantedAuthority[]{AUTHENTICATED_AUTHORITY}); } };
/** * Invokes slave.exe with a SCM management command. * * <p> * If it fails in a way that indicates the presence of UAC, retry in an UAC compatible manner. */ static int runElevated(File slaveExe, String command, TaskListener out, File pwd) throws IOException, InterruptedException { try { return new LocalLauncher(out).launch().cmds(slaveExe, command).stdout(out).pwd(pwd).join(); } catch (IOException e) { if (e.getMessage().contains("CreateProcess") && e.getMessage().contains("=740")) { // fall through } else { throw e; } } String logFile = "redirect.log"; try { return NativeUtils.getInstance().windowsExec(slaveExe, command, logFile, pwd); } catch (NativeAccessException ex) { Logger.getLogger(WindowsSlaveInstaller.class.getName()).log(Level.SEVERE, null, ex); return -1; } finally { FileInputStream fin = new FileInputStream(new File(pwd, "redirect.log")); IOUtils.copy(fin, out.getLogger()); fin.close(); } }
success = NativeUtils.getInstance().createSymlink(targetPath, baseDir); } catch (NativeAccessException ex) { errmsg = "Native function mod failed" + NativeUtils.getInstance().getLastUnixError();
protected NativeSystemMemory monitor(Computer c) throws IOException, InterruptedException { return c.getChannel().call(new MonitorTask(NativeUtils.getInstance())); }
public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getPrincipal().toString(); String password = authentication.getCredentials().toString(); try { Set<String> grps = NativeUtils.getInstance().pamAuthenticate(serviceName, username, password); GrantedAuthority[] groups = new GrantedAuthority[grps.size()]; int i = 0; for (String g : grps) { groups[i++] = new GrantedAuthorityImpl(g); } EnvVars.setHudsonUserEnvVar(username); // I never understood why Spring Security insists on keeping the password... return new UsernamePasswordAuthenticationToken(username, password, groups); } catch (NativeAccessException exc) { throw new BadCredentialsException(exc.getMessage(), exc); } }
/** * Makes the given file writable by any means possible. */ private static void makeWritable(File f) { // try chmod. this becomes no-op if this is not Unix. try { Chmod chmod = new Chmod(); chmod.setProject(new Project()); chmod.setFile(f); chmod.setPerm("u+w"); chmod.execute(); } catch (BuildException e) { LOGGER.log(Level.INFO, "Failed to chmod " + f, e); } // also try JDK6-way of doing it. try { f.setWritable(true); } catch (NoSuchMethodError e) { // not JDK6 } if (!Functions.isWindows()) { try { NativeUtils.getInstance().makeFileWritable(f); } catch (NativeAccessException exc) { LOGGER.log(Level.FINE, "Failed to chmod(2) " + f, exc); } } }
@Override public void verifyRestartable() throws RestartNotSupportedException { // see http://lists.apple.com/archives/cocoa-dev/2005/Oct/msg00836.html and // http://factor-language.blogspot.com/2007/07/execve-returning-enotsup-on-mac-os-x.html // on Mac, execv fails with ENOTSUP if the caller is multi-threaded, resulting in an error like // the one described in http://www.nabble.com/Restarting-hudson-not-working-on-MacOS--to24641779.html if (Hudson.isDarwin()) { throw new RestartNotSupportedException("Restart is not supported on Mac OS X"); } else { try { if (!NativeUtils.getInstance().canRestartJavaProcess()) { throw new RestartNotSupportedException("Restart is not supported on this Platform"); } } catch (NativeAccessException exc) { throw new RestartNotSupportedException("Restart is not supported on this Platform"); } } } }
VirtualChannel start(TaskListener listener, String rootPassword) throws IOException, InterruptedException { final int uid; try { uid = NativeUtils.getInstance().getEuid(); } catch (NativeAccessException exc) { // TODO: Added to avoid adding NativeExecutionException to throws clause throw new IOException(exc); } if(uid==0) // already running as root return newLocalChannel(); String javaExe = System.getProperty("java.home") + "/bin/java"; File slaveJar = Which.jarFile(Launcher.class); ArgumentListBuilder args = new ArgumentListBuilder().add(javaExe); if(slaveJar.isFile()) args.add("-jar").add(slaveJar); else // in production code this never happens, but during debugging this is convenientud args.add("-cp").add(slaveJar).add(hudson.remoting.Launcher.class.getName()); if(rootPassword==null) { // try sudo, in the hope that the user has the permission to do so without password return new LocalLauncher(listener).launchChannel( args.prepend(sudoExe()).toCommandArray(), listener.getLogger(), null, Collections.<String, String>emptyMap()); } else { // try sudo with the given password. Also run in pfexec so that we can elevate the privileges Process proc = sudoWithPass(args); return Channels.forProcess(args.toStringWithQuote(), Computer.threadPoolForRemoting, proc, listener.getLogger() ); } } }