PostgreSQL Source Code  git master
genfile.c File Reference
#include "postgres.h"
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include "access/htup_details.h"
#include "access/xlog_internal.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_tablespace_d.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "postmaster/syslogger.h"
#include "storage/fd.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
Include dependency graph for genfile.c:

Go to the source code of this file.

Macros

#define MIN_READ_SIZE   4096
 

Functions

static char * convert_and_check_filename (text *arg)
 
static bytearead_binary_file (const char *filename, int64 seek_offset, int64 bytes_to_read, bool missing_ok)
 
static textread_text_file (const char *filename, int64 seek_offset, int64 bytes_to_read, bool missing_ok)
 
Datum pg_read_file (PG_FUNCTION_ARGS)
 
Datum pg_read_file_v2 (PG_FUNCTION_ARGS)
 
Datum pg_read_binary_file (PG_FUNCTION_ARGS)
 
Datum pg_read_file_off_len (PG_FUNCTION_ARGS)
 
Datum pg_read_file_all (PG_FUNCTION_ARGS)
 
Datum pg_read_binary_file_off_len (PG_FUNCTION_ARGS)
 
Datum pg_read_binary_file_all (PG_FUNCTION_ARGS)
 
Datum pg_stat_file (PG_FUNCTION_ARGS)
 
Datum pg_stat_file_1arg (PG_FUNCTION_ARGS)
 
Datum pg_ls_dir (PG_FUNCTION_ARGS)
 
Datum pg_ls_dir_1arg (PG_FUNCTION_ARGS)
 
static Datum pg_ls_dir_files (FunctionCallInfo fcinfo, const char *dir, bool missing_ok)
 
Datum pg_ls_logdir (PG_FUNCTION_ARGS)
 
Datum pg_ls_waldir (PG_FUNCTION_ARGS)
 
static Datum pg_ls_tmpdir (FunctionCallInfo fcinfo, Oid tblspc)
 
Datum pg_ls_tmpdir_noargs (PG_FUNCTION_ARGS)
 
Datum pg_ls_tmpdir_1arg (PG_FUNCTION_ARGS)
 
Datum pg_ls_archive_statusdir (PG_FUNCTION_ARGS)
 

Macro Definition Documentation

◆ MIN_READ_SIZE

#define MIN_READ_SIZE   4096

Referenced by read_binary_file().

Function Documentation

◆ convert_and_check_filename()

static char* convert_and_check_filename ( text arg)
static

Definition at line 53 of file genfile.c.

References canonicalize_path(), DataDir, ereport, errcode(), ERRCODE_INSUFFICIENT_PRIVILEGE, errmsg(), ERROR, filename, GetUserId(), is_absolute_path, is_member_of_role(), Log_directory, path_contains_parent_reference(), path_is_prefix_of_path(), path_is_relative_and_below_cwd(), and text_to_cstring().

Referenced by pg_ls_dir(), pg_read_binary_file(), pg_read_file(), pg_read_file_v2(), and pg_stat_file().

54 {
55  char *filename;
56 
57  filename = text_to_cstring(arg);
58  canonicalize_path(filename); /* filename can change length here */
59 
60  /*
61  * Members of the 'pg_read_server_files' role are allowed to access any
62  * files on the server as the PG user, so no need to do any further checks
63  * here.
64  */
65  if (is_member_of_role(GetUserId(), DEFAULT_ROLE_READ_SERVER_FILES))
66  return filename;
67 
68  /* User isn't a member of the default role, so check if it's allowable */
69  if (is_absolute_path(filename))
70  {
71  /* Disallow '/a/b/data/..' */
72  if (path_contains_parent_reference(filename))
73  ereport(ERROR,
75  errmsg("reference to parent directory (\"..\") not allowed")));
76 
77  /*
78  * Allow absolute paths if within DataDir or Log_directory, even
79  * though Log_directory might be outside DataDir.
80  */
81  if (!path_is_prefix_of_path(DataDir, filename) &&
84  ereport(ERROR,
86  errmsg("absolute path not allowed")));
87  }
88  else if (!path_is_relative_and_below_cwd(filename))
89  ereport(ERROR,
91  errmsg("path must be in or below the current directory")));
92 
93  return filename;
94 }
char * Log_directory
Definition: syslogger.c:72
Oid GetUserId(void)
Definition: miscinit.c:476
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition: path.c:438
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:610
bool path_contains_parent_reference(const char *path)
Definition: path.c:376
#define ERRCODE_INSUFFICIENT_PRIVILEGE
#define ERROR
Definition: elog.h:43
#define is_absolute_path(filename)
Definition: port.h:86
bool path_is_relative_and_below_cwd(const char *path)
Definition: path.c:405
#define ereport(elevel,...)
Definition: elog.h:144
bool is_member_of_role(Oid member, Oid role)
Definition: acl.c:4916
char * text_to_cstring(const text *t)
Definition: varlena.c:221
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
char * DataDir
Definition: globals.c:62

◆ pg_ls_archive_statusdir()

Datum pg_ls_archive_statusdir ( PG_FUNCTION_ARGS  )

Definition at line 717 of file genfile.c.

References pg_ls_dir_files(), and XLOGDIR.

718 {
719  return pg_ls_dir_files(fcinfo, XLOGDIR "/archive_status", true);
720 }
static Datum pg_ls_dir_files(FunctionCallInfo fcinfo, const char *dir, bool missing_ok)
Definition: genfile.c:574
#define XLOGDIR

◆ pg_ls_dir()

Datum pg_ls_dir ( PG_FUNCTION_ARGS  )

Definition at line 477 of file genfile.c.

References AllocateDir(), ReturnSetInfo::allowedModes, convert_and_check_filename(), CreateTemplateTupleDesc(), CStringGetTextDatum, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, FreeDir(), IsA, MemoryContextSwitchTo(), PG_ARGISNULL, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, ReadDir(), ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_putvalues(), values, and work_mem.

Referenced by pg_ls_dir_1arg().

478 {
479  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
480  char *location;
481  bool missing_ok = false;
482  bool include_dot_dirs = false;
483  bool randomAccess;
484  TupleDesc tupdesc;
485  Tuplestorestate *tupstore;
486  DIR *dirdesc;
487  struct dirent *de;
488  MemoryContext oldcontext;
489 
491 
492  /* check the optional arguments */
493  if (PG_NARGS() == 3)
494  {
495  if (!PG_ARGISNULL(1))
496  missing_ok = PG_GETARG_BOOL(1);
497  if (!PG_ARGISNULL(2))
498  include_dot_dirs = PG_GETARG_BOOL(2);
499  }
500 
501  /* check to see if caller supports us returning a tuplestore */
502  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
503  ereport(ERROR,
504  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
505  errmsg("set-valued function called in context that cannot accept a set")));
506  if (!(rsinfo->allowedModes & SFRM_Materialize))
507  ereport(ERROR,
508  (errcode(ERRCODE_SYNTAX_ERROR),
509  errmsg("materialize mode required, but it is not allowed in this context")));
510 
511  /* The tupdesc and tuplestore must be created in ecxt_per_query_memory */
513 
514  tupdesc = CreateTemplateTupleDesc(1);
515  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "pg_ls_dir", TEXTOID, -1, 0);
516 
517  randomAccess = (rsinfo->allowedModes & SFRM_Materialize_Random) != 0;
518  tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
519  rsinfo->returnMode = SFRM_Materialize;
520  rsinfo->setResult = tupstore;
521  rsinfo->setDesc = tupdesc;
522 
523  MemoryContextSwitchTo(oldcontext);
524 
525  dirdesc = AllocateDir(location);
526  if (!dirdesc)
527  {
528  /* Return empty tuplestore if appropriate */
529  if (missing_ok && errno == ENOENT)
530  return (Datum) 0;
531  /* Otherwise, we can let ReadDir() throw the error */
532  }
533 
534  while ((de = ReadDir(dirdesc, location)) != NULL)
535  {
536  Datum values[1];
537  bool nulls[1];
538 
539  if (!include_dot_dirs &&
540  (strcmp(de->d_name, ".") == 0 ||
541  strcmp(de->d_name, "..") == 0))
542  continue;
543 
544  values[0] = CStringGetTextDatum(de->d_name);
545  nulls[0] = false;
546 
547  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
548  }
549 
550  FreeDir(dirdesc);
551  return (Datum) 0;
552 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
static char * convert_and_check_filename(text *arg)
Definition: genfile.c:53
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:44
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
Definition: dirent.h:9
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:308
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2583
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:603
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
uintptr_t Datum
Definition: postgres.h:367
int work_mem
Definition: globals.c:121
#define ereport(elevel,...)
Definition: elog.h:144
int allowedModes
Definition: execnodes.h:304
SetFunctionReturnMode returnMode
Definition: execnodes.h:306
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2649
#define PG_NARGS()
Definition: fmgr.h:203
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:232
Tuplestorestate * setResult
Definition: execnodes.h:309
static Datum values[MAXATTR]
Definition: bootstrap.c:165
ExprContext * econtext
Definition: execnodes.h:302
TupleDesc setDesc
Definition: execnodes.h:310
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define CStringGetTextDatum(s)
Definition: builtins.h:86
int16 AttrNumber
Definition: attnum.h:21
int FreeDir(DIR *dir)
Definition: fd.c:2701

◆ pg_ls_dir_1arg()

Datum pg_ls_dir_1arg ( PG_FUNCTION_ARGS  )

Definition at line 562 of file genfile.c.

References pg_ls_dir().

563 {
564  return pg_ls_dir(fcinfo);
565 }
Datum pg_ls_dir(PG_FUNCTION_ARGS)
Definition: genfile.c:477

◆ pg_ls_dir_files()

static Datum pg_ls_dir_files ( FunctionCallInfo  fcinfo,
const char *  dir,
bool  missing_ok 
)
static

Definition at line 574 of file genfile.c.

References AllocateDir(), ReturnSetInfo::allowedModes, CStringGetTextDatum, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, FreeDir(), get_call_result_type(), Int64GetDatum(), IsA, MAXPGPATH, MemoryContextSwitchTo(), ReadDir(), FunctionCallInfoBaseData::resultinfo, ReturnSetInfo::returnMode, S_ISREG, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, snprintf, stat::st_mode, stat::st_mtime, stat::st_size, stat, time_t_to_timestamptz(), TimestampTzGetDatum, tuplestore_begin_heap(), tuplestore_putvalues(), TYPEFUNC_COMPOSITE, values, and work_mem.

Referenced by pg_ls_archive_statusdir(), pg_ls_logdir(), pg_ls_tmpdir(), and pg_ls_waldir().

575 {
576  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
577  bool randomAccess;
578  TupleDesc tupdesc;
579  Tuplestorestate *tupstore;
580  DIR *dirdesc;
581  struct dirent *de;
582  MemoryContext oldcontext;
583 
584  /* check to see if caller supports us returning a tuplestore */
585  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
586  ereport(ERROR,
587  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
588  errmsg("set-valued function called in context that cannot accept a set")));
589  if (!(rsinfo->allowedModes & SFRM_Materialize))
590  ereport(ERROR,
591  (errcode(ERRCODE_SYNTAX_ERROR),
592  errmsg("materialize mode required, but it is not allowed in this context")));
593 
594  /* The tupdesc and tuplestore must be created in ecxt_per_query_memory */
596 
597  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
598  elog(ERROR, "return type must be a row type");
599 
600  randomAccess = (rsinfo->allowedModes & SFRM_Materialize_Random) != 0;
601  tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
602  rsinfo->returnMode = SFRM_Materialize;
603  rsinfo->setResult = tupstore;
604  rsinfo->setDesc = tupdesc;
605 
606  MemoryContextSwitchTo(oldcontext);
607 
608  /*
609  * Now walk the directory. Note that we must do this within a single SRF
610  * call, not leave the directory open across multiple calls, since we
611  * can't count on the SRF being run to completion.
612  */
613  dirdesc = AllocateDir(dir);
614  if (!dirdesc)
615  {
616  /* Return empty tuplestore if appropriate */
617  if (missing_ok && errno == ENOENT)
618  return (Datum) 0;
619  /* Otherwise, we can let ReadDir() throw the error */
620  }
621 
622  while ((de = ReadDir(dirdesc, dir)) != NULL)
623  {
624  Datum values[3];
625  bool nulls[3];
626  char path[MAXPGPATH * 2];
627  struct stat attrib;
628 
629  /* Skip hidden files */
630  if (de->d_name[0] == '.')
631  continue;
632 
633  /* Get the file info */
634  snprintf(path, sizeof(path), "%s/%s", dir, de->d_name);
635  if (stat(path, &attrib) < 0)
636  {
637  /* Ignore concurrently-deleted files, else complain */
638  if (errno == ENOENT)
639  continue;
640  ereport(ERROR,
642  errmsg("could not stat file \"%s\": %m", path)));
643  }
644 
645  /* Ignore anything but regular files */
646  if (!S_ISREG(attrib.st_mode))
647  continue;
648 
649  values[0] = CStringGetTextDatum(de->d_name);
650  values[1] = Int64GetDatum((int64) attrib.st_size);
651  values[2] = TimestampTzGetDatum(time_t_to_timestamptz(attrib.st_mtime));
652  memset(nulls, 0, sizeof(nulls));
653 
654  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
655  }
656 
657  FreeDir(dirdesc);
658  return (Datum) 0;
659 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:205
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:610
Definition: dirent.h:9
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
fmNodePtr resultinfo
Definition: fmgr.h:89
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:633
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2583
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1701
#define S_ISREG(m)
Definition: win32_port.h:319
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
uintptr_t Datum
Definition: postgres.h:367
int work_mem
Definition: globals.c:121
TimestampTz time_t_to_timestamptz(pg_time_t tm)
Definition: timestamp.c:1698
#define ereport(elevel,...)
Definition: elog.h:144
int allowedModes
Definition: execnodes.h:304
SetFunctionReturnMode returnMode
Definition: execnodes.h:306
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2649
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:232
Tuplestorestate * setResult
Definition: execnodes.h:309
static Datum values[MAXATTR]
Definition: bootstrap.c:165
ExprContext * econtext
Definition: execnodes.h:302
TupleDesc setDesc
Definition: execnodes.h:310
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
#define CStringGetTextDatum(s)
Definition: builtins.h:86
#define snprintf
Definition: port.h:215
int FreeDir(DIR *dir)
Definition: fd.c:2701
#define stat
Definition: win32_port.h:275

◆ pg_ls_logdir()

Datum pg_ls_logdir ( PG_FUNCTION_ARGS  )

Definition at line 663 of file genfile.c.

References Log_directory, and pg_ls_dir_files().

664 {
665  return pg_ls_dir_files(fcinfo, Log_directory, false);
666 }
char * Log_directory
Definition: syslogger.c:72
static Datum pg_ls_dir_files(FunctionCallInfo fcinfo, const char *dir, bool missing_ok)
Definition: genfile.c:574

◆ pg_ls_tmpdir()

static Datum pg_ls_tmpdir ( FunctionCallInfo  fcinfo,
Oid  tblspc 
)
static

Definition at line 679 of file genfile.c.

References ereport, errcode(), errmsg(), ERROR, MAXPGPATH, ObjectIdGetDatum, pg_ls_dir_files(), SearchSysCacheExists1, TABLESPACEOID, and TempTablespacePath().

Referenced by pg_ls_tmpdir_1arg(), and pg_ls_tmpdir_noargs().

680 {
681  char path[MAXPGPATH];
682 
684  ereport(ERROR,
685  (errcode(ERRCODE_UNDEFINED_OBJECT),
686  errmsg("tablespace with OID %u does not exist",
687  tblspc)));
688 
689  TempTablespacePath(path, tblspc);
690  return pg_ls_dir_files(fcinfo, path, true);
691 }
int errcode(int sqlerrcode)
Definition: elog.c:610
void TempTablespacePath(char *path, Oid tablespace)
Definition: fd.c:1631
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:183
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define MAXPGPATH
static Datum pg_ls_dir_files(FunctionCallInfo fcinfo, const char *dir, bool missing_ok)
Definition: genfile.c:574
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ pg_ls_tmpdir_1arg()

Datum pg_ls_tmpdir_1arg ( PG_FUNCTION_ARGS  )

Definition at line 708 of file genfile.c.

References PG_GETARG_OID, and pg_ls_tmpdir().

709 {
710  return pg_ls_tmpdir(fcinfo, PG_GETARG_OID(0));
711 }
static Datum pg_ls_tmpdir(FunctionCallInfo fcinfo, Oid tblspc)
Definition: genfile.c:679
#define PG_GETARG_OID(n)
Definition: fmgr.h:275

◆ pg_ls_tmpdir_noargs()

Datum pg_ls_tmpdir_noargs ( PG_FUNCTION_ARGS  )

Definition at line 698 of file genfile.c.

References pg_ls_tmpdir().

699 {
700  return pg_ls_tmpdir(fcinfo, DEFAULTTABLESPACE_OID);
701 }
static Datum pg_ls_tmpdir(FunctionCallInfo fcinfo, Oid tblspc)
Definition: genfile.c:679

◆ pg_ls_waldir()

Datum pg_ls_waldir ( PG_FUNCTION_ARGS  )

Definition at line 670 of file genfile.c.

References pg_ls_dir_files(), and XLOGDIR.

671 {
672  return pg_ls_dir_files(fcinfo, XLOGDIR, false);
673 }
static Datum pg_ls_dir_files(FunctionCallInfo fcinfo, const char *dir, bool missing_ok)
Definition: genfile.c:574
#define XLOGDIR

◆ pg_read_binary_file()

Datum pg_read_binary_file ( PG_FUNCTION_ARGS  )

Definition at line 322 of file genfile.c.

References convert_and_check_filename(), ereport, errcode(), errmsg(), ERROR, filename, PG_GETARG_BOOL, PG_GETARG_INT64, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_BYTEA_P, PG_RETURN_NULL, and read_binary_file().

Referenced by pg_read_binary_file_all(), and pg_read_binary_file_off_len().

323 {
324  text *filename_t = PG_GETARG_TEXT_PP(0);
325  int64 seek_offset = 0;
326  int64 bytes_to_read = -1;
327  bool missing_ok = false;
328  char *filename;
329  bytea *result;
330 
331  /* handle optional arguments */
332  if (PG_NARGS() >= 3)
333  {
334  seek_offset = PG_GETARG_INT64(1);
335  bytes_to_read = PG_GETARG_INT64(2);
336 
337  if (bytes_to_read < 0)
338  ereport(ERROR,
339  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
340  errmsg("requested length cannot be negative")));
341  }
342  if (PG_NARGS() >= 4)
343  missing_ok = PG_GETARG_BOOL(3);
344 
345  filename = convert_and_check_filename(filename_t);
346 
347  result = read_binary_file(filename, seek_offset,
348  bytes_to_read, missing_ok);
349  if (result)
350  PG_RETURN_BYTEA_P(result);
351  else
352  PG_RETURN_NULL();
353 }
static char * convert_and_check_filename(text *arg)
Definition: genfile.c:53
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:369
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:308
#define ERROR
Definition: elog.h:43
static bytea * read_binary_file(const char *filename, int64 seek_offset, int64 bytes_to_read, bool missing_ok)
Definition: genfile.c:105
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_NARGS()
Definition: fmgr.h:203
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
Definition: c.h:563
#define PG_GETARG_INT64(n)
Definition: fmgr.h:282
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ pg_read_binary_file_all()

Datum pg_read_binary_file_all ( PG_FUNCTION_ARGS  )

Definition at line 383 of file genfile.c.

References pg_read_binary_file().

384 {
385  return pg_read_binary_file(fcinfo);
386 }
Datum pg_read_binary_file(PG_FUNCTION_ARGS)
Definition: genfile.c:322

◆ pg_read_binary_file_off_len()

Datum pg_read_binary_file_off_len ( PG_FUNCTION_ARGS  )

Definition at line 377 of file genfile.c.

References pg_read_binary_file().

378 {
379  return pg_read_binary_file(fcinfo);
380 }
Datum pg_read_binary_file(PG_FUNCTION_ARGS)
Definition: genfile.c:322

◆ pg_read_file()

Datum pg_read_file ( PG_FUNCTION_ARGS  )

Definition at line 239 of file genfile.c.

References convert_and_check_filename(), ereport, errcode(), ERRCODE_INSUFFICIENT_PRIVILEGE, errhint(), errmsg(), ERROR, filename, PG_GETARG_BOOL, PG_GETARG_INT64, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_NULL, PG_RETURN_TEXT_P, read_text_file(), and superuser().

240 {
241  text *filename_t = PG_GETARG_TEXT_PP(0);
242  int64 seek_offset = 0;
243  int64 bytes_to_read = -1;
244  bool missing_ok = false;
245  char *filename;
246  text *result;
247 
248  if (!superuser())
249  ereport(ERROR,
251  errmsg("must be superuser to read files with adminpack 1.0"),
252  /* translator: %s is a SQL function name */
253  errhint("Consider using %s, which is part of core, instead.",
254  "pg_file_read()")));
255 
256  /* handle optional arguments */
257  if (PG_NARGS() >= 3)
258  {
259  seek_offset = PG_GETARG_INT64(1);
260  bytes_to_read = PG_GETARG_INT64(2);
261 
262  if (bytes_to_read < 0)
263  ereport(ERROR,
264  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
265  errmsg("requested length cannot be negative")));
266  }
267  if (PG_NARGS() >= 4)
268  missing_ok = PG_GETARG_BOOL(3);
269 
270  filename = convert_and_check_filename(filename_t);
271 
272  result = read_text_file(filename, seek_offset, bytes_to_read, missing_ok);
273  if (result)
274  PG_RETURN_TEXT_P(result);
275  else
276  PG_RETURN_NULL();
277 }
static char * convert_and_check_filename(text *arg)
Definition: genfile.c:53
int errhint(const char *fmt,...)
Definition: elog.c:1068
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:308
#define ERRCODE_INSUFFICIENT_PRIVILEGE
#define ERROR
Definition: elog.h:43
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:370
#define PG_NARGS()
Definition: fmgr.h:203
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
Definition: c.h:563
static text * read_text_file(const char *filename, int64 seek_offset, int64 bytes_to_read, bool missing_ok)
Definition: genfile.c:214
#define PG_GETARG_INT64(n)
Definition: fmgr.h:282
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ pg_read_file_all()

Datum pg_read_file_all ( PG_FUNCTION_ARGS  )

Definition at line 371 of file genfile.c.

References pg_read_file_v2().

372 {
373  return pg_read_file_v2(fcinfo);
374 }
Datum pg_read_file_v2(PG_FUNCTION_ARGS)
Definition: genfile.c:286

◆ pg_read_file_off_len()

Datum pg_read_file_off_len ( PG_FUNCTION_ARGS  )

Definition at line 365 of file genfile.c.

References pg_read_file_v2().

366 {
367  return pg_read_file_v2(fcinfo);
368 }
Datum pg_read_file_v2(PG_FUNCTION_ARGS)
Definition: genfile.c:286

◆ pg_read_file_v2()

Datum pg_read_file_v2 ( PG_FUNCTION_ARGS  )

Definition at line 286 of file genfile.c.

References convert_and_check_filename(), ereport, errcode(), errmsg(), ERROR, filename, PG_GETARG_BOOL, PG_GETARG_INT64, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_NULL, PG_RETURN_TEXT_P, and read_text_file().

Referenced by pg_read_file_all(), and pg_read_file_off_len().

287 {
288  text *filename_t = PG_GETARG_TEXT_PP(0);
289  int64 seek_offset = 0;
290  int64 bytes_to_read = -1;
291  bool missing_ok = false;
292  char *filename;
293  text *result;
294 
295  /* handle optional arguments */
296  if (PG_NARGS() >= 3)
297  {
298  seek_offset = PG_GETARG_INT64(1);
299  bytes_to_read = PG_GETARG_INT64(2);
300 
301  if (bytes_to_read < 0)
302  ereport(ERROR,
303  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
304  errmsg("requested length cannot be negative")));
305  }
306  if (PG_NARGS() >= 4)
307  missing_ok = PG_GETARG_BOOL(3);
308 
309  filename = convert_and_check_filename(filename_t);
310 
311  result = read_text_file(filename, seek_offset, bytes_to_read, missing_ok);
312  if (result)
313  PG_RETURN_TEXT_P(result);
314  else
315  PG_RETURN_NULL();
316 }
static char * convert_and_check_filename(text *arg)
Definition: genfile.c:53
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:308
#define ERROR
Definition: elog.h:43
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:370
#define PG_NARGS()
Definition: fmgr.h:203
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
Definition: c.h:563
static text * read_text_file(const char *filename, int64 seek_offset, int64 bytes_to_read, bool missing_ok)
Definition: genfile.c:214
#define PG_GETARG_INT64(n)
Definition: fmgr.h:282
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ pg_stat_file()

Datum pg_stat_file ( PG_FUNCTION_ARGS  )

Definition at line 392 of file genfile.c.

References BlessTupleDesc(), BoolGetDatum, convert_and_check_filename(), CreateTemplateTupleDesc(), ereport, errcode_for_file_access(), errmsg(), ERROR, filename, heap_form_tuple(), HeapTupleGetDatum, Int64GetDatum(), pfree(), PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_DATUM, PG_RETURN_NULL, S_ISDIR, stat::st_atime, stat::st_ctime, stat::st_mode, stat::st_mtime, stat::st_size, stat, time_t_to_timestamptz(), TimestampTzGetDatum, TupleDescInitEntry(), and values.

Referenced by pg_stat_file_1arg().

393 {
394  text *filename_t = PG_GETARG_TEXT_PP(0);
395  char *filename;
396  struct stat fst;
397  Datum values[6];
398  bool isnull[6];
399  HeapTuple tuple;
400  TupleDesc tupdesc;
401  bool missing_ok = false;
402 
403  /* check the optional argument */
404  if (PG_NARGS() == 2)
405  missing_ok = PG_GETARG_BOOL(1);
406 
407  filename = convert_and_check_filename(filename_t);
408 
409  if (stat(filename, &fst) < 0)
410  {
411  if (missing_ok && errno == ENOENT)
412  PG_RETURN_NULL();
413  else
414  ereport(ERROR,
416  errmsg("could not stat file \"%s\": %m", filename)));
417  }
418 
419  /*
420  * This record type had better match the output parameters declared for me
421  * in pg_proc.h.
422  */
423  tupdesc = CreateTemplateTupleDesc(6);
424  TupleDescInitEntry(tupdesc, (AttrNumber) 1,
425  "size", INT8OID, -1, 0);
426  TupleDescInitEntry(tupdesc, (AttrNumber) 2,
427  "access", TIMESTAMPTZOID, -1, 0);
428  TupleDescInitEntry(tupdesc, (AttrNumber) 3,
429  "modification", TIMESTAMPTZOID, -1, 0);
430  TupleDescInitEntry(tupdesc, (AttrNumber) 4,
431  "change", TIMESTAMPTZOID, -1, 0);
432  TupleDescInitEntry(tupdesc, (AttrNumber) 5,
433  "creation", TIMESTAMPTZOID, -1, 0);
434  TupleDescInitEntry(tupdesc, (AttrNumber) 6,
435  "isdir", BOOLOID, -1, 0);
436  BlessTupleDesc(tupdesc);
437 
438  memset(isnull, false, sizeof(isnull));
439 
440  values[0] = Int64GetDatum((int64) fst.st_size);
441  values[1] = TimestampTzGetDatum(time_t_to_timestamptz(fst.st_atime));
442  values[2] = TimestampTzGetDatum(time_t_to_timestamptz(fst.st_mtime));
443  /* Unix has file status change time, while Win32 has creation time */
444 #if !defined(WIN32) && !defined(__CYGWIN__)
445  values[3] = TimestampTzGetDatum(time_t_to_timestamptz(fst.st_ctime));
446  isnull[4] = true;
447 #else
448  isnull[3] = true;
449  values[4] = TimestampTzGetDatum(time_t_to_timestamptz(fst.st_ctime));
450 #endif
451  values[5] = BoolGetDatum(S_ISDIR(fst.st_mode));
452 
453  tuple = heap_form_tuple(tupdesc, values, isnull);
454 
455  pfree(filename);
456 
458 }
static char * convert_and_check_filename(text *arg)
Definition: genfile.c:53
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:44
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:308
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:43
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2052
int errcode_for_file_access(void)
Definition: elog.c:633
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1701
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:603
uintptr_t Datum
Definition: postgres.h:367
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:352
TimestampTz time_t_to_timestamptz(pg_time_t tm)
Definition: timestamp.c:1698
#define BoolGetDatum(X)
Definition: postgres.h:402
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_NARGS()
Definition: fmgr.h:203
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
#define S_ISDIR(m)
Definition: win32_port.h:316
static Datum values[MAXATTR]
Definition: bootstrap.c:165
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
Definition: c.h:563
int16 AttrNumber
Definition: attnum.h:21
#define PG_RETURN_NULL()
Definition: fmgr.h:344
#define stat
Definition: win32_port.h:275

◆ pg_stat_file_1arg()

Datum pg_stat_file_1arg ( PG_FUNCTION_ARGS  )

Definition at line 468 of file genfile.c.

References pg_stat_file().

469 {
470  return pg_stat_file(fcinfo);
471 }
Datum pg_stat_file(PG_FUNCTION_ARGS)
Definition: genfile.c:392

◆ read_binary_file()

static bytea* read_binary_file ( const char *  filename,
int64  seek_offset,
int64  bytes_to_read,
bool  missing_ok 
)
static

Definition at line 105 of file genfile.c.

References AllocateFile(), Assert, buf, StringInfoData::data, enlargeStringInfo(), ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, FreeFile(), fseeko, initStringInfo(), StringInfoData::len, MaxAllocSize, StringInfoData::maxlen, MIN_READ_SIZE, palloc(), PG_BINARY_R, SET_VARSIZE, VARDATA, and VARHDRSZ.

Referenced by pg_read_binary_file(), and read_text_file().

107 {
108  bytea *buf;
109  size_t nbytes = 0;
110  FILE *file;
111 
112  /* clamp request size to what we can actually deliver */
113  if (bytes_to_read > (int64) (MaxAllocSize - VARHDRSZ))
114  ereport(ERROR,
115  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
116  errmsg("requested length too large")));
117 
118  if ((file = AllocateFile(filename, PG_BINARY_R)) == NULL)
119  {
120  if (missing_ok && errno == ENOENT)
121  return NULL;
122  else
123  ereport(ERROR,
125  errmsg("could not open file \"%s\" for reading: %m",
126  filename)));
127  }
128 
129  if (fseeko(file, (off_t) seek_offset,
130  (seek_offset >= 0) ? SEEK_SET : SEEK_END) != 0)
131  ereport(ERROR,
133  errmsg("could not seek in file \"%s\": %m", filename)));
134 
135  if (bytes_to_read >= 0)
136  {
137  /* If passed explicit read size just do it */
138  buf = (bytea *) palloc((Size) bytes_to_read + VARHDRSZ);
139 
140  nbytes = fread(VARDATA(buf), 1, (size_t) bytes_to_read, file);
141  }
142  else
143  {
144  /* Negative read size, read rest of file */
145  StringInfoData sbuf;
146 
147  initStringInfo(&sbuf);
148  /* Leave room in the buffer for the varlena length word */
149  sbuf.len += VARHDRSZ;
150  Assert(sbuf.len < sbuf.maxlen);
151 
152  while (!(feof(file) || ferror(file)))
153  {
154  size_t rbytes;
155 
156  /* Minimum amount to read at a time */
157 #define MIN_READ_SIZE 4096
158 
159  /*
160  * If not at end of file, and sbuf.len is equal to
161  * MaxAllocSize - 1, then either the file is too large, or
162  * there is nothing left to read. Attempt to read one more
163  * byte to see if the end of file has been reached. If not,
164  * the file is too large; we'd rather give the error message
165  * for that ourselves.
166  */
167  if (sbuf.len == MaxAllocSize - 1)
168  {
169  char rbuf[1];
170 
171  if (fread(rbuf, 1, 1, file) != 0 || !feof(file))
172  ereport(ERROR,
173  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
174  errmsg("file length too large")));
175  else
176  break;
177  }
178 
179  /* OK, ensure that we can read at least MIN_READ_SIZE */
181 
182  /*
183  * stringinfo.c likes to allocate in powers of 2, so it's likely
184  * that much more space is available than we asked for. Use all
185  * of it, rather than making more fread calls than necessary.
186  */
187  rbytes = fread(sbuf.data + sbuf.len, 1,
188  (size_t) (sbuf.maxlen - sbuf.len - 1), file);
189  sbuf.len += rbytes;
190  nbytes += rbytes;
191  }
192 
193  /* Now we can commandeer the stringinfo's buffer as the result */
194  buf = (bytea *) sbuf.data;
195  }
196 
197  if (ferror(file))
198  ereport(ERROR,
200  errmsg("could not read file \"%s\": %m", filename)));
201 
202  SET_VARSIZE(buf, nbytes + VARHDRSZ);
203 
204  FreeFile(file);
205 
206  return buf;
207 }
#define VARDATA(PTR)
Definition: postgres.h:302
#define VARHDRSZ
Definition: c.h:569
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PG_BINARY_R
Definition: c.h:1215
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:68
int errcode_for_file_access(void)
Definition: elog.c:633
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2322
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283
#define MIN_READ_SIZE
#define MaxAllocSize
Definition: memutils.h:40
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define fseeko(stream, offset, origin)
Definition: win32_port.h:207
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
size_t Size
Definition: c.h:474
int FreeFile(FILE *file)
Definition: fd.c:2521
static char * filename
Definition: pg_dumpall.c:91
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
Definition: c.h:563
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329

◆ read_text_file()

static text* read_text_file ( const char *  filename,
int64  seek_offset,
int64  bytes_to_read,
bool  missing_ok 
)
static

Definition at line 214 of file genfile.c.

References buf, pg_verifymbstr(), read_binary_file(), VARDATA, VARHDRSZ, and VARSIZE.

Referenced by pg_read_file(), and pg_read_file_v2().

216 {
217  bytea *buf;
218 
219  buf = read_binary_file(filename, seek_offset, bytes_to_read, missing_ok);
220 
221  if (buf != NULL)
222  {
223  /* Make sure the input is valid */
224  pg_verifymbstr(VARDATA(buf), VARSIZE(buf) - VARHDRSZ, false);
225 
226  /* OK, we can cast it to text safely */
227  return (text *) buf;
228  }
229  else
230  return NULL;
231 }
#define VARDATA(PTR)
Definition: postgres.h:302
#define VARSIZE(PTR)
Definition: postgres.h:303
#define VARHDRSZ
Definition: c.h:569
static bytea * read_binary_file(const char *filename, int64 seek_offset, int64 bytes_to_read, bool missing_ok)
Definition: genfile.c:105
static char * buf
Definition: pg_test_fsync.c:68
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: mbutils.c:1446
static char * filename
Definition: pg_dumpall.c:91
Definition: c.h:563