package ru.rudb.java; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.LocalDate; public final class Daemon { private static final int HEALTH = 1; private static final int HEALTH_OK = 2; private static final int PROP = 3; private static final int PROP_OK = 4; private static final int CALL = 5; private static final int RESULT = 6; private static final int ERROR = 7; private static final int LOAD_CLASS = 8; private static final int CLASS_BYTES = 9; private static final int OUTPUT = 10; private static final int COMPILE = 11; private static final int COMPILE_OK = 12; static final int SQL_EXEC = 13; static final int SQL_FETCH = 14; static final int SQL_CLOSE = 15; static final int SQL_ROWS = 16; static final int SQL_DONE = 17; static final int SQL_ERROR = 18; static final int SQL_COMMIT = 19; static final int SQL_ROLLBACK = 20; private static final int ERROUT = 21; private static final int POLICY = 22; private static final int JMX = 23; private static final int BLOB = 24; private static final ThreadLocal jmxTouched = new ThreadLocal(); private static final ThreadLocal grantsHold = new ThreadLocal(); private static final ThreadLocal deadlineHold = new ThreadLocal(); static final class Env { int fd; CatalogLoader loader; File logDir; int peer; int request; Env prev; } static final class SqlReply { int type; byte[] body; } private static final ThreadLocal envHold = new ThreadLocal(); public static void main(String[] args) throws Exception { if (args.length < 1 || args.length > 2) throw new IllegalArgumentException("socket path and optional log directory required"); Class.forName("ru.rudb.java.DefaultDriver"); System.setSecurityManager(new Gate()); int server = Sock.listen(args[0]); if (server < 0) throw new IOException("listen failed"); File logDir; if (args.length == 2) logDir = new File(args[1]); else { logDir = new File(args[0]).getParentFile().getParentFile(); logDir = new File(logDir, "log/dbms_java"); } while (true) { int client = Sock.accept(server); if (client < 0) continue; final int fd = client; final File dir = logDir; Thread session = new Thread(() -> runSession(fd, dir)); session.setDaemon(true); session.start(); } } private static void runSession(int fd, File logDir) { SessionContext ctx = new SessionContext(); CatalogLoader loader = new CatalogLoader(fd, 0); byte[] buf = new byte[65536]; int peer = Sock.peerPid(fd); try { while (serve(fd, buf, ctx, loader, logDir, peer)) { } } catch (IOException ex) { log(logDir, peer, 0, "сеанс оборван"); } finally { if (Boolean.TRUE.equals(jmxTouched.get())) stopJmx(); jmxTouched.remove(); Sock.close(fd); } } private static String jmxField(String[] lines, int idx) { if (idx >= lines.length || lines[idx].length() == 0) return null; return lines[idx]; } private static String startJmx(String payload) { String[] lines = payload.split("\n", -1); String port = jmxField(lines, 0); String ssl = jmxField(lines, 1); String auth = jmxField(lines, 2); try { if (port != null) System.setProperty("com.sun.management.jmxremote.port", port); if (ssl != null) System.setProperty("com.sun.management.jmxremote.ssl", ssl); if (auth != null) System.setProperty("com.sun.management.jmxremote.authenticate", auth); Class agent = Class.forName("jdk.internal.agent.Agent"); java.lang.reflect.Field props = agent.getDeclaredField("mgmtProps"); props.setAccessible(true); props.set(null, null); agent.getMethod("startAgent").invoke(null); return null; } catch (Throwable ex) { Throwable cause = ex; while (cause instanceof java.lang.reflect.InvocationTargetException && cause.getCause() != null) cause = cause.getCause(); String detail = cause.getMessage() != null ? cause.getMessage() : cause.toString(); return "java.lang.RuntimeException: java.lang.RuntimeException: Management agent class failed : " + detail; } } private static void stopJmx() { try { Class agent = Class.forName("jdk.internal.agent.Agent"); java.lang.reflect.Method stop = agent.getDeclaredMethod("stopRemoteManagementAgent"); stop.setAccessible(true); stop.invoke(null); } catch (Throwable ignored) { } try { Class agent = Class.forName("jdk.internal.agent.Agent"); java.lang.reflect.Field props = agent.getDeclaredField("mgmtProps"); props.setAccessible(true); props.set(null, null); } catch (Throwable ignored) { } System.clearProperty("com.sun.management.jmxremote.port"); System.clearProperty("com.sun.management.jmxremote.ssl"); System.clearProperty("com.sun.management.jmxremote.authenticate"); } private static boolean handleBlob(int fd, CatalogLoader loader, byte[] raw, int len, int request, File logDir, int peer) throws IOException { int marks = 0; int cut = 0; for (; cut < len && marks < 3; cut++) { if (raw[cut] == '\n') marks++; } String head = new String(raw, 0, cut, StandardCharsets.UTF_8); String[] parts = head.split("\n", -1); if (parts.length < 3) { writeFrame(fd, ERROR, request, "IllegalArgumentException: дескриптор".getBytes(StandardCharsets.UTF_8)); return true; } byte[] arg = java.util.Arrays.copyOfRange(raw, cut, len); try { loader.request = request; Class cls = loader.loadClass(parts[0].replace('/', '.')); java.lang.reflect.Method found = cls.getMethod(parts[1], byte[].class); found.setAccessible(true); Object value = found.invoke(null, new Object[] { arg }); byte[] reply = value == null ? new byte[0] : String.valueOf(value).getBytes(StandardCharsets.UTF_8); writeFrame(fd, RESULT, request, reply); } catch (Throwable ex) { Throwable cause = ex; if (ex instanceof java.lang.reflect.InvocationTargetException && ex.getCause() != null) cause = ex.getCause(); String text = cause.getClass().getName() + ": " + String.valueOf(cause.getMessage()); writeFrame(fd, ERROR, request, text.getBytes(StandardCharsets.UTF_8)); } log(logDir, peer, request, parts[0] + "." + parts[1]); return true; } private static boolean serve(int fd, byte[] buf, SessionContext ctx, CatalogLoader loader, File logDir, int peer) throws IOException { byte[] hdr = new byte[16]; if (!readFully(fd, hdr, 16)) return false; int type = u16(hdr, 6); int request = u32(hdr, 8); int len = u32(hdr, 12); if (len < 0 || len > 256 * 1024 * 1024) return false; byte[] raw = buf; if (len > buf.length) raw = new byte[len]; if (len > 0 && !readFully(fd, raw, len)) return false; if (type == BLOB) return handleBlob(fd, loader, raw, len, request, logDir, peer); String payload = new String(raw, 0, len, java.nio.charset.StandardCharsets.UTF_8); String answer; int reply; if (type == HEALTH) { reply = HEALTH_OK; answer = System.getProperty("java.version", ""); } else if (type == PROP) { reply = PROP_OK; answer = System.getProperty(payload, ""); } else if (type == CALL) return handleCall(fd, loader, payload, request, logDir, peer); else if (type == COMPILE) return handleCompile(fd, payload, request, logDir, peer); else if (type == POLICY) { applyPolicy(payload); return true; } else if (type == JMX) { String err = startJmx(payload); jmxTouched.set(Boolean.TRUE); if (err == null) writeFrame(fd, RESULT, request, "ok".getBytes(StandardCharsets.UTF_8)); else writeFrame(fd, ERROR, request, err.getBytes(StandardCharsets.UTF_8)); return true; } else return true; if (type != HEALTH) log(logDir, peer, request, payload); byte[] body = answer.getBytes(StandardCharsets.UTF_8); byte[] frame = new byte[16 + body.length]; frame[0] = 'R'; frame[1] = 'J'; frame[2] = 'V'; frame[3] = 'A'; put16(frame, 4, 1); put16(frame, 6, reply); put32(frame, 8, request); put32(frame, 12, body.length); System.arraycopy(body, 0, frame, 16, body.length); writeFully(fd, frame); return true; } private static byte[] hexToBytes(String hex) { int n = hex.length() / 2; byte[] out = new byte[n]; for (int i = 0; i < n; i++) out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); return out; } private static String bytesToHex(byte[] raw) { char[] digits = "0123456789ABCDEF".toCharArray(); char[] out = new char[raw.length * 2]; for (int i = 0; i < raw.length; i++) { int v = raw[i] & 0xff; out[i * 2] = digits[v >>> 4]; out[i * 2 + 1] = digits[v & 0x0f]; } return new String(out); } private static boolean handleCall(int fd, CatalogLoader loader, String payload, int request, File logDir, int peer) throws IOException { Env env = new Env(); env.fd = fd; env.loader = loader; env.logDir = logDir; env.peer = peer; env.request = request; env.prev = envHold.get(); envHold.set(env); try { return handleCallBody(fd, loader, payload, request, logDir, peer); } finally { if (env.prev == null) envHold.remove(); else envHold.set(env.prev); } } static SqlReply exchangeSql(int type, byte[] body) throws IOException { Env env = envHold.get(); if (env == null) throw new IOException("нет сеанса"); writeFrame(env.fd, type, env.request, body); while (true) { byte[] hdr = new byte[16]; if (!readFully(env.fd, hdr, 16)) throw new IOException("обрыв"); int got = u16(hdr, 6); int req = u32(hdr, 8); int len = u32(hdr, 12); if (len < 0 || len > 8 * 1024 * 1024) throw new IOException("кадр"); byte[] payload = new byte[len]; if (len > 0 && !readFully(env.fd, payload, len)) throw new IOException("обрыв"); if (got == SQL_ROWS || got == SQL_DONE || got == SQL_ERROR) { SqlReply reply = new SqlReply(); reply.type = got; reply.body = payload; return reply; } if (got == CALL) { handleCall(env.fd, env.loader, new String(payload, StandardCharsets.UTF_8), req, env.logDir, env.peer); continue; } throw new IOException("кадр " + got); } } private static boolean handleCallBody(int fd, CatalogLoader loader, String payload, int request, File logDir, int peer) throws IOException { String[] parts = payload.split("\n", -1); if (parts.length < 3) { writeFrame(fd, ERROR, request, "IllegalArgumentException: дескриптор".getBytes(StandardCharsets.UTF_8)); return true; } String className = parts[0]; String method = parts[1]; String ret = parts[2]; boolean capture = parts.length > 3 && ("1".equals(parts[3]) || "2".equals(parts[3])); boolean captureErr = parts.length > 3 && "2".equals(parts[3]); log(logDir, peer, request, className + "." + method); try { loader.request = request; Class cls = loader.loadClass(className.replace('/', '.')); int nargs = parts.length > 4 && parts[4].length() > 0 ? Integer.parseInt(parts[4]) : 0; Class[] sig = new Class[nargs]; Object[] vals = new Object[nargs]; for (int i = 0; i < nargs; i++) { String argType = parts[5 + i * 2]; String argVal = parts[6 + i * 2]; if ("int".equals(argType)) { sig[i] = int.class; vals[i] = Integer.valueOf(argVal); } else if ("long".equals(argType)) { sig[i] = long.class; vals[i] = Long.valueOf(argVal); } else if ("double".equals(argType)) { sig[i] = double.class; vals[i] = Double.valueOf(argVal); } else if ("short".equals(argType)) { sig[i] = short.class; vals[i] = Short.valueOf(argVal); } else if ("byte".equals(argType)) { sig[i] = byte.class; vals[i] = Byte.valueOf(argVal); } else if ("float".equals(argType)) { sig[i] = float.class; vals[i] = Float.valueOf(argVal); } else if ("decimal".equals(argType)) { sig[i] = java.math.BigDecimal.class; vals[i] = new java.math.BigDecimal(argVal); } else if ("nulldecimal".equals(argType)) { sig[i] = java.math.BigDecimal.class; vals[i] = null; } else if ("bytes".equals(argType)) { sig[i] = byte[].class; vals[i] = hexToBytes(argVal); } else if ("nullbytes".equals(argType)) { sig[i] = byte[].class; vals[i] = null; } else if ("date".equals(argType)) { sig[i] = java.sql.Date.class; vals[i] = java.sql.Date.valueOf(argVal.substring(0, 10)); } else if ("nulldate".equals(argType)) { sig[i] = java.sql.Date.class; vals[i] = null; } else if ("timestamp".equals(argType)) { sig[i] = java.sql.Timestamp.class; vals[i] = java.sql.Timestamp.valueOf(argVal); } else if ("nullts".equals(argType)) { sig[i] = java.sql.Timestamp.class; vals[i] = null; } else if ("boolean".equals(argType)) { sig[i] = boolean.class; vals[i] = Boolean.valueOf("true".equals(argVal)); } else if ("null".equals(argType)) { sig[i] = String.class; vals[i] = null; } else { sig[i] = String.class; vals[i] = argVal; } } java.lang.reflect.Method found; Object[] invokeVals = vals; if ("main".equals(method) && nargs == 0) { found = cls.getMethod("main", String[].class); invokeVals = new Object[] { new String[0] }; } else found = cls.getMethod(method, sig); found.setAccessible(true); java.io.ByteArrayOutputStream captured = new java.io.ByteArrayOutputStream(); java.io.ByteArrayOutputStream capturedErr = new java.io.ByteArrayOutputStream(); java.io.PrintStream previous = System.out; java.io.PrintStream previousErr = System.err; if (capture) System.setOut(new java.io.PrintStream(captured, true, "UTF-8")); if (captureErr) System.setErr(new java.io.PrintStream(capturedErr, true, "UTF-8")); Object value; java.util.Timer timer = null; final Thread self = Thread.currentThread(); Integer limit = deadlineHold.get(); if (limit != null && limit.intValue() > 0) { timer = new java.util.Timer(true); timer.schedule(new java.util.TimerTask() { @Override public void run() { self.interrupt(); } }, limit.intValue()); } try { value = found.invoke(null, invokeVals); } finally { if (timer != null) timer.cancel(); Thread.interrupted(); if (capture) System.setOut(previous); if (captureErr) System.setErr(previousErr); } if (capture && captured.size() > 0) writeFrame(fd, OUTPUT, request, captured.toByteArray()); if (captureErr && capturedErr.size() > 0) writeFrame(fd, ERROUT, request, capturedErr.toByteArray()); byte[] body; if ("void".equals(ret) || value == null) body = new byte[0]; else if (value instanceof byte[]) body = bytesToHex((byte[]) value).getBytes(StandardCharsets.UTF_8); else if (value instanceof java.sql.Timestamp) body = ((java.sql.Timestamp) value).toString().getBytes(StandardCharsets.UTF_8); else if (value instanceof java.sql.Date) body = ((java.sql.Date) value).toString().getBytes(StandardCharsets.UTF_8); else body = String.valueOf(value).getBytes(StandardCharsets.UTF_8); writeFrame(fd, RESULT, request, body); } catch (Throwable ex) { Throwable cause = ex; if (ex instanceof java.lang.reflect.InvocationTargetException && ex.getCause() != null) cause = ex.getCause(); String text = cause.getClass().getName() + ": " + String.valueOf(cause.getMessage()); writeFrame(fd, ERROR, request, text.getBytes(StandardCharsets.UTF_8)); } return true; } private static final class CatalogLoader extends ClassLoader { private final int fd; private int request; CatalogLoader(int fd, int request) { super(ClassLoader.getSystemClassLoader()); this.fd = fd; this.request = request; } @Override protected Class findClass(String name) throws ClassNotFoundException { byte[] bytes; try { bytes = fetch(name.replace('.', '/')); } catch (IOException ex) { throw new ClassNotFoundException(name, ex); } if (bytes == null || bytes.length == 0) throw new ClassNotFoundException(name); return defineClass(name, bytes, 0, bytes.length); } private byte[] fetch(String internalName) throws IOException { writeFrame(fd, LOAD_CLASS, request, internalName.getBytes(StandardCharsets.UTF_8)); byte[] hdr = new byte[16]; if (!readFully(fd, hdr, 16)) return null; int type = u16(hdr, 6); int len = u32(hdr, 12); if (type != CLASS_BYTES || len < 0 || len > 8 * 1024 * 1024) return null; if (len == 0) return new byte[0]; byte[] body = new byte[len]; if (!readFully(fd, body, len)) return null; return body; } } private static boolean handleCompile(int fd, String payload, int request, File logDir, int peer) throws IOException { int nl = payload.indexOf('\n'); if (nl <= 0) { writeFrame(fd, ERROR, request, "IllegalArgumentException: исходник".getBytes(StandardCharsets.UTF_8)); return true; } String internal = payload.substring(0, nl); String source = payload.substring(nl + 1); String dotted = internal.replace('/', '.'); log(logDir, peer, request, "compile " + dotted); try { java.util.Map classes = MemCompiler.compile(dotted, source); java.io.ByteArrayOutputStream body = new java.io.ByteArrayOutputStream(); body.write((classes.size() + "\n").getBytes(StandardCharsets.UTF_8)); for (java.util.Map.Entry entry : classes.entrySet()) { byte[] raw = entry.getValue(); body.write((entry.getKey() + "\n").getBytes(StandardCharsets.UTF_8)); body.write((raw.length + "\n").getBytes(StandardCharsets.UTF_8)); body.write(raw); } writeFrame(fd, COMPILE_OK, request, body.toByteArray()); } catch (Throwable ex) { String text = ex.getClass().getName() + ": " + String.valueOf(ex.getMessage()); writeFrame(fd, ERROR, request, text.getBytes(StandardCharsets.UTF_8)); } return true; } private static void writeFrame(int fd, int type, int request, byte[] body) throws IOException { byte[] frame = new byte[16 + body.length]; frame[0] = 'R'; frame[1] = 'J'; frame[2] = 'V'; frame[3] = 'A'; put16(frame, 4, 1); put16(frame, 6, type); put32(frame, 8, request); put32(frame, 12, body.length); System.arraycopy(body, 0, frame, 16, body.length); writeFully(fd, frame); } private static void log(File dir, int peer, int request, String detail) { String name = "daemon-" + LocalDate.now() + ".log"; String line1 = "dbms_java: запрос\n"; String line2 = "Output: [Pid: " + peer + ", RequestId: " + request + ", Detail: " + detail + "]\n"; try (FileOutputStream out = new FileOutputStream(new File(dir, name), true)) { out.write(line1.getBytes(StandardCharsets.UTF_8)); out.write(line2.getBytes(StandardCharsets.UTF_8)); } catch (IOException ex) { } } private static boolean readFully(int fd, byte[] buf, int len) throws IOException { int got = 0; while (got < len) { int n = Sock.read(fd, buf, got, len - got); if (n <= 0) return false; got += n; } return true; } private static void writeFully(int fd, byte[] buf) throws IOException { int off = 0; while (off < buf.length) { int n = Sock.write(fd, buf, off, buf.length - off); if (n < 0) throw new IOException("write failed"); if (n == 0) continue; off += n; } } private static int u16(byte[] b, int o) { return ((b[o] & 0xff) << 8) | (b[o + 1] & 0xff); } private static int u32(byte[] b, int o) { return ((b[o] & 0xff) << 24) | ((b[o + 1] & 0xff) << 16) | ((b[o + 2] & 0xff) << 8) | (b[o + 3] & 0xff); } private static void put16(byte[] b, int o, int v) { b[o] = (byte) ((v >> 8) & 0xff); b[o + 1] = (byte) (v & 0xff); } private static void put32(byte[] b, int o, int v) { b[o] = (byte) ((v >> 24) & 0xff); b[o + 1] = (byte) ((v >> 16) & 0xff); b[o + 2] = (byte) ((v >> 8) & 0xff); b[o + 3] = (byte) (v & 0xff); } private static void applyPolicy(String payload) { java.security.Permissions empty = new java.security.Permissions(); grantsHold.set(empty); deadlineHold.set(Integer.valueOf(0)); String[] lines = payload.split("\n", -1); if (lines.length < 2) return; try { int ms = Integer.parseInt(lines[0].trim()); int count = Integer.parseInt(lines[1].trim()); if (ms < 0) ms = 0; deadlineHold.set(Integer.valueOf(ms)); java.security.Permissions grants = new java.security.Permissions(); int idx = 2; for (int i = 0; i < count; i++) { if (idx + 3 >= lines.length) break; String kind = lines[idx++]; String type = lines[idx++]; String name = lines[idx++]; String action = lines[idx++]; if (!"GRANT".equals(kind)) continue; try { if (type.endsWith("java.io.FilePermission")) grants.add(new java.io.FilePermission(name, action.isEmpty() ? "read" : action)); else if (type.endsWith("java.lang.RuntimePermission") && name.length() > 0) grants.add(new java.lang.RuntimePermission(name)); } catch (IllegalArgumentException ex) { } } grants.setReadOnly(); grantsHold.set(grants); } catch (RuntimeException ex) { grantsHold.set(empty); deadlineHold.set(Integer.valueOf(0)); } } private static final class Gate extends SecurityManager { private final ThreadLocal checking = new ThreadLocal(); @Override public void checkPermission(java.security.Permission perm) { if (checking.get() == Boolean.TRUE) return; checking.set(Boolean.TRUE); try { if (!catalogOnStack()) return; if (!(perm instanceof java.io.FilePermission) && !execPerm(perm)) return; java.security.PermissionCollection grants = grantsHold.get(); if (grants != null && grants.implies(perm)) return; throw new java.security.AccessControlException("access denied " + perm); } finally { checking.set(Boolean.FALSE); } } @Override public void checkPermission(java.security.Permission perm, Object context) { checkPermission(perm); } private static boolean execPerm(java.security.Permission perm) { return perm instanceof RuntimePermission && perm.getName() != null && perm.getName().startsWith("exec"); } private boolean catalogOnStack() { Class[] stack = getClassContext(); for (int i = 0; i < stack.length; i++) { ClassLoader loader = stack[i].getClassLoader(); if (loader instanceof CatalogLoader) return true; } return false; } } }