You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

adminpack.c 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*-------------------------------------------------------------------------
  2. *
  3. * adminpack.c
  4. *
  5. *
  6. * Copyright (c) 2002-2019, PostgreSQL Global Development Group
  7. *
  8. * Author: Andreas Pflug <pgadmin@pse-consulting.de>
  9. *
  10. * IDENTIFICATION
  11. * contrib/adminpack/adminpack.c
  12. *
  13. *-------------------------------------------------------------------------
  14. */
  15. #include "postgres.h"
  16. #include <sys/file.h>
  17. #include <sys/stat.h>
  18. #include <unistd.h>
  19. #include "catalog/pg_authid.h"
  20. #include "catalog/pg_type.h"
  21. #include "funcapi.h"
  22. #include "miscadmin.h"
  23. #include "postmaster/syslogger.h"
  24. #include "storage/fd.h"
  25. #include "utils/builtins.h"
  26. #include "utils/datetime.h"
  27. #ifdef WIN32
  28. #ifdef rename
  29. #undef rename
  30. #endif
  31. #ifdef unlink
  32. #undef unlink
  33. #endif
  34. #endif
  35. PG_MODULE_MAGIC;
  36. PG_FUNCTION_INFO_V1(pg_file_write);
  37. PG_FUNCTION_INFO_V1(pg_file_write_v1_1);
  38. PG_FUNCTION_INFO_V1(pg_file_rename);
  39. PG_FUNCTION_INFO_V1(pg_file_rename_v1_1);
  40. PG_FUNCTION_INFO_V1(pg_file_unlink);
  41. PG_FUNCTION_INFO_V1(pg_file_unlink_v1_1);
  42. PG_FUNCTION_INFO_V1(pg_logdir_ls);
  43. PG_FUNCTION_INFO_V1(pg_logdir_ls_v1_1);
  44. static int64 pg_file_write_internal(text *file, text *data, bool replace);
  45. static bool pg_file_rename_internal(text *file1, text *file2, text *file3);
  46. static Datum pg_logdir_ls_internal(FunctionCallInfo fcinfo);
  47. typedef struct
  48. {
  49. char *location;
  50. DIR *dirdesc;
  51. } directory_fctx;
  52. /*-----------------------
  53. * some helper functions
  54. */
  55. /*
  56. * Convert a "text" filename argument to C string, and check it's allowable.
  57. *
  58. * Filename may be absolute or relative to the DataDir, but we only allow
  59. * absolute paths that match DataDir or Log_directory.
  60. */
  61. static char *
  62. convert_and_check_filename(text *arg, bool logAllowed)
  63. {
  64. char *filename = text_to_cstring(arg);
  65. canonicalize_path(filename); /* filename can change length here */
  66. /*
  67. * Members of the 'pg_write_server_files' role are allowed to access any
  68. * files on the server as the PG user, so no need to do any further checks
  69. * here.
  70. */
  71. if (is_member_of_role(GetUserId(), DEFAULT_ROLE_WRITE_SERVER_FILES))
  72. return filename;
  73. /* User isn't a member of the default role, so check if it's allowable */
  74. if (is_absolute_path(filename))
  75. {
  76. /* Disallow '/a/b/data/..' */
  77. if (path_contains_parent_reference(filename))
  78. ereport(ERROR,
  79. (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
  80. (errmsg("reference to parent directory (\"..\") not allowed"))));
  81. /*
  82. * Allow absolute paths if within DataDir or Log_directory, even
  83. * though Log_directory might be outside DataDir.
  84. */
  85. if (!path_is_prefix_of_path(DataDir, filename) &&
  86. (!logAllowed || !is_absolute_path(Log_directory) ||
  87. !path_is_prefix_of_path(Log_directory, filename)))
  88. ereport(ERROR,
  89. (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
  90. (errmsg("absolute path not allowed"))));
  91. }
  92. else if (!path_is_relative_and_below_cwd(filename))
  93. ereport(ERROR,
  94. (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
  95. (errmsg("path must be in or below the current directory"))));
  96. return filename;
  97. }
  98. /*
  99. * check for superuser, bark if not.
  100. */
  101. static void
  102. requireSuperuser(void)
  103. {
  104. if (!superuser())
  105. ereport(ERROR,
  106. (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
  107. (errmsg("only superuser may access generic file functions"))));
  108. }
  109. /* ------------------------------------
  110. * pg_file_write - old version
  111. *
  112. * The superuser() check here must be kept as the library might be upgraded
  113. * without the extension being upgraded, meaning that in pre-1.1 installations
  114. * these functions could be called by any user.
  115. */
  116. Datum
  117. pg_file_write(PG_FUNCTION_ARGS)
  118. {
  119. text *file = PG_GETARG_TEXT_PP(0);
  120. text *data = PG_GETARG_TEXT_PP(1);
  121. bool replace = PG_GETARG_BOOL(2);
  122. int64 count = 0;
  123. requireSuperuser();
  124. count = pg_file_write_internal(file, data, replace);
  125. PG_RETURN_INT64(count);
  126. }
  127. /* ------------------------------------
  128. * pg_file_write_v1_1 - Version 1.1
  129. *
  130. * As of adminpack version 1.1, we no longer need to check if the user
  131. * is a superuser because we REVOKE EXECUTE on the function from PUBLIC.
  132. * Users can then grant access to it based on their policies.
  133. *
  134. * Otherwise identical to pg_file_write (above).
  135. */
  136. Datum
  137. pg_file_write_v1_1(PG_FUNCTION_ARGS)
  138. {
  139. text *file = PG_GETARG_TEXT_PP(0);
  140. text *data = PG_GETARG_TEXT_PP(1);
  141. bool replace = PG_GETARG_BOOL(2);
  142. int64 count = 0;
  143. count = pg_file_write_internal(file, data, replace);
  144. PG_RETURN_INT64(count);
  145. }
  146. /* ------------------------------------
  147. * pg_file_write_internal - Workhorse for pg_file_write functions.
  148. *
  149. * This handles the actual work for pg_file_write.
  150. */
  151. static int64
  152. pg_file_write_internal(text *file, text *data, bool replace)
  153. {
  154. FILE *f;
  155. char *filename;
  156. int64 count = 0;
  157. filename = convert_and_check_filename(file, false);
  158. if (!replace)
  159. {
  160. struct stat fst;
  161. if (stat(filename, &fst) >= 0)
  162. ereport(ERROR,
  163. (ERRCODE_DUPLICATE_FILE,
  164. errmsg("file \"%s\" exists", filename)));
  165. f = AllocateFile(filename, "wb");
  166. }
  167. else
  168. f = AllocateFile(filename, "ab");
  169. if (!f)
  170. ereport(ERROR,
  171. (errcode_for_file_access(),
  172. errmsg("could not open file \"%s\" for writing: %m",
  173. filename)));
  174. count = fwrite(VARDATA_ANY(data), 1, VARSIZE_ANY_EXHDR(data), f);
  175. if (count != VARSIZE_ANY_EXHDR(data) || FreeFile(f))
  176. ereport(ERROR,
  177. (errcode_for_file_access(),
  178. errmsg("could not write file \"%s\": %m", filename)));
  179. return (count);
  180. }
  181. /* ------------------------------------
  182. * pg_file_rename - old version
  183. *
  184. * The superuser() check here must be kept as the library might be upgraded
  185. * without the extension being upgraded, meaning that in pre-1.1 installations
  186. * these functions could be called by any user.
  187. */
  188. Datum
  189. pg_file_rename(PG_FUNCTION_ARGS)
  190. {
  191. text *file1;
  192. text *file2;
  193. text *file3;
  194. bool result;
  195. requireSuperuser();
  196. if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
  197. PG_RETURN_NULL();
  198. file1 = PG_GETARG_TEXT_PP(0);
  199. file2 = PG_GETARG_TEXT_PP(1);
  200. if (PG_ARGISNULL(2))
  201. file3 = NULL;
  202. else
  203. file3 = PG_GETARG_TEXT_PP(2);
  204. result = pg_file_rename_internal(file1, file2, file3);
  205. PG_RETURN_BOOL(result);
  206. }
  207. /* ------------------------------------
  208. * pg_file_rename_v1_1 - Version 1.1
  209. *
  210. * As of adminpack version 1.1, we no longer need to check if the user
  211. * is a superuser because we REVOKE EXECUTE on the function from PUBLIC.
  212. * Users can then grant access to it based on their policies.
  213. *
  214. * Otherwise identical to pg_file_write (above).
  215. */
  216. Datum
  217. pg_file_rename_v1_1(PG_FUNCTION_ARGS)
  218. {
  219. text *file1;
  220. text *file2;
  221. text *file3;
  222. bool result;
  223. if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
  224. PG_RETURN_NULL();
  225. file1 = PG_GETARG_TEXT_PP(0);
  226. file2 = PG_GETARG_TEXT_PP(1);
  227. if (PG_ARGISNULL(2))
  228. file3 = NULL;
  229. else
  230. file3 = PG_GETARG_TEXT_PP(2);
  231. result = pg_file_rename_internal(file1, file2, file3);
  232. PG_RETURN_BOOL(result);
  233. }
  234. /* ------------------------------------
  235. * pg_file_rename_internal - Workhorse for pg_file_rename functions.
  236. *
  237. * This handles the actual work for pg_file_rename.
  238. */
  239. static bool
  240. pg_file_rename_internal(text *file1, text *file2, text *file3)
  241. {
  242. char *fn1,
  243. *fn2,
  244. *fn3;
  245. int rc;
  246. fn1 = convert_and_check_filename(file1, false);
  247. fn2 = convert_and_check_filename(file2, false);
  248. if (file3 == NULL)
  249. fn3 = NULL;
  250. else
  251. fn3 = convert_and_check_filename(file3, false);
  252. if (access(fn1, W_OK) < 0)
  253. {
  254. ereport(WARNING,
  255. (errcode_for_file_access(),
  256. errmsg("file \"%s\" is not accessible: %m", fn1)));
  257. return false;
  258. }
  259. if (fn3 && access(fn2, W_OK) < 0)
  260. {
  261. ereport(WARNING,
  262. (errcode_for_file_access(),
  263. errmsg("file \"%s\" is not accessible: %m", fn2)));
  264. return false;
  265. }
  266. rc = access(fn3 ? fn3 : fn2, W_OK);
  267. if (rc >= 0 || errno != ENOENT)
  268. {
  269. ereport(ERROR,
  270. (ERRCODE_DUPLICATE_FILE,
  271. errmsg("cannot rename to target file \"%s\"",
  272. fn3 ? fn3 : fn2)));
  273. }
  274. if (fn3)
  275. {
  276. if (rename(fn2, fn3) != 0)
  277. {
  278. ereport(ERROR,
  279. (errcode_for_file_access(),
  280. errmsg("could not rename \"%s\" to \"%s\": %m",
  281. fn2, fn3)));
  282. }
  283. if (rename(fn1, fn2) != 0)
  284. {
  285. ereport(WARNING,
  286. (errcode_for_file_access(),
  287. errmsg("could not rename \"%s\" to \"%s\": %m",
  288. fn1, fn2)));
  289. if (rename(fn3, fn2) != 0)
  290. {
  291. ereport(ERROR,
  292. (errcode_for_file_access(),
  293. errmsg("could not rename \"%s\" back to \"%s\": %m",
  294. fn3, fn2)));
  295. }
  296. else
  297. {
  298. ereport(ERROR,
  299. (ERRCODE_UNDEFINED_FILE,
  300. errmsg("renaming \"%s\" to \"%s\" was reverted",
  301. fn2, fn3)));
  302. }
  303. }
  304. }
  305. else if (rename(fn1, fn2) != 0)
  306. {
  307. ereport(ERROR,
  308. (errcode_for_file_access(),
  309. errmsg("could not rename \"%s\" to \"%s\": %m", fn1, fn2)));
  310. }
  311. return true;
  312. }
  313. /* ------------------------------------
  314. * pg_file_unlink - old version
  315. *
  316. * The superuser() check here must be kept as the library might be upgraded
  317. * without the extension being upgraded, meaning that in pre-1.1 installations
  318. * these functions could be called by any user.
  319. */
  320. Datum
  321. pg_file_unlink(PG_FUNCTION_ARGS)
  322. {
  323. char *filename;
  324. requireSuperuser();
  325. filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0), false);
  326. if (access(filename, W_OK) < 0)
  327. {
  328. if (errno == ENOENT)
  329. PG_RETURN_BOOL(false);
  330. else
  331. ereport(ERROR,
  332. (errcode_for_file_access(),
  333. errmsg("file \"%s\" is not accessible: %m", filename)));
  334. }
  335. if (unlink(filename) < 0)
  336. {
  337. ereport(WARNING,
  338. (errcode_for_file_access(),
  339. errmsg("could not unlink file \"%s\": %m", filename)));
  340. PG_RETURN_BOOL(false);
  341. }
  342. PG_RETURN_BOOL(true);
  343. }
  344. /* ------------------------------------
  345. * pg_file_unlink_v1_1 - Version 1.1
  346. *
  347. * As of adminpack version 1.1, we no longer need to check if the user
  348. * is a superuser because we REVOKE EXECUTE on the function from PUBLIC.
  349. * Users can then grant access to it based on their policies.
  350. *
  351. * Otherwise identical to pg_file_unlink (above).
  352. */
  353. Datum
  354. pg_file_unlink_v1_1(PG_FUNCTION_ARGS)
  355. {
  356. char *filename;
  357. filename = convert_and_check_filename(PG_GETARG_TEXT_PP(0), false);
  358. if (access(filename, W_OK) < 0)
  359. {
  360. if (errno == ENOENT)
  361. PG_RETURN_BOOL(false);
  362. else
  363. ereport(ERROR,
  364. (errcode_for_file_access(),
  365. errmsg("file \"%s\" is not accessible: %m", filename)));
  366. }
  367. if (unlink(filename) < 0)
  368. {
  369. ereport(WARNING,
  370. (errcode_for_file_access(),
  371. errmsg("could not unlink file \"%s\": %m", filename)));
  372. PG_RETURN_BOOL(false);
  373. }
  374. PG_RETURN_BOOL(true);
  375. }
  376. /* ------------------------------------
  377. * pg_logdir_ls - Old version
  378. *
  379. * The superuser() check here must be kept as the library might be upgraded
  380. * without the extension being upgraded, meaning that in pre-1.1 installations
  381. * these functions could be called by any user.
  382. */
  383. Datum
  384. pg_logdir_ls(PG_FUNCTION_ARGS)
  385. {
  386. if (!superuser())
  387. ereport(ERROR,
  388. (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
  389. (errmsg("only superuser can list the log directory"))));
  390. return (pg_logdir_ls_internal(fcinfo));
  391. }
  392. /* ------------------------------------
  393. * pg_logdir_ls_v1_1 - Version 1.1
  394. *
  395. * As of adminpack version 1.1, we no longer need to check if the user
  396. * is a superuser because we REVOKE EXECUTE on the function from PUBLIC.
  397. * Users can then grant access to it based on their policies.
  398. *
  399. * Otherwise identical to pg_logdir_ls (above).
  400. */
  401. Datum
  402. pg_logdir_ls_v1_1(PG_FUNCTION_ARGS)
  403. {
  404. return (pg_logdir_ls_internal(fcinfo));
  405. }
  406. static Datum
  407. pg_logdir_ls_internal(FunctionCallInfo fcinfo)
  408. {
  409. FuncCallContext *funcctx;
  410. struct dirent *de;
  411. directory_fctx *fctx;
  412. if (strcmp(Log_filename, "postgresql-%Y-%m-%d_%H%M%S.log") != 0)
  413. ereport(ERROR,
  414. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  415. (errmsg("the log_filename parameter must equal 'postgresql-%%Y-%%m-%%d_%%H%%M%%S.log'"))));
  416. if (SRF_IS_FIRSTCALL())
  417. {
  418. MemoryContext oldcontext;
  419. TupleDesc tupdesc;
  420. funcctx = SRF_FIRSTCALL_INIT();
  421. oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
  422. fctx = palloc(sizeof(directory_fctx));
  423. tupdesc = CreateTemplateTupleDesc(2);
  424. TupleDescInitEntry(tupdesc, (AttrNumber) 1, "starttime",
  425. TIMESTAMPOID, -1, 0);
  426. TupleDescInitEntry(tupdesc, (AttrNumber) 2, "filename",
  427. TEXTOID, -1, 0);
  428. funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
  429. fctx->location = pstrdup(Log_directory);
  430. fctx->dirdesc = AllocateDir(fctx->location);
  431. if (!fctx->dirdesc)
  432. ereport(ERROR,
  433. (errcode_for_file_access(),
  434. errmsg("could not open directory \"%s\": %m",
  435. fctx->location)));
  436. funcctx->user_fctx = fctx;
  437. MemoryContextSwitchTo(oldcontext);
  438. }
  439. funcctx = SRF_PERCALL_SETUP();
  440. fctx = (directory_fctx *) funcctx->user_fctx;
  441. while ((de = ReadDir(fctx->dirdesc, fctx->location)) != NULL)
  442. {
  443. char *values[2];
  444. HeapTuple tuple;
  445. char timestampbuf[32];
  446. char *field[MAXDATEFIELDS];
  447. char lowstr[MAXDATELEN + 1];
  448. int dtype;
  449. int nf,
  450. ftype[MAXDATEFIELDS];
  451. fsec_t fsec;
  452. int tz = 0;
  453. struct pg_tm date;
  454. /*
  455. * Default format: postgresql-YYYY-MM-DD_HHMMSS.log
  456. */
  457. if (strlen(de->d_name) != 32
  458. || strncmp(de->d_name, "postgresql-", 11) != 0
  459. || de->d_name[21] != '_'
  460. || strcmp(de->d_name + 28, ".log") != 0)
  461. continue;
  462. /* extract timestamp portion of filename */
  463. strcpy(timestampbuf, de->d_name + 11);
  464. timestampbuf[17] = '\0';
  465. /* parse and decode expected timestamp to verify it's OK format */
  466. if (ParseDateTime(timestampbuf, lowstr, MAXDATELEN, field, ftype, MAXDATEFIELDS, &nf))
  467. continue;
  468. if (DecodeDateTime(field, ftype, nf, &dtype, &date, &fsec, &tz))
  469. continue;
  470. /* Seems the timestamp is OK; prepare and return tuple */
  471. values[0] = timestampbuf;
  472. values[1] = psprintf("%s/%s", fctx->location, de->d_name);
  473. tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
  474. SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
  475. }
  476. FreeDir(fctx->dirdesc);
  477. SRF_RETURN_DONE(funcctx);
  478. }