Mercurial Hosting > luan
view src/luan/modules/IoLuan.java @ 1311:ca742d51b31f
don't delete into symbolic links
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Thu, 24 Jan 2019 21:15:03 -0700 |
parents | 781ec0a92bb5 |
children | 15af473045c4 |
line wrap: on
line source
package luan.modules; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; import java.io.StringReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.ByteArrayInputStream; import java.io.StringWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.net.URL; import java.net.InetAddress; import java.net.Inet4Address; import java.net.NetworkInterface; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.nio.file.Files; import java.util.Enumeration; import java.util.Map; import luan.LuanState; import luan.LuanTable; import luan.LuanFunction; import luan.LuanException; import luan.modules.url.LuanUrl; public final class IoLuan { public static String read_console_line(String prompt) throws IOException { if( prompt==null ) prompt = "> "; return System.console().readLine(prompt); } public interface LuanWriter { public Object out(); public void write(LuanState luan,Object... args) throws LuanException, IOException; public void close() throws IOException; } public static LuanWriter luanWriter(final PrintStream out) { return new LuanWriter() { public Object out() { return out; } public void write(LuanState luan,Object... args) throws LuanException { for( Object obj : args ) { out.print( luan.toString(obj) ); } } public void close() { out.close(); } }; } public static LuanWriter luanWriter(final Writer out) { return new LuanWriter() { public Object out() { return out; } public void write(LuanState luan,Object... args) throws LuanException, IOException { for( Object obj : args ) { out.write( luan.toString(obj) ); } } public void close() throws IOException { out.close(); } }; } static LuanFunction lines(final BufferedReader in) { return new LuanFunction() { @Override public Object call(LuanState luan,Object[] args) throws LuanException { try { if( args.length > 0 ) { if( args.length > 1 || !"close".equals(args[0]) ) throw new LuanException( "the only argument allowed is 'close'" ); in.close(); return null; } String rtn = in.readLine(); if( rtn==null ) in.close(); return rtn; } catch(IOException e) { throw new LuanException(e); } } }; } static LuanFunction blocks(final InputStream in,final int blockSize) { return new LuanFunction() { final byte[] a = new byte[blockSize]; @Override public Object call(LuanState luan,Object[] args) throws LuanException { try { if( args.length > 0 ) { if( args.length > 1 || !"close".equals(args[0]) ) throw new LuanException( "the only argument allowed is 'close'" ); in.close(); return null; } if( in.read(a) == -1 ) { in.close(); return null; } return a; } catch(IOException e) { throw new LuanException(e); } } }; } private static File objToFile(Object obj) { if( obj instanceof String ) { return new File((String)obj); } if( obj instanceof LuanTable ) { LuanTable t = (LuanTable)obj; Object java = t.rawGet("java"); if( java instanceof LuanFile ) { LuanFile luanFile = (LuanFile)java; return luanFile.file; } } return null; } public static abstract class LuanIn { protected String charset = null; public abstract InputStream inputStream(LuanState luan) throws IOException, LuanException; public abstract String to_string(); public abstract String to_uri_string(); public Reader reader(LuanState luan) throws IOException, LuanException { InputStream in = inputStream(luan); return charset==null ? new InputStreamReader(in) : new InputStreamReader(in,charset); } public String read_text(LuanState luan) throws IOException, LuanException { Reader in = reader(luan); String s = Utils.readAll(in); in.close(); return s; } public byte[] read_binary(LuanState luan) throws IOException, LuanException { InputStream in = inputStream(luan); byte[] a = Utils.readAll(in); in.close(); return a; } public LuanFunction read_lines(LuanState luan) throws IOException, LuanException { return lines(new BufferedReader(reader(luan))); } public LuanFunction read_blocks(LuanState luan,Integer blockSize) throws IOException, LuanException { int n = blockSize!=null ? blockSize : Utils.bufSize; return blocks(inputStream(luan),n); } public boolean exists(LuanState luan) throws IOException, LuanException { try { inputStream(luan).close(); return true; } catch(FileNotFoundException e) { return false; } catch(UnknownHostException e) { return false; } } public long checksum(LuanState luan) throws IOException, LuanException { long cs = 0; InputStream in = new BufferedInputStream(inputStream(luan)); int c; while( (c=in.read()) != -1 ) { cs = 31 * cs + c; } in.close(); return cs; } public String charset() { return charset; } public void set_charset(String charset) { this.charset = charset; } } public static final LuanIn defaultStdin = new LuanIn() { @Override public InputStream inputStream(LuanState luan) { return System.in; } @Override public String to_string() { return "<stdin>"; } @Override public String to_uri_string() { return "stdin:"; } @Override public String read_text(LuanState luan) throws IOException { return Utils.readAll(new InputStreamReader(System.in)); } @Override public byte[] read_binary(LuanState luan) throws IOException { return Utils.readAll(System.in); } @Override public boolean exists(LuanState luan) { return true; } }; public static abstract class LuanIO extends LuanIn { abstract OutputStream outputStream() throws IOException; private Writer writer() throws IOException { OutputStream out = outputStream(); return charset==null ? new OutputStreamWriter(out) : new OutputStreamWriter(out,charset); } public void write(LuanState luan,Object obj) throws LuanException, IOException { if( obj instanceof String ) { String s = (String)obj; Writer out = writer(); out.write(s); out.close(); return; } if( obj instanceof byte[] ) { byte[] a = (byte[])obj; OutputStream out = outputStream(); Utils.copyAll(new ByteArrayInputStream(a),out); out.close(); return; } if( obj instanceof LuanTable ) { LuanTable t = (LuanTable)obj; Object java = t.rawGet("java"); if( java instanceof LuanIn ) { LuanIn luanIn = (LuanIn)java; InputStream in = luanIn.inputStream(luan); OutputStream out = outputStream(); Utils.copyAll(in,out); out.close(); in.close(); return; } } throw new LuanException( "bad argument #1 to 'write' (string or binary or Io.uri expected)" ); } public LuanWriter text_writer() throws IOException { return luanWriter(new BufferedWriter(writer())); } public OutputStream binary_writer() throws IOException { return new BufferedOutputStream(outputStream()); } public void write_text(LuanState luan,Object... args) throws LuanException, IOException { LuanWriter luanWriter = luanWriter(new BufferedWriter(writer())); luanWriter.write(luan,args); luanWriter.close(); } } public static final LuanIO nullIO = new LuanIO() { private final InputStream in = new InputStream() { @Override public int read() { return -1; } }; private final OutputStream out = new OutputStream() { @Override public void write(int b) {} }; @Override public InputStream inputStream(LuanState luan) { return in; } @Override OutputStream outputStream() { return out; } @Override public String to_string() { return "<null>"; } @Override public String to_uri_string() { return "null:"; } }; public static final class LuanString extends LuanIO { private String s; public LuanString(String s) throws LuanException { Utils.checkNotNull(s); this.s = s; } @Override public InputStream inputStream(LuanState luan) { throw new UnsupportedOperationException(); } @Override OutputStream outputStream() { throw new UnsupportedOperationException(); } @Override public String to_string() { return "<string>"; } @Override public String to_uri_string() { return "string:" + s; } @Override public Reader reader(LuanState luan) { return new StringReader(s); } @Override public String read_text(LuanState luan) { return s; } @Override public boolean exists(LuanState luan) { return true; } @Override public LuanWriter text_writer() { return new LuanWriter() { private final Writer out = new StringWriter(); public Object out() { return out; } public void write(LuanState luan,Object... args) throws LuanException, IOException { for( Object obj : args ) { out.write( luan.toString(obj) ); } } public void close() throws IOException { s = out.toString(); } }; } } public static final class LuanFile extends LuanIO { public final File file; public LuanFile(LuanState luan,String path) throws LuanException { this(luan,new File(path)); } private LuanFile(LuanState luan,File file) throws LuanException { this(file); check(luan,"file:"+file.toString()); } private LuanFile(File file) { this.file = file; } @Override public InputStream inputStream(LuanState luan) throws IOException { return new FileInputStream(file); } @Override OutputStream outputStream() throws IOException { return new FileOutputStream(file); } @Override public String to_string() { return file.toString(); } @Override public String to_uri_string() { return "file:" + file.toString(); } public LuanFile child(LuanState luan,String name) throws LuanException { return new LuanFile(luan,new File(file,name)); } public LuanTable children(LuanState luan) throws LuanException { File[] files = file.listFiles(); if( files==null ) return null; LuanTable list = new LuanTable(luan); for( File f : files ) { list.rawPut(list.rawLength()+1,new LuanFile(luan,f)); } return list; } public LuanFile parent(LuanState luan) throws LuanException, IOException { File parent = file.getParentFile(); if( parent==null ) parent = file.getCanonicalFile().getParentFile(); return new LuanFile(luan,parent); } @Override public boolean exists(LuanState luan) { return file.exists(); } public void rename_to(Object destObj) throws LuanException { File dest = objToFile(destObj); if( dest==null ) throw new LuanException( "bad argument #1 to 'objToFile' (string or file table expected)" ); if( !file.renameTo(dest) ) throw new LuanException("couldn't rename file "+file+" to "+dest); } public LuanFile canonical(LuanState luan) throws LuanException, IOException { return new LuanFile(luan,file.getCanonicalFile()); } public LuanFile create_temp_file(LuanState luan,String prefix,String suffix) throws LuanException, IOException { File tmp = File.createTempFile(prefix,suffix,file); return new LuanFile(luan,tmp); } public void delete() throws LuanException { if( file.exists() ) delete(file); } private static void delete(File file) throws LuanException { if( !isSymbolicLink(file) ) { File[] children = file.listFiles(); if( children != null ) { for( File child : children ) { delete(child); } } } if( !file.delete() ) throw new LuanException("couldn't delete file "+file); } public void mkdir() throws LuanException { if( !file.isDirectory() ) { if( !file.mkdirs() ) throw new LuanException("couldn't make directory "+file); } } public void set_last_modified(long time) throws LuanException { if( !file.setLastModified(time) ) throw new LuanException("couldn't set_last_modified on "+file); } private static boolean isSymbolicLink(File file) { return Files.isSymbolicLink(file.toPath()); } public boolean is_symbolic_link() { return isSymbolicLink(file); } } public static LuanUrl classpath(LuanState luan,String name) throws LuanException { if( name.contains("//") ) return null; String path = name; check(luan,"classpath:"+path); URL url; if( !path.contains("#") ) { url = ClassLoader.getSystemResource(path); } else { String[] a = path.split("#"); url = ClassLoader.getSystemResource(a[0]); if( url==null ) { for( int i=1; i<a.length; i++ ) { url = ClassLoader.getSystemResource(a[0]+"/"+a[i]); if( url != null ) { try { url = new URL(url,"."); } catch(MalformedURLException e) { throw new RuntimeException(e); } break; } } } } if( url != null ) return new LuanUrl(url,null); return null; } public static class BaseOs extends LuanIO { private final String cmd; final File dir; Process proc; private BaseOs(String cmd,LuanTable options) throws IOException, LuanException { this.cmd = cmd; File dir = null; if( options != null ) { Map map = options.asMap(); Object obj = map.remove("dir"); dir = objToFile(obj); if( dir==null ) throw new LuanException( "bad option 'dir' (string or file table expected)" ); if( !map.isEmpty() ) throw new LuanException( "unrecognized options: "+map ); } this.dir = dir; } @Override public InputStream inputStream(LuanState luan) throws IOException { return proc.getInputStream(); } @Override OutputStream outputStream() throws IOException { return proc.getOutputStream(); } @Override public String to_string() { return proc.toString(); } @Override public String to_uri_string() { throw new UnsupportedOperationException(); } @Override public boolean exists(LuanState luan) { return true; } public void wait_for() throws IOException, LuanException { try { proc.waitFor(); } catch(InterruptedException e) { throw new RuntimeException(e); } int exitVal = proc.exitValue(); if( exitVal != 0 ) { Reader err = new InputStreamReader(proc.getErrorStream()); String error = "exit value "+exitVal+" in: "+cmd+"\n"+Utils.readAll(err); err.close(); throw new LuanException(error); } } @Override public String read_text(LuanState luan) throws IOException, LuanException { String s = super.read_text(luan); wait_for(); return s; } } public static final class LuanOs extends BaseOs { public LuanOs(LuanState luan,String cmd,LuanTable options) throws IOException, LuanException { super(cmd,options); check(luan,"os:"+cmd); this.proc = Runtime.getRuntime().exec(cmd,null,dir); } } public static final class LuanBash extends BaseOs { public LuanBash(LuanState luan,String cmd,LuanTable options) throws IOException, LuanException { super(cmd,options); check(luan,"bash:"+cmd); this.proc = Runtime.getRuntime().exec(new String[]{"bash","-c",cmd},null,dir); } } public static class LuanInput extends LuanIn { private final InputStream in; public LuanInput(InputStream in) { this.in = in; } @Override public InputStream inputStream(LuanState luan) { return in; } @Override public String to_string() { return "<input_stream>"; } @Override public String to_uri_string() { throw new UnsupportedOperationException(); } @Override public boolean exists(LuanState luan) { return true; } }; public static String ip(String domain) { try { return InetAddress.getByName(domain).getHostAddress(); } catch(UnknownHostException e) { return null; } } public static LuanTable my_ips(LuanState luan) throws IOException { LuanTable tbl = new LuanTable(luan); for( Enumeration<NetworkInterface> e1 = NetworkInterface.getNetworkInterfaces(); e1.hasMoreElements(); ) { NetworkInterface ni = e1.nextElement(); for( Enumeration<InetAddress> e2 = ni.getInetAddresses(); e2.hasMoreElements(); ) { InetAddress ia = e2.nextElement(); if( ia instanceof Inet4Address ) tbl.rawPut(ia.getHostAddress(),true); } } return tbl; } // security public static void unrestricted(LuanState luan) throws LuanException { JavaLuan.check(luan); luan.javaOk.unrestrictedIo = true; } public interface Security { public void check(LuanState luan,String name) throws LuanException; } private static String SECURITY_KEY = "Io.Security"; private static void check(LuanState luan,String name) throws LuanException { if( luan.javaOk.unrestrictedIo ) return; Security s = (Security)luan.registry().get(SECURITY_KEY); if( s!=null ) s.check(luan,name); } public static void setSecurity(LuanState luan,Security s) { luan.registry().put(SECURITY_KEY,s); } private void IoLuan() {} // never }