Исходный код СУБД 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
extern "C"
{
#include "postgres.h"
#include "fmgr.h"
#include "access/htup_details.h"
#include "catalog/pg_collation_d.h"
#include "catalog/pg_type_d.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "lib/stringinfo.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/formatting.h"
}
 
#include "dbms_network_acl_admin.hpp"
 
#include <cstring>
 
namespace DbmsNetworkAcl
{
 
static void
spiConnect()
{
    if (SPI_connect() != SPI_OK_CONNECT)
        ereport(ERROR,
                (errmsg("dbms_network_acl_admin: SPI не открылся"),
                 errdetail_internal("Output: [Status: FAIL]")));
}
 
static uint64
execRows(const char *sql, int nargs, Oid *argtypes, Datum *values, const char *nulls, bool read)
{
    int rc;
    uint64 n;
 
    spiConnect();
    rc = SPI_execute_with_args(sql, nargs, argtypes, values, nulls, read, read ? 1 : 0);
    if (rc < 0)
    {
        SPI_finish();
        ereport(ERROR,
                (errmsg("dbms_network_acl_admin: запрос каталога не выполнен"),
                 errdetail_internal("Output: [Status: FAIL, Code: %d]", rc)));
    }
    n = SPI_processed;
    SPI_finish();
    return n;
}
 
static void
badArgument()
{
    ereport(ERROR,
            (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
             errmsg("ORA-29261: bad argument")));
}
 
static void
notGranted()
{
    ereport(ERROR,
            (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
             errmsg("ORA-01927: A privilege cannot be revoked if you did not grant it.")));
}
 
static void
logAce(const char *status, const char *host, const char *ports,
       const char *principal, const char *privilege)
{
    ereport(LOG,
            (errmsg("dbms_network_acl_admin: %s", status),
             errdetail_internal("Output: [Status: %s, Host: %s, Port: %s, Principal: %s, Privilege: %s]",
                                status, host, ports, principal, privilege)));
}
 
static char *
portText(bool lowerNull, int32 lower, bool upperNull, int32 upper)
{
    char buf[64];
 
    if (lowerNull && upperNull)
        return pstrdup("-");
    if (lowerNull)
        snprintf(buf, sizeof(buf), "-%d", upper);
    else if (upperNull)
        snprintf(buf, sizeof(buf), "%d-", lower);
    else
        snprintf(buf, sizeof(buf), "%d-%d", lower, upper);
    return pstrdup(buf);
}
 
struct Ace
{
    char **privileges;
    int npriv;
    bool is_grant;
    bool inverted;
    char *principal;
    bool ptype_null;
    int32 ptype;
    bool start_null;
    Datum start_date;
    bool end_null;
    Datum end_date;
};
 
static char *
textAttr(HeapTupleHeader rec, const char *name, bool *isnull)
{
    Datum d = GetAttributeByName(rec, name, isnull);
 
    if (*isnull)
        return NULL;
    return text_to_cstring(DatumGetTextPP(d));
}
 
static Ace
readAce(HeapTupleHeader rec)
{
    Ace ace;
    bool isnull = false;
    Datum d;
    ArrayType *arr;
    Datum *elems;
    bool *elemnulls;
    int nelems;
    int i;
 
    memset(&ace, 0, sizeof(ace));
 
    d = GetAttributeByName(rec, "privilege_list", &isnull);
    if (isnull)
        badArgument();
    arr = DatumGetArrayTypeP(d);
    deconstruct_array_builtin(arr, TEXTOID, &elems, &elemnulls, &nelems);
    if (nelems <= 0)
        badArgument();
    ace.privileges = (char **) palloc(sizeof(char *) * nelems);
    ace.npriv = 0;
    for (i = 0; i < nelems; i++)
    {
        char *raw;
        char *up;
 
        if (elemnulls[i])
            badArgument();
        raw = text_to_cstring(DatumGetTextPP(elems[i]));
        if (raw[0] == '\0')
            badArgument();
        up = str_toupper(raw, strlen(raw), DEFAULT_COLLATION_OID);
        ace.privileges[ace.npriv++] = up;
    }
 
    d = GetAttributeByName(rec, "is_grant", &isnull);
    if (isnull)
        badArgument();
    ace.is_grant = DatumGetBool(d);
 
    d = GetAttributeByName(rec, "inverted", &isnull);
    if (isnull)
        badArgument();
    ace.inverted = DatumGetBool(d);
 
    ace.principal = textAttr(rec, "principal_name", &isnull);
    if (isnull || ace.principal == NULL || ace.principal[0] == '\0')
        badArgument();
 
    d = GetAttributeByName(rec, "principal_type", &isnull);
    ace.ptype_null = isnull;
    if (!isnull)
        ace.ptype = DatumGetInt32(d);
 
    ace.start_date = GetAttributeByName(rec, "start_date", &ace.start_null);
    ace.end_date = GetAttributeByName(rec, "end_date", &ace.end_null);
    return ace;
}
 
static void
bindIdentity(Oid *argtypes, Datum *values, char *nulls,
             const char *host, bool lowerNull, int32 lower, bool upperNull, int32 upper,
             const Ace *ace, int privIndex, bool flag)
{
    argtypes[0] = TEXTOID;
    argtypes[1] = INT4OID;
    argtypes[2] = INT4OID;
    argtypes[3] = TEXTOID;
    argtypes[4] = TEXTOID;
    argtypes[5] = BOOLOID;
    argtypes[6] = BOOLOID;
    argtypes[7] = INT4OID;
    argtypes[8] = TIMESTAMPTZOID;
    argtypes[9] = TIMESTAMPTZOID;
    argtypes[10] = BOOLOID;
 
    values[0] = CStringGetTextDatum(host);
    nulls[0] = ' ';
    values[1] = Int32GetDatum(lower);
    nulls[1] = lowerNull ? 'n' : ' ';
    values[2] = Int32GetDatum(upper);
    nulls[2] = upperNull ? 'n' : ' ';
    values[3] = CStringGetTextDatum(ace->principal);
    nulls[3] = ' ';
    values[4] = CStringGetTextDatum(ace->privileges[privIndex]);
    nulls[4] = ' ';
    values[5] = BoolGetDatum(ace->is_grant);
    nulls[5] = ' ';
    values[6] = BoolGetDatum(ace->inverted);
    nulls[6] = ' ';
    values[7] = Int32GetDatum(ace->ptype);
    nulls[7] = ace->ptype_null ? 'n' : ' ';
    values[8] = ace->start_date;
    nulls[8] = ace->start_null ? 'n' : ' ';
    values[9] = ace->end_date;
    nulls[9] = ace->end_null ? 'n' : ' ';
    values[10] = BoolGetDatum(flag);
    nulls[10] = ' ';
}
 
static const char *existsSql =
    "SELECT 1 FROM pg_catalog.dbms_network_acl_host_ace "
    " WHERE host = $1 "
    "   AND lower_port IS NOT DISTINCT FROM $2 "
    "   AND upper_port IS NOT DISTINCT FROM $3 "
    "   AND principal = $4 "
    "   AND privilege = $5 "
    "   AND is_grant = $6 "
    "   AND inverted = $7 "
    "   AND principal_type IS NOT DISTINCT FROM $8 "
    "   AND start_date IS NOT DISTINCT FROM $9 "
    "   AND end_date IS NOT DISTINCT FROM $10 "
    "   AND private_target = $11";
 
static const char *insertSql =
    "INSERT INTO pg_catalog.dbms_network_acl_host_ace "
    "(host, lower_port, upper_port, principal, privilege, is_grant, inverted, "
    " principal_type, start_date, end_date, private_target) "
    "VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)";
 
static const char *deleteSql =
    "DELETE FROM pg_catalog.dbms_network_acl_host_ace "
    " WHERE host = $1 "
    "   AND lower_port IS NOT DISTINCT FROM $2 "
    "   AND upper_port IS NOT DISTINCT FROM $3 "
    "   AND principal = $4 "
    "   AND privilege = $5 "
    "   AND is_grant = $6 "
    "   AND inverted = $7 "
    "   AND principal_type IS NOT DISTINCT FROM $8 "
    "   AND start_date IS NOT DISTINCT FROM $9 "
    "   AND end_date IS NOT DISTINCT FROM $10";
 
static char *
privilegeList(const Ace *ace)
{
    StringInfoData buf;
    int i;
 
    initStringInfo(&buf);
    for (i = 0; i < ace->npriv; i++)
    {
        if (i > 0)
            appendStringInfoChar(&buf, ',');
        appendStringInfoString(&buf, ace->privileges[i]);
    }
    return buf.data;
}
 
void
appendAce(const char *host, bool lowerNull, int32 lower, bool upperNull, int32 upper,
          HeapTupleHeader rec, bool private_target)
{
    Ace ace;
    char *ports;
    char *privs;
    bool inserted = false;
    int i;
 
    if (host == NULL)
        badArgument();
    ace = readAce(rec);
    ports = portText(lowerNull, lower, upperNull, upper);
    privs = privilegeList(&ace);
 
    for (i = 0; i < ace.npriv; i++)
    {
        Oid argtypes[11];
        Datum values[11];
        char nulls[11];
 
        bindIdentity(argtypes, values, nulls, host, lowerNull, lower, upperNull, upper,
                     &ace, i, private_target);
        if (execRows(existsSql, 11, argtypes, values, nulls, true) > 0)
            continue;
        execRows(insertSql, 11, argtypes, values, nulls, false);
        inserted = true;
    }
 
    logAce(inserted ? "ACE добавлена" : "ACE уже есть", host, ports, ace.principal, privs);
}
 
void
removeAce(const char *host, bool lowerNull, int32 lower, bool upperNull, int32 upper,
          HeapTupleHeader rec, bool remove_empty)
{
    Ace ace;
    char *ports;
    char *privs;
    uint64 removed = 0;
    int i;
 
    if (host == NULL)
        badArgument();
    ace = readAce(rec);
    ports = portText(lowerNull, lower, upperNull, upper);
    privs = privilegeList(&ace);
 
    for (i = 0; i < ace.npriv; i++)
    {
        Oid argtypes[11];
        Datum values[11];
        char nulls[11];
 
        bindIdentity(argtypes, values, nulls, host, lowerNull, lower, upperNull, upper,
                     &ace, i, false);
        removed += execRows(deleteSql, 10, argtypes, values, nulls, false);
    }
 
    if (removed == 0 && !remove_empty)
        notGranted();
 
    logAce(removed > 0 ? "ACE снята" : "ACE не было", host, ports, ace.principal, privs);
}
 
} /* namespace DbmsNetworkAcl */
 
extern "C"
{
 
PG_FUNCTION_INFO_V1(c_dbms_network_acl_admin_append_host_ace);
PG_FUNCTION_INFO_V1(c_dbms_network_acl_admin_remove_host_ace);
 
Datum
c_dbms_network_acl_admin_append_host_ace(PG_FUNCTION_ARGS)
{
    bool lowerNull = PG_ARGISNULL(1);
    bool upperNull = PG_ARGISNULL(2);
    int32 lower = lowerNull ? 0 : PG_GETARG_INT32(1);
    int32 upper = upperNull ? 0 : PG_GETARG_INT32(2);
    bool private_target = false;
 
    if (PG_ARGISNULL(0) || PG_ARGISNULL(3))
        DbmsNetworkAcl::badArgument();
    if (!PG_ARGISNULL(4))
        private_target = PG_GETARG_BOOL(4);
 
    DbmsNetworkAcl::appendAce(text_to_cstring(PG_GETARG_TEXT_PP(0)),
                              lowerNull, lower, upperNull, upper,
                              PG_GETARG_HEAPTUPLEHEADER(3),
                              private_target);
    PG_RETURN_VOID();
}
 
Datum
c_dbms_network_acl_admin_remove_host_ace(PG_FUNCTION_ARGS)
{
    bool lowerNull = PG_ARGISNULL(1);
    bool upperNull = PG_ARGISNULL(2);
    int32 lower = lowerNull ? 0 : PG_GETARG_INT32(1);
    int32 upper = upperNull ? 0 : PG_GETARG_INT32(2);
    bool remove_empty = false;
 
    if (PG_ARGISNULL(0) || PG_ARGISNULL(3))
        DbmsNetworkAcl::badArgument();
    if (!PG_ARGISNULL(4))
        remove_empty = PG_GETARG_BOOL(4);
 
    DbmsNetworkAcl::removeAce(text_to_cstring(PG_GETARG_TEXT_PP(0)),
                              lowerNull, lower, upperNull, upper,
                              PG_GETARG_HEAPTUPLEHEADER(3),
                              remove_empty);
    PG_RETURN_VOID();
}
 
void
dbms_network_acl_admin_check_connect(const char *host, int port)
{
    MemoryContext caller = CurrentMemoryContext;
    const char *sql =
        "SELECT principal FROM pg_catalog.dbms_network_acl_host_ace "
        " WHERE host = $1 "
        "   AND privilege = 'CONNECT' "
        "   AND is_grant "
        "   AND NOT inverted "
        "   AND ((lower_port IS NULL AND upper_port IS NULL) "
        "        OR $2 BETWEEN lower_port AND upper_port) "
        " LIMIT 1";
    Oid argtypes[2] = {TEXTOID, INT4OID};
    Datum values[2];
    char nulls[2] = {' ', ' '};
    int rc;
    bool allowed = false;
    char *principal = NULL;
 
    if (host == NULL || host[0] == '\0')
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 errmsg("ORA-24247: network access denied by access control list (ACL)"),
                 errdetail_internal("Output: [Status: DENY, Host: , Port: %d, Privilege: CONNECT]",
                                    port)));
 
    values[0] = CStringGetTextDatum(host);
    values[1] = Int32GetDatum(port);
 
    if (SPI_connect() != SPI_OK_CONNECT)
        ereport(ERROR,
                (errmsg("dbms_network_acl_admin: SPI не открылся"),
                 errdetail_internal("Output: [Status: FAIL]")));
 
    rc = SPI_execute_with_args(sql, 2, argtypes, values, nulls, true, 1);
    if (rc != SPI_OK_SELECT)
    {
        SPI_finish();
        ereport(ERROR,
                (errmsg("dbms_network_acl_admin: запрос каталога не выполнен"),
                 errdetail_internal("Output: [Status: FAIL, Code: %d]", rc)));
    }
    if (SPI_processed == 1)
    {
        bool isnull = false;
        Datum d = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
 
        allowed = true;
        if (!isnull)
        {
            char *tmp = text_to_cstring(DatumGetTextPP(d));
 
            principal = MemoryContextStrdup(caller, tmp);
        }
    }
    SPI_finish();
 
    if (!allowed)
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 errmsg("ORA-24247: network access denied by access control list (ACL)"),
                 errdetail_internal("Output: [Status: DENY, Host: %s, Port: %d, Privilege: CONNECT]",
                                    host, port)));
 
    ereport(LOG,
            (errmsg("dbms_network_acl_admin: соединение разрешено"),
             errdetail_internal("Output: [Status: OK, Host: %s, Port: %d, Principal: %s, Privilege: CONNECT]",
                                host, port, principal != NULL ? principal : "-")));
}
 
} /* extern "C" */