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 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
|
/*
* Attention - this functionality doesn't work when Orace is not linked with
* correct runtime library. The combination "vcruntime140.dll" is working for
* PostgreSQL 12 (vcruntime140d.dll doesn't work). Probably this runtime should
* be same like Postgres server runtime (what is used can be detected by
* dependency walker). Without correct linking the server crash when IO related
* functionality is used.
*/
#ifdef _MSC_VER
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include "postgres.h"
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include "executor/spi.h"
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "fmgr.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "port.h"
#include "storage/fd.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#ifdef WIN32
#include "utils/pg_locale.h"
#endif
#include "orafce.h"
#include "builtins.h"
#ifndef ERRCODE_NO_DATA_FOUND
#define ERRCODE_NO_DATA_FOUND MAKE_SQLSTATE('P','0', '0','0','2')
#endif
#define INVALID_OPERATION "UTL_FILE_INVALID_OPERATION"
#define WRITE_ERROR "UTL_FILE_WRITE_ERROR"
#define READ_ERROR "UTL_FILE_READ_ERROR"
#define INVALID_FILEHANDLE "UTL_FILE_INVALID_FILEHANDLE"
#define INVALID_MAXLINESIZE "UTL_FILE_INVALID_MAXLINESIZE"
#define INVALID_MODE "UTL_FILE_INVALID_MODE"
#define INVALID_PATH "UTL_FILE_INVALID_PATH"
#define VALUE_ERROR "UTL_FILE_VALUE_ERROR"
PG_FUNCTION_INFO_V1(utl_file_fopen);
PG_FUNCTION_INFO_V1(utl_file_is_open);
PG_FUNCTION_INFO_V1(utl_file_get_line);
PG_FUNCTION_INFO_V1(utl_file_get_nextline);
PG_FUNCTION_INFO_V1(utl_file_put);
PG_FUNCTION_INFO_V1(utl_file_put_line);
PG_FUNCTION_INFO_V1(utl_file_new_line);
PG_FUNCTION_INFO_V1(utl_file_putf);
PG_FUNCTION_INFO_V1(utl_file_fflush);
PG_FUNCTION_INFO_V1(utl_file_fclose);
PG_FUNCTION_INFO_V1(utl_file_fclose_all);
PG_FUNCTION_INFO_V1(utl_file_fremove);
PG_FUNCTION_INFO_V1(utl_file_frename);
PG_FUNCTION_INFO_V1(utl_file_fcopy);
PG_FUNCTION_INFO_V1(utl_file_fgetattr);
PG_FUNCTION_INFO_V1(utl_file_tmpdir);
#define CUSTOM_EXCEPTION(msg, detail) \
ereport(ERROR, \
(errcode(ERRCODE_RAISE_EXCEPTION), \
errmsg("%s", msg), \
errdetail("%s", detail)))
#define STRERROR_EXCEPTION(msg) \
do { char *strerr = strerror(errno); CUSTOM_EXCEPTION(msg, strerr); } while(0);
#define INVALID_FILEHANDLE_EXCEPTION() CUSTOM_EXCEPTION(INVALID_FILEHANDLE, "Used file handle isn't valid.")
#define CHECK_FILE_HANDLE() \
if (PG_ARGISNULL(0)) \
CUSTOM_EXCEPTION(INVALID_FILEHANDLE, "Used file handle isn't valid.")
#define NON_EMPTY_TEXT(dat) \
if (VARSIZE(dat) - VARHDRSZ == 0) \
ereport(ERROR, \
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
errmsg("invalid parameter"), \
errdetail("Empty string isn't allowed.")));
#define NOT_NULL_ARG(n) \
if (PG_ARGISNULL(n)) \
ereport(ERROR, \
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), \
errmsg("null value not allowed"), \
errhint("%dth argument is NULL.", n)));
#define MAX_LINESIZE 32767
#define CHECK_LINESIZE(max_linesize) \
do { \
if ((max_linesize) < 1 || (max_linesize) > MAX_LINESIZE) \
CUSTOM_EXCEPTION(INVALID_MAXLINESIZE, "maxlinesize is out of range"); \
} while(0)
typedef struct FileSlot
{
FILE *file;
int max_linesize;
int encoding;
int32 id;
} FileSlot;
#define MAX_SLOTS 50 /* Oracle 10g supports 50 files */
#define INVALID_SLOTID 0 /* invalid slot id */
static FileSlot slots[MAX_SLOTS]; /* initilaized with zeros */
static int32 slotid = 0; /* next slot id */
static void check_secure_locality(const char *path);
static char *get_safe_path(text *location, text *filename);
static int copy_text_file(FILE *srcfile, FILE *dstfile,
int start_line, int end_line);
static int orafce_umask = 077;
char *orafce_umask_str = NULL;
static Oid orafce_set_umask_roleid = InvalidOid;
void
orafce_umask_assign_hook(const char *newvalue, void *extra)
{
orafce_umask = *((int *) extra);
}
bool
orafce_umask_check_hook(char **newval, void **extra, GucSource source)
{
int digits = 0;
char *ptr = *newval;
int *myextra;
if (orafce_initialized && IsNormalProcessingMode() && IsTransactionState())
{
if (!superuser())
{
if (!OidIsValid(orafce_set_umask_roleid))
orafce_set_umask_roleid = get_role_oid("orafce_set_umask", false);
if (!has_privs_of_role(GetUserId(), orafce_set_umask_roleid))
{
GUC_check_errcode(ERRCODE_INSUFFICIENT_PRIVILEGE);
GUC_check_errmsg("permission denied to set \"orafce.umask\"");
GUC_check_errdetail("Only roles with privileges of the \"orafce_set_umask\" can set \"orafce.umask\".");
return false;
}
}
}
while (*ptr)
{
if (*ptr < '0' || *ptr > '7')
{
GUC_check_errdetail("invalid octal digit");
return false;
}
if (digits > 3)
{
GUC_check_errdetail("number is too big (only four digits are allowed");
return false;
}
ptr++;
digits++;
}
#if PG_VERSION_NUM >= 160000
myextra = (int *) guc_malloc(LOG, sizeof(int));
#else
myextra = (int *) malloc(sizeof(int));
#endif
if (!myextra)
return false;
*myextra = (int) strtol(*newval, NULL, 8);
*extra = (void *) myextra;
return true;
}
/*
* get_descriptor(FILE *file) find any free slot for FILE pointer.
* If isn't realloc array slots and add 32 new free slots.
*
*/
static int
get_descriptor(FILE *file, int max_linesize, int encoding)
{
int i;
for (i = 0; i < MAX_SLOTS; i++)
{
if (slots[i].id == INVALID_SLOTID)
{
slots[i].id = ++slotid;
if (slots[i].id == INVALID_SLOTID)
slots[i].id = ++slotid; /* skip INVALID_SLOTID */
slots[i].file = file;
slots[i].max_linesize = max_linesize;
slots[i].encoding = encoding;
return slots[i].id;
}
}
return INVALID_SLOTID;
}
/* return stored pointer to FILE */
static FILE *
get_stream(int d, size_t *max_linesize, int *encoding)
{
int i;
if (d == INVALID_SLOTID)
INVALID_FILEHANDLE_EXCEPTION();
for (i = 0; i < MAX_SLOTS; i++)
{
if (slots[i].id == d)
{
if (max_linesize)
*max_linesize = slots[i].max_linesize;
if (encoding)
*encoding = slots[i].encoding;
return slots[i].file;
}
}
INVALID_FILEHANDLE_EXCEPTION();
return NULL; /* keep compiler quiet */
}
static void
IO_EXCEPTION(void)
{
switch (errno)
{
case EACCES:
case ENAMETOOLONG:
case ENOENT:
case ENOTDIR:
STRERROR_EXCEPTION(INVALID_PATH);
break;
default:
STRERROR_EXCEPTION(INVALID_OPERATION);
}
}
/*
* On WIN32 platform multibyte chars are not supported by
* fopen function. Instead we can use _wfopen functin. The
* arguments are of wchar strings, and should to use UTF16
* charset. Conversion from server encoding to wide strings
* is provided by function char2wchar (tested only for UTF8)
*/
#ifdef WIN32
static wchar_t *
to_wchar(const char *str)
{
size_t nbytes;
wchar_t *buff;
nbytes = strlen(str);
if ((nbytes + 1) > INT_MAX / sizeof(wchar_t))
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
buff = (wchar_t *) palloc((nbytes + 1) * sizeof(wchar_t));
char2wchar(buff, nbytes + 1, str, nbytes, 0);
return buff;
}
#endif
/*
* FUNCTION UTL_FILE.FOPEN(location text,
* filename text,
* open_mode text,
* max_linesize integer
* [, encoding text ])
* RETURNS UTL_FILE.FILE_TYPE;
*
* The FOPEN function opens specified file and returns file handle.
* open_mode: ['R', 'W', 'A']
* max_linesize: [1 .. 32767]
*
* Exceptions:
* INVALID_MODE, INVALID_OPERATION, INVALID_PATH, INVALID_MAXLINESIZE
*/
Datum
utl_file_fopen(PG_FUNCTION_ARGS)
{
text *open_mode;
int max_linesize;
int encoding;
const char *mode = NULL;
FILE *file;
char *fullname;
int d;
mode_t oldmask;
NOT_NULL_ARG(0);
NOT_NULL_ARG(1);
NOT_NULL_ARG(2);
NOT_NULL_ARG(3);
open_mode = PG_GETARG_TEXT_P(2);
NON_EMPTY_TEXT(open_mode);
max_linesize = PG_GETARG_INT32(3);
CHECK_LINESIZE(max_linesize);
if (PG_NARGS() > 4 && !PG_ARGISNULL(4))
{
const char *encname = NameStr(*PG_GETARG_NAME(4));
encoding = pg_char_to_encoding(encname);
if (encoding < 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid encoding name \"%s\"", encname)));
}
else
encoding = GetDatabaseEncoding();
if (VARSIZE(open_mode) - VARHDRSZ != 1)
CUSTOM_EXCEPTION(INVALID_MODE, "open mode is different than [R,W,A]");
switch (*((char *) VARDATA(open_mode)))
{
case 'a':
case 'A':
mode = "a";
break;
case 'r':
case 'R':
mode = "r";
break;
case 'w':
case 'W':
mode = "w";
break;
default:
CUSTOM_EXCEPTION(INVALID_MODE, "open mode is different than [R,W,A]");
}
/* open file */
fullname = get_safe_path(PG_GETARG_TEXT_P(0), PG_GETARG_TEXT_P(1));
/*
* We cannot use AllocateFile here because those files are automatically
* closed at the end of (sub)transactions, but we want to keep them open
* for oracle compatibility.
*/
oldmask = umask((mode_t) orafce_umask);
#ifndef WIN32
file = fopen(fullname, mode);
#else
if (pg_database_encoding_max_length() > 1)
{
wchar_t *_fullname = to_wchar(fullname);
wchar_t *_mode = to_wchar(mode);
file = _wfopen(_fullname, _mode);
pfree(_fullname);
pfree(_mode);
}
else
file = fopen(fullname, mode);
#endif
umask(oldmask);
if (!file)
IO_EXCEPTION();
d = get_descriptor(file, max_linesize, encoding);
if (d == INVALID_SLOTID)
{
fclose(file);
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("program limit exceeded"),
errdetail("Too many files opened concurrently"),
errhint("You can only open a maximum of ten files for each session")));
}
PG_RETURN_INT32(d);
}
Datum
utl_file_is_open(PG_FUNCTION_ARGS)
{
if (!PG_ARGISNULL(0))
{
int i;
int d = PG_GETARG_INT32(0);
for (i = 0; i < MAX_SLOTS; i++)
{
if (slots[i].id == d)
PG_RETURN_BOOL(slots[i].file != NULL);
}
}
PG_RETURN_BOOL(false);
}
#define CHECK_LENGTH(l) \
if (l > max_linesize) \
CUSTOM_EXCEPTION(VALUE_ERROR, "buffer is too short");
/* read line from file. set eof if is EOF */
static text *
get_line(FILE *f, size_t max_linesize, int encoding, bool *iseof)
{
int c;
char *buffer = NULL;
char *bpt;
size_t csize = 0;
text *result = NULL;
bool eof = true;
buffer = palloc(max_linesize + 2);
bpt = buffer;
errno = 0;
while (csize < max_linesize && (c = fgetc(f)) != EOF)
{
eof = false; /* I was able read one char */
if (c == '\r') /* lookin ahead \n */
{
c = fgetc(f);
if (c == EOF)
break; /* last char */
if (c != '\n')
ungetc(c, f);
/* skip \r\n */
break;
}
else if (c == '\n')
break;
++csize;
*bpt++ = c;
}
if (!eof)
{
char *decoded;
size_t len;
pg_verify_mbstr(encoding, buffer, size2int(csize), false);
decoded = (char *) pg_do_encoding_conversion((unsigned char *) buffer,
size2int(csize), encoding, GetDatabaseEncoding());
len = (decoded == buffer ? csize : strlen(decoded));
result = palloc(len + VARHDRSZ);
memcpy(VARDATA(result), decoded, len);
SET_VARSIZE(result, len + VARHDRSZ);
if (decoded != buffer)
pfree(decoded);
*iseof = false;
}
else
{
switch (errno)
{
case 0:
break;
case EBADF:
CUSTOM_EXCEPTION(INVALID_OPERATION, "file descriptor isn't valid for reading");
break;
default:
STRERROR_EXCEPTION(READ_ERROR);
break;
}
*iseof = true;
}
pfree(buffer);
return result;
}
/*
* FUNCTION UTL_FILE.GET_LINE(file UTL_TYPE.FILE_TYPE, line int DEFAULT NULL)
* RETURNS text;
*
* Reads one line from file.
*
* Exceptions:
* NO_DATA_FOUND, INVALID_FILEHANDLE, INVALID_OPERATION, READ_ERROR
*/
Datum
utl_file_get_line(PG_FUNCTION_ARGS)
{
size_t max_linesize = 0; /* keep compiler quiet */
int encoding = 0; /* keep compiler quiet */
FILE *f;
text *result;
bool iseof;
CHECK_FILE_HANDLE();
f = get_stream(PG_GETARG_INT32(0), &max_linesize, &encoding);
/* 'len' overwrites max_linesize, but must be smaller than max_linesize */
if (PG_NARGS() > 1 && !PG_ARGISNULL(1))
{
size_t len = (size_t) PG_GETARG_INT32(1);
CHECK_LINESIZE(len);
if (max_linesize > len)
max_linesize = len;
}
result = get_line(f, max_linesize, encoding, &iseof);
if (iseof)
ereport(ERROR,
(errcode(ERRCODE_NO_DATA_FOUND),
errmsg("no data found")));
PG_RETURN_TEXT_P(result);
}
/*
* FUNCTION UTL_FILE.GET_NEXTLINE(file UTL_TYPE.FILE_TYPE)
* RETURNS text;
*
* Reads one line from file or retutns NULL
* by Steven Feuerstein.
*
* Exceptions:
* INVALID_FILEHANDLE, INVALID_OPERATION, READ_ERROR
*/
Datum
utl_file_get_nextline(PG_FUNCTION_ARGS)
{
size_t max_linesize = 0; /* keep compiler quiet */
int encoding = 0; /* keep compiler quiet */
FILE *f;
text *result;
bool iseof;
CHECK_FILE_HANDLE();
f = get_stream(PG_GETARG_INT32(0), &max_linesize, &encoding);
result = get_line(f, max_linesize, encoding, &iseof);
if (iseof)
PG_RETURN_NULL();
PG_RETURN_TEXT_P(result);
}
static void
do_flush(FILE *f)
{
if (fflush(f) != 0)
{
if (errno == EBADF)
CUSTOM_EXCEPTION(INVALID_OPERATION, "File is not an opened, or is not open for writing");
else
STRERROR_EXCEPTION(WRITE_ERROR);
}
}
/*
* FUNCTION UTL_FILE.PUT(file UTL_FILE.FILE_TYPE, buffer text)
* RETURNS bool;
*
* The PUT function puts data out to specified file. Buffer length allowed is
* 32K or 1024 (max_linesize);
*
* Exceptions:
* INVALID_FILEHANDLE, INVALID_OPERATION, WRITE_ERROR, VALUE_ERROR
*
* Note: returns bool because I cannot do envelope over void function
*/
#define CHECK_ERRNO_PUT() \
switch (errno) \
{ \
case EBADF: \
CUSTOM_EXCEPTION(INVALID_OPERATION, "file descriptor isn't valid for writing"); \
break; \
default: \
STRERROR_EXCEPTION(WRITE_ERROR); \
}
/* encode(t, encoding) */
static char *
encode_text(int encoding, text *t, size_t *length)
{
char *src = VARDATA_ANY(t);
char *encoded;
encoded = (char *) pg_do_encoding_conversion((unsigned char *) src,
VARSIZE_ANY_EXHDR(t), GetDatabaseEncoding(), encoding);
*length = (src == encoded ? VARSIZE_ANY_EXHDR(t) : strlen(encoded));
return encoded;
}
/* fwrite(encode(args[n], encoding), f) */
static size_t
do_write(PG_FUNCTION_ARGS, int n, FILE *f, size_t max_linesize, int encoding)
{
text *arg = PG_GETARG_TEXT_P(n);
char *str;
size_t len;
str = encode_text(encoding, arg, &len);
CHECK_LENGTH(len);
if (fwrite(str, 1, len, f) != len)
CHECK_ERRNO_PUT();
if (VARDATA(arg) != str)
pfree(str);
PG_FREE_IF_COPY(arg, n);
return len;
}
static FILE *
do_put(PG_FUNCTION_ARGS)
{
FILE *f;
size_t max_linesize = 0; /* keep compiler quiet */
int encoding = 0; /* keep compiler quiet */
CHECK_FILE_HANDLE();
f = get_stream(PG_GETARG_INT32(0), &max_linesize, &encoding);
NOT_NULL_ARG(1);
do_write(fcinfo, 1, f, max_linesize, encoding);
return f;
}
Datum
utl_file_put(PG_FUNCTION_ARGS)
{
do_put(fcinfo);
PG_RETURN_BOOL(true);
}
static void
do_new_line(FILE *f, int lines)
{
int i;
for (i = 0; i < lines; i++)
{
#ifndef WIN32
if (fputc('\n', f) == EOF)
CHECK_ERRNO_PUT();
#else
if (fputs("\r\n", f) == EOF)
CHECK_ERRNO_PUT();
#endif
}
}
Datum
utl_file_put_line(PG_FUNCTION_ARGS)
{
FILE *f;
bool autoflush;
f = do_put(fcinfo);
autoflush = PG_GETARG_IF_EXISTS(2, BOOL, false);
do_new_line(f, 1);
if (autoflush)
do_flush(f);
PG_RETURN_BOOL(true);
}
Datum
utl_file_new_line(PG_FUNCTION_ARGS)
{
FILE *f;
int lines;
CHECK_FILE_HANDLE();
f = get_stream(PG_GETARG_INT32(0), NULL, NULL);
lines = PG_GETARG_IF_EXISTS(1, INT32, 1);
do_new_line(f, lines);
PG_RETURN_BOOL(true);
}
/*
* FUNCTION UTL_FILE.PUTF(file UTL_FILE.FILE_TYPE,
* format text,
* arg1 text,
* arg2 text,
* arg3 text,
* arg4 text,
* arg5 text)
* RETURNS bool;
*
* Puts formated data to file. Allows %s like subst symbol.
*
* Exception:
* INVALID_FILEHANDLE, INVALID_OPERATION, WRITE_ERROR
*/
Datum
utl_file_putf(PG_FUNCTION_ARGS)
{
FILE *f;
char *format;
size_t max_linesize;
int encoding;
size_t format_length;
char *fpt;
int cur_par = 0;
size_t cur_len = 0;
CHECK_FILE_HANDLE();
f = get_stream(PG_GETARG_INT32(0), &max_linesize, &encoding);
NOT_NULL_ARG(1);
format = encode_text(encoding, PG_GETARG_TEXT_P(1), &format_length);
for (fpt = format; format_length > 0; fpt++, format_length--)
{
if (format_length == 1)
{
/* last char */
CHECK_LENGTH(++cur_len);
if (fputc(*fpt, f) == EOF)
CHECK_ERRNO_PUT();
continue;
}
/* ansi compatible string */
if (fpt[0] == '\\' && fpt[1] == 'n')
{
CHECK_LENGTH(++cur_len);
if (fputc('\n', f) == EOF)
CHECK_ERRNO_PUT();
fpt++;
format_length--;
continue;
}
if (fpt[0] == '%')
{
if (fpt[1] == '%')
{
CHECK_LENGTH(++cur_len);
if (fputc('%', f) == EOF)
CHECK_ERRNO_PUT();
}
else if (fpt[1] == 's' && ++cur_par <= 5 && !PG_ARGISNULL(cur_par + 1))
{
cur_len += do_write(fcinfo, cur_par + 1, f, max_linesize - cur_len, encoding);
}
fpt++;
format_length--;
continue;
}
CHECK_LENGTH(++cur_len);
if (fputc(fpt[0], f) == EOF)
CHECK_ERRNO_PUT();
}
PG_RETURN_BOOL(true);
}
/*
* FUNCTION UTL_FILE.FFLUSH(file UTL_FILE.FILE_TYPE)
* RETURNS void;
*
* This function makes sure that all pending data for the specified file is written
* physically out to file.
*
* Exceptions:
* INVALID_FILEHANDLE, INVALID_OPERATION, WRITE_ERROR
*/
Datum
utl_file_fflush(PG_FUNCTION_ARGS)
{
FILE *f;
CHECK_FILE_HANDLE();
f = get_stream(PG_GETARG_INT32(0), NULL, NULL);
do_flush(f);
PG_RETURN_VOID();
}
/*
* FUNCTION UTL_FILE.FCLOSE(file UTL_FILE.FILE_TYPE)
* RETURNS NULL
*
* Close an open file. This function reset file handle to NULL on Oracle platform.
* It isn't possible in PostgreSQL, and then you have to call fclose function
* like:
* file := utl_file.fclose(file);
*
* Exception:
* INVALID_FILEHANDLE, WRITE_ERROR
*/
Datum
utl_file_fclose(PG_FUNCTION_ARGS)
{
int i;
int d = PG_GETARG_INT32(0);
for (i = 0; i < MAX_SLOTS; i++)
{
if (slots[i].id == d)
{
FILE *f = slots[i].file;
slots[i].file = NULL;
slots[i].id = INVALID_SLOTID;
if (f && fclose(f) != 0)
{
if (errno == EBADF)
CUSTOM_EXCEPTION(INVALID_FILEHANDLE, "File is not an opened");
else
STRERROR_EXCEPTION(WRITE_ERROR);
}
PG_RETURN_NULL();
}
}
INVALID_FILEHANDLE_EXCEPTION();
PG_RETURN_NULL();
}
/*
* FUNCTION UTL_FILE.FCLOSE_ALL()
* RETURNS void
*
* Close all opened files.
*
* Exceptions: WRITE_ERROR
*/
Datum
utl_file_fclose_all(PG_FUNCTION_ARGS)
{
int i;
for (i = 0; i < MAX_SLOTS; i++)
{
if (slots[i].id != INVALID_SLOTID)
{
FILE *f = slots[i].file;
slots[i].file = NULL;
slots[i].id = INVALID_SLOTID;
if (f && fclose(f) != 0)
{
if (errno == EBADF)
CUSTOM_EXCEPTION(INVALID_FILEHANDLE, "File is not an opened");
else
STRERROR_EXCEPTION(WRITE_ERROR);
}
}
}
PG_RETURN_VOID();
}
/*
* utl_file_dir security .. is solved with aux. table.
*
* Raise exception if don't find string in table.
*/
static void
check_secure_locality(const char *path)
{
static SPIPlanPtr plan = NULL;
Datum values[1];
char nulls[1] = {' '};
values[0] = CStringGetTextDatum(path);
/*
* SELECT 1 FROM utl_file.utl_file_dir WHERE CASE WHEN substring(dir from
* '.$') = '/' THEN substring($1, 1, length(dir)) = dir ELSE substring($1,
* 1, length(dir) + 1) = dir || '/' END
*/
if (SPI_connect() < 0)
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("SPI_connect failed")));
if (!plan)
{
Oid argtypes[] = {TEXTOID};
/* Don't use LIKE not to escape '_' and '%' */
SPIPlanPtr p = SPI_prepare(
"SELECT 1 FROM utl_file.utl_file_dir"
" WHERE CASE WHEN substring(dir from '.$') = '/' THEN"
" substring($1, 1, length(dir)) = dir"
" ELSE"
" substring($1, 1, length(dir) + 1) = dir || '/'"
" END",
1, argtypes);
if (p == NULL || (plan = SPI_saveplan(p)) == NULL)
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("SPI_prepare_failed")));
}
if (SPI_OK_SELECT != SPI_execute_plan(plan, values, nulls, false, 1))
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("can't execute sql")));
if (SPI_processed == 0)
ereport(ERROR,
(errcode(ERRCODE_RAISE_EXCEPTION),
errmsg(INVALID_PATH),
errdetail("you cannot access locality"),
errhint("locality is not found in utl_file_dir table")));
SPI_finish();
}
static char *
safe_named_location(text *location)
{
static SPIPlanPtr plan = NULL;
MemoryContext old_cxt;
Datum values[1];
char nulls[1] = {' '};
char *result;
old_cxt = CurrentMemoryContext;
values[0] = PointerGetDatum(location);
if (SPI_connect() < 0)
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("SPI_connect failed")));
if (!plan)
{
Oid argtypes[] = {TEXTOID};
/* Don't use LIKE not to escape '_' and '%' */
SPIPlanPtr p = SPI_prepare(
"SELECT dir FROM utl_file.utl_file_dir WHERE dirname = $1",
1, argtypes);
if (p == NULL || (plan = SPI_saveplan(p)) == NULL)
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("SPI_prepare_failed")));
}
if (SPI_OK_SELECT != SPI_execute_plan(plan, values, nulls, false, 1))
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("can't execute sql")));
if (SPI_processed > 0)
{
char *loc = SPI_getvalue(SPI_tuptable->vals[0],
SPI_tuptable->tupdesc, 1);
if (loc)
result = MemoryContextStrdup(old_cxt, loc);
else
result = NULL;
}
else
result = NULL;
SPI_finish();
MemoryContextSwitchTo(old_cxt);
return result;
}
/*
* get_safe_path - make a fullpath and check security.
*/
static char *
get_safe_path(text *location_or_dirname, text *filename)
{
char *fullname;
char *location;
bool check_locality;
NON_EMPTY_TEXT(location_or_dirname);
NON_EMPTY_TEXT(filename);
location = safe_named_location(location_or_dirname);
if (location)
{
int aux_pos = size2int(strlen(location));
int aux_len = VARSIZE_ANY_EXHDR(filename);
fullname = palloc(aux_pos + 1 + aux_len + 1);
strcpy(fullname, location);
fullname[aux_pos] = '/';
memcpy(fullname + aux_pos + 1, VARDATA(filename), aux_len);
fullname[aux_pos + aux_len + 1] = '\0';
/* location is safe (ensured by dirname) */
check_locality = false;
pfree(location);
}
else
{
int aux_pos = VARSIZE_ANY_EXHDR(location_or_dirname);
int aux_len = VARSIZE_ANY_EXHDR(filename);
fullname = palloc(aux_pos + 1 + aux_len + 1);
memcpy(fullname, VARDATA(location_or_dirname), aux_pos);
fullname[aux_pos] = '/';
memcpy(fullname + aux_pos + 1, VARDATA(filename), aux_len);
fullname[aux_pos + aux_len + 1] = '\0';
check_locality = true;
}
/* check locality in canonizalized form of path */
canonicalize_path(fullname);
if (check_locality)
check_secure_locality(fullname);
return fullname;
}
/*
* CREATE FUNCTION utl_file.fremove(
* location text,
* filename text)
*/
Datum
utl_file_fremove(PG_FUNCTION_ARGS)
{
char *fullname;
NOT_NULL_ARG(0);
NOT_NULL_ARG(1);
fullname = get_safe_path(PG_GETARG_TEXT_P(0), PG_GETARG_TEXT_P(1));
#ifndef WIN32
if (unlink(fullname) != 0)
IO_EXCEPTION();
#else
if (pg_database_encoding_max_length() > 1)
{
wchar_t *_fullname = to_wchar(fullname);
if (_wunlink(_fullname) != 0)
IO_EXCEPTION();
pfree(_fullname);
}
else
{
if (unlink(fullname) != 0)
IO_EXCEPTION();
}
#endif
PG_RETURN_VOID();
}
/*
* CREATE FUNCTION utl_file.frename(
* location text,
* filename text,
* dest_dir text,
* dest_file text,
* overwrite boolean DEFAULT false)
*/
Datum
utl_file_frename(PG_FUNCTION_ARGS)
{
char *srcpath;
char *dstpath;
bool overwrite;
NOT_NULL_ARG(0);
NOT_NULL_ARG(1);
NOT_NULL_ARG(2);
NOT_NULL_ARG(3);
overwrite = PG_GETARG_IF_EXISTS(4, BOOL, false);
srcpath = get_safe_path(PG_GETARG_TEXT_P(0), PG_GETARG_TEXT_P(1));
dstpath = get_safe_path(PG_GETARG_TEXT_P(2), PG_GETARG_TEXT_P(3));
#ifndef WIN32
if (!overwrite)
{
struct stat st;
if (stat(dstpath, &st) == 0)
CUSTOM_EXCEPTION(WRITE_ERROR, "File exists");
else if (errno != ENOENT)
IO_EXCEPTION();
}
/* rename() overwrites existing files. */
if (rename(srcpath, dstpath) != 0)
IO_EXCEPTION();
#else
if (pg_database_encoding_max_length() > 1)
{
wchar_t *_dstpath = to_wchar(dstpath);
wchar_t *_srcpath = to_wchar(srcpath);
if (!overwrite)
{
struct _stat _st;
if (_wstat(_dstpath, &_st) == 0)
CUSTOM_EXCEPTION(WRITE_ERROR, "File exists");
else if (errno != ENOENT)
IO_EXCEPTION();
}
/*
* Originaly there was rename() function, but this cannot to replace
* other existing file.
*/
if (!MoveFileExW(_srcpath, _dstpath, MOVEFILE_REPLACE_EXISTING))
IO_EXCEPTION();
pfree(_dstpath);
pfree(_srcpath);
}
else
{
if (!overwrite)
{
struct stat st;
if (stat(dstpath, &st) == 0)
CUSTOM_EXCEPTION(WRITE_ERROR, "File exists");
else if (errno != ENOENT)
IO_EXCEPTION();
}
if (!MoveFileEx(srcpath, dstpath, MOVEFILE_REPLACE_EXISTING))
IO_EXCEPTION();
}
#endif
PG_RETURN_VOID();
}
/*
* CREATE FUNCTION utl_file.fcopy(
* src_location text,
* src_filename text,
* dest_location text,
* dest_filename text,
* start_line integer DEFAULT NULL
* end_line integer DEFAULT NULL)
*/
Datum
utl_file_fcopy(PG_FUNCTION_ARGS)
{
char *srcpath;
char *dstpath;
int start_line;
int end_line;
FILE *srcfile;
FILE *dstfile;
NOT_NULL_ARG(0);
NOT_NULL_ARG(1);
NOT_NULL_ARG(2);
NOT_NULL_ARG(3);
srcpath = get_safe_path(PG_GETARG_TEXT_P(0), PG_GETARG_TEXT_P(1));
dstpath = get_safe_path(PG_GETARG_TEXT_P(2), PG_GETARG_TEXT_P(3));
start_line = PG_GETARG_IF_EXISTS(4, INT32, 1);
if (start_line <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("start_line must be positive (%d passed)", start_line)));
end_line = PG_GETARG_IF_EXISTS(5, INT32, INT_MAX);
if (end_line <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("end_line must be positive (%d passed)", end_line)));
#ifndef WIN32
srcfile = fopen(srcpath, "rt");
#else
if (pg_database_encoding_max_length() > 1)
{
wchar_t *_srcpath = to_wchar(srcpath);
wchar_t *_mode = to_wchar("rt");
srcfile = _wfopen(_srcpath, _mode);
pfree(_srcpath);
pfree(_mode);
}
else
srcfile = fopen(srcpath, "rt");
#endif
if (srcfile == NULL)
{
/* failed to open src file. */
IO_EXCEPTION();
}
#ifndef WIN32
dstfile = fopen(dstpath, "wt");
#else
if (pg_database_encoding_max_length() > 1)
{
wchar_t *_dstpath = to_wchar(dstpath);
wchar_t *_mode = to_wchar("wt");
dstfile = _wfopen(_dstpath, _mode);
pfree(_dstpath);
pfree(_mode);
}
else
dstfile = fopen(dstpath, "wt");
#endif
if (dstfile == NULL)
{
/* failed to open dst file. */
fclose(srcfile);
IO_EXCEPTION();
}
if (copy_text_file(srcfile, dstfile, start_line, end_line))
IO_EXCEPTION();
fclose(srcfile);
fclose(dstfile);
PG_RETURN_VOID();
}
/*
* Copy srcfile to dstfile. Return 0 if succeeded, or non-0 if error.
*/
static int
copy_text_file(FILE *srcfile, FILE *dstfile, int start_line, int end_line)
{
char *buffer;
size_t len;
int i;
buffer = palloc(MAX_LINESIZE);
errno = 0;
/* skip first start_line. */
for (i = 1; i < start_line; i++)
{
CHECK_FOR_INTERRUPTS();
do
{
if (fgets(buffer, MAX_LINESIZE, srcfile) == NULL)
return errno;
len = strlen(buffer);
} while (buffer[len - 1] != '\n');
}
/* copy until end_line. */
for (; i <= end_line; i++)
{
CHECK_FOR_INTERRUPTS();
do
{
if (fgets(buffer, MAX_LINESIZE, srcfile) == NULL)
return errno;
len = strlen(buffer);
if (fwrite(buffer, 1, len, dstfile) != len)
return errno;
} while (buffer[len - 1] != '\n');
}
pfree(buffer);
return 0;
}
/*
* CREATE FUNCTION utl_file.fgetattr(
* location text,
* filename text
* ) RETURNS (
* fexists boolean,
* file_length bigint,
* blocksize integer)
*/
Datum
utl_file_fgetattr(PG_FUNCTION_ARGS)
{
char *fullname;
struct stat st;
TupleDesc tupdesc;
Datum result;
HeapTuple tuple;
Datum values[3];
bool nulls[3] = {0};
NOT_NULL_ARG(0);
NOT_NULL_ARG(1);
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
elog(ERROR, "return type must be a row type");
fullname = get_safe_path(PG_GETARG_TEXT_P(0), PG_GETARG_TEXT_P(1));
#ifndef WIN32
if (stat(fullname, &st) == 0)
{
values[0] = BoolGetDatum(true);
values[1] = Int64GetDatum(st.st_size);
values[2] = Int32GetDatum(st.st_blksize);
}
else
{
values[0] = BoolGetDatum(false);
nulls[1] = true;
nulls[2] = true;
}
#else
if (pg_database_encoding_max_length() > 1)
{
wchar_t *_fullname = to_wchar(fullname);
struct _stat _st;
if (_wstat(_fullname, &_st) == 0)
{
values[0] = BoolGetDatum(true);
values[1] = Int64GetDatum(_st.st_size);
values[2] = 512; /* NTFS block size */
}
else
{
values[0] = BoolGetDatum(false);
nulls[1] = true;
nulls[2] = true;
}
pfree(_fullname);
}
else if (stat(fullname, &st) == 0)
{
values[0] = BoolGetDatum(true);
values[1] = Int64GetDatum(st.st_size);
values[2] = 512; /* NTFS block size */
}
else
{
values[0] = BoolGetDatum(false);
nulls[1] = true;
nulls[2] = true;
}
#endif
tuple = heap_form_tuple(tupdesc, values, nulls);
result = HeapTupleGetDatum(tuple);
PG_RETURN_DATUM(result);
}
Datum
utl_file_tmpdir(PG_FUNCTION_ARGS)
{
#ifndef WIN32
const char *tmpdir = getenv("TMPDIR");
if (!tmpdir)
tmpdir = "/tmp";
#else
char tmpdir[MAXPGPATH];
int ret;
ret = GetTempPathA(MAXPGPATH, tmpdir);
if (ret == 0 || ret > MAXPGPATH)
CUSTOM_EXCEPTION(INVALID_PATH, strerror(errno));
canonicalize_path(tmpdir);
#endif
PG_RETURN_TEXT_P(cstring_to_text(tmpdir));
}
|