Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
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<Boolean> jmxTouched = new ThreadLocal<Boolean>();
 
    private static final ThreadLocal<java.security.PermissionCollection> grantsHold =
            new ThreadLocal<java.security.PermissionCollection>();
    private static final ThreadLocal<Integer> deadlineHold = new ThreadLocal<Integer>();
 
    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<Env> envHold = new ThreadLocal<Env>();
 
    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<String, byte[]> 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<String, byte[]> 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<Boolean> checking = new ThreadLocal<Boolean>();
 
        @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;
        }
    }
}