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(), 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(), ROLE_PG_READ_SERVER_FILES))
66  return filename;
67 
68  /*
69  * User isn't a member of the pg_read_server_files role, so check if it's
70  * allowable
71  */
72  if (is_absolute_path(filename))
73  {
74  /* Disallow '/a/b/data/..' */
75  if (path_contains_parent_reference(filename))
76  ereport(ERROR,
77  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
78  errmsg("reference to parent directory (\"..\") not allowed")));
79 
80  /*
81  * Allow absolute paths if within DataDir or Log_directory, even
82  * though Log_directory might be outside DataDir.
83  */
84  if (!path_is_prefix_of_path(DataDir, filename) &&
87  ereport(ERROR,
88  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
89  errmsg("absolute path not allowed")));
90  }
91  else if (!path_is_relative_and_below_cwd(filename))
92  ereport(ERROR,
93  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
94  errmsg("path must be in or below the current directory")));
95 
96  return filename;
97 }
char * Log_directory
Definition: syslogger.c:74
Oid GetUserId(void)
Definition: miscinit.c:495
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:698
bool path_contains_parent_reference(const char *path)
Definition: path.c:376
#define ERROR
Definition: elog.h:46
#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:157
bool is_member_of_role(Oid member, Oid role)
Definition: acl.c:4869
char * text_to_cstring(const text *t)
Definition: varlena.c:222
static char * filename
Definition: pg_dumpall.c:92
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * DataDir
Definition: globals.c:65

◆ pg_ls_archive_statusdir()

Datum pg_ls_archive_statusdir ( PG_FUNCTION_ARGS  )

Definition at line 719 of file genfile.c.

References pg_ls_dir_files(), and XLOGDIR.

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

◆ pg_ls_dir()

Datum pg_ls_dir ( PG_FUNCTION_ARGS  )

Definition at line 479 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().

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

◆ pg_ls_dir_1arg()

Datum pg_ls_dir_1arg ( PG_FUNCTION_ARGS  )

Definition at line 564 of file genfile.c.

References pg_ls_dir().

565 {
566  return pg_ls_dir(fcinfo);
567 }
Datum pg_ls_dir(PG_FUNCTION_ARGS)
Definition: genfile.c:479

◆ pg_ls_dir_files()

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

Definition at line 576 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().

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

◆ pg_ls_logdir()

Datum pg_ls_logdir ( PG_FUNCTION_ARGS  )

Definition at line 665 of file genfile.c.

References Log_directory, and pg_ls_dir_files().

666 {
667  return pg_ls_dir_files(fcinfo, Log_directory, false);
668 }
char * Log_directory
Definition: syslogger.c:74
static Datum pg_ls_dir_files(FunctionCallInfo fcinfo, const char *dir, bool missing_ok)
Definition: genfile.c:576

◆ pg_ls_tmpdir()

static Datum pg_ls_tmpdir ( FunctionCallInfo  fcinfo,
Oid  tblspc 
)
static

Definition at line 681 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().

682 {
683  char path[MAXPGPATH];
684 
686  ereport(ERROR,
687  (errcode(ERRCODE_UNDEFINED_OBJECT),
688  errmsg("tablespace with OID %u does not exist",
689  tblspc)));
690 
691  TempTablespacePath(path, tblspc);
692  return pg_ls_dir_files(fcinfo, path, true);
693 }
int errcode(int sqlerrcode)
Definition: elog.c:698
void TempTablespacePath(char *path, Oid tablespace)
Definition: fd.c:1760
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:184
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define MAXPGPATH
static Datum pg_ls_dir_files(FunctionCallInfo fcinfo, const char *dir, bool missing_ok)
Definition: genfile.c:576
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ pg_ls_tmpdir_1arg()

Datum pg_ls_tmpdir_1arg ( PG_FUNCTION_ARGS  )

Definition at line 710 of file genfile.c.

References PG_GETARG_OID, and pg_ls_tmpdir().

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

◆ pg_ls_tmpdir_noargs()

Datum pg_ls_tmpdir_noargs ( PG_FUNCTION_ARGS  )

Definition at line 700 of file genfile.c.

References pg_ls_tmpdir().

701 {
702  return pg_ls_tmpdir(fcinfo, DEFAULTTABLESPACE_OID);
703 }
static Datum pg_ls_tmpdir(FunctionCallInfo fcinfo, Oid tblspc)
Definition: genfile.c:681

◆ pg_ls_waldir()

Datum pg_ls_waldir ( PG_FUNCTION_ARGS  )

Definition at line 672 of file genfile.c.

References pg_ls_dir_files(), and XLOGDIR.

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

◆ pg_read_binary_file()

Datum pg_read_binary_file ( PG_FUNCTION_ARGS  )

Definition at line 324 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().

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

◆ pg_read_binary_file_all()

Datum pg_read_binary_file_all ( PG_FUNCTION_ARGS  )

Definition at line 385 of file genfile.c.

References pg_read_binary_file().

386 {
387  return pg_read_binary_file(fcinfo);
388 }
Datum pg_read_binary_file(PG_FUNCTION_ARGS)
Definition: genfile.c:324

◆ pg_read_binary_file_off_len()

Datum pg_read_binary_file_off_len ( PG_FUNCTION_ARGS  )

Definition at line 379 of file genfile.c.

References pg_read_binary_file().

380 {
381  return pg_read_binary_file(fcinfo);
382 }
Datum pg_read_binary_file(PG_FUNCTION_ARGS)
Definition: genfile.c:324

◆ pg_read_file()

Datum pg_read_file ( PG_FUNCTION_ARGS  )

Definition at line 241 of file genfile.c.

References convert_and_check_filename(), ereport, errcode(), 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().

242 {
243  text *filename_t = PG_GETARG_TEXT_PP(0);
244  int64 seek_offset = 0;
245  int64 bytes_to_read = -1;
246  bool missing_ok = false;
247  char *filename;
248  text *result;
249 
250  if (!superuser())
251  ereport(ERROR,
252  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
253  errmsg("must be superuser to read files with adminpack 1.0"),
254  /* translator: %s is a SQL function name */
255  errhint("Consider using %s, which is part of core, instead.",
256  "pg_read_file()")));
257 
258  /* handle optional arguments */
259  if (PG_NARGS() >= 3)
260  {
261  seek_offset = PG_GETARG_INT64(1);
262  bytes_to_read = PG_GETARG_INT64(2);
263 
264  if (bytes_to_read < 0)
265  ereport(ERROR,
266  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
267  errmsg("requested length cannot be negative")));
268  }
269  if (PG_NARGS() >= 4)
270  missing_ok = PG_GETARG_BOOL(3);
271 
272  filename = convert_and_check_filename(filename_t);
273 
274  result = read_text_file(filename, seek_offset, bytes_to_read, missing_ok);
275  if (result)
276  PG_RETURN_TEXT_P(result);
277  else
278  PG_RETURN_NULL();
279 }
static char * convert_and_check_filename(text *arg)
Definition: genfile.c:53
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
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:309
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
#define PG_NARGS()
Definition: fmgr.h:203
static char * filename
Definition: pg_dumpall.c:92
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: c.h:621
static text * read_text_file(const char *filename, int64 seek_offset, int64 bytes_to_read, bool missing_ok)
Definition: genfile.c:216
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283
#define PG_RETURN_NULL()
Definition: fmgr.h:345

◆ pg_read_file_all()

Datum pg_read_file_all ( PG_FUNCTION_ARGS  )

Definition at line 373 of file genfile.c.

References pg_read_file_v2().

374 {
375  return pg_read_file_v2(fcinfo);
376 }
Datum pg_read_file_v2(PG_FUNCTION_ARGS)
Definition: genfile.c:288

◆ pg_read_file_off_len()

Datum pg_read_file_off_len ( PG_FUNCTION_ARGS  )

Definition at line 367 of file genfile.c.

References pg_read_file_v2().

368 {
369  return pg_read_file_v2(fcinfo);
370 }
Datum pg_read_file_v2(PG_FUNCTION_ARGS)
Definition: genfile.c:288

◆ pg_read_file_v2()

Datum pg_read_file_v2 ( PG_FUNCTION_ARGS  )

Definition at line 288 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().

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

◆ pg_stat_file()

Datum pg_stat_file ( PG_FUNCTION_ARGS  )

Definition at line 394 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().

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

◆ pg_stat_file_1arg()

Datum pg_stat_file_1arg ( PG_FUNCTION_ARGS  )

Definition at line 470 of file genfile.c.

References pg_stat_file().

471 {
472  return pg_stat_file(fcinfo);
473 }
Datum pg_stat_file(PG_FUNCTION_ARGS)
Definition: genfile.c:394

◆ 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 108 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().

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

◆ 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 216 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().

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