1 /*-------------------------------------------------------------------------
2  *
3  * adminpack.c
4  *
5  *
6  * Copyright (c) 2002-2016, 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 
17 #include <sys/file.h>
18 #include <sys/stat.h>
19 #include <unistd.h>
20 
21 #include "catalog/pg_type.h"
22 #include "funcapi.h"
23 #include "miscadmin.h"
24 #include "postmaster/syslogger.h"
25 #include "storage/fd.h"
26 #include "utils/builtins.h"
27 #include "utils/datetime.h"
28 
29 
30 #ifdef WIN32
31 
32 #ifdef rename
33 #undef rename
34 #endif
35 
36 #ifdef unlink
37 #undef unlink
38 #endif
39 #endif
40 
41 PG_MODULE_MAGIC;
42 
43 PG_FUNCTION_INFO_V1(pg_file_write);
44 PG_FUNCTION_INFO_V1(pg_file_rename);
45 PG_FUNCTION_INFO_V1(pg_file_unlink);
46 PG_FUNCTION_INFO_V1(pg_logdir_ls);
47 
48 
49 /*-----------------------
50  * some helper functions
51  */
52 
53 /*
54  * Convert a "text" filename argument to C string, and check it's allowable.
55  *
56  * Filename may be absolute or relative to the DataDir, but we only allow
57  * absolute paths that match DataDir or Log_directory.
58  */
59 static char *
convert_and_check_filename(text * arg,bool logAllowed)60 convert_and_check_filename(text *arg, bool logAllowed)
61 {
62 	char	   *filename = text_to_cstring(arg);
63 
64 	canonicalize_path(filename);	/* filename can change length here */
65 
66 	if (is_absolute_path(filename))
67 	{
68 		/* Disallow '/a/b/data/..' */
69 		if (path_contains_parent_reference(filename))
70 			ereport(ERROR,
71 					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
72 			(errmsg("reference to parent directory (\"..\") not allowed"))));
73 
74 		/*
75 		 * Allow absolute paths if within DataDir or Log_directory, even
76 		 * though Log_directory might be outside DataDir.
77 		 */
78 		if (!path_is_prefix_of_path(DataDir, filename) &&
79 			(!logAllowed || !is_absolute_path(Log_directory) ||
80 			 !path_is_prefix_of_path(Log_directory, filename)))
81 			ereport(ERROR,
82 					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
83 					 (errmsg("absolute path not allowed"))));
84 	}
85 	else if (!path_is_relative_and_below_cwd(filename))
86 		ereport(ERROR,
87 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
88 				 (errmsg("path must be in or below the current directory"))));
89 
90 	return filename;
91 }
92 
93 
94 /*
95  * check for superuser, bark if not.
96  */
97 static void
requireSuperuser(void)98 requireSuperuser(void)
99 {
100 	if (!superuser())
101 		ereport(ERROR,
102 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
103 			  (errmsg("only superuser may access generic file functions"))));
104 }
105 
106 
107 
108 /* ------------------------------------
109  * generic file handling functions
110  */
111 
112 Datum
pg_file_write(PG_FUNCTION_ARGS)113 pg_file_write(PG_FUNCTION_ARGS)
114 {
115 	FILE	   *f;
116 	char	   *filename;
117 	text	   *data;
118 	int64		count = 0;
119 
120 	requireSuperuser();
121 
122 	filename = convert_and_check_filename(PG_GETARG_TEXT_P(0), false);
123 	data = PG_GETARG_TEXT_P(1);
124 
125 	if (!PG_GETARG_BOOL(2))
126 	{
127 		struct stat fst;
128 
129 		if (stat(filename, &fst) >= 0)
130 			ereport(ERROR,
131 					(errcode(ERRCODE_DUPLICATE_FILE),
132 					 errmsg("file \"%s\" exists", filename)));
133 
134 		f = AllocateFile(filename, "wb");
135 	}
136 	else
137 		f = AllocateFile(filename, "ab");
138 
139 	if (!f)
140 		ereport(ERROR,
141 				(errcode_for_file_access(),
142 				 errmsg("could not open file \"%s\" for writing: %m",
143 						filename)));
144 
145 	count = fwrite(VARDATA(data), 1, VARSIZE(data) - VARHDRSZ, f);
146 	if (count != VARSIZE(data) - VARHDRSZ || FreeFile(f))
147 		ereport(ERROR,
148 				(errcode_for_file_access(),
149 				 errmsg("could not write file \"%s\": %m", filename)));
150 
151 	PG_RETURN_INT64(count);
152 }
153 
154 
155 Datum
pg_file_rename(PG_FUNCTION_ARGS)156 pg_file_rename(PG_FUNCTION_ARGS)
157 {
158 	char	   *fn1,
159 			   *fn2,
160 			   *fn3;
161 	int			rc;
162 
163 	requireSuperuser();
164 
165 	if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
166 		PG_RETURN_NULL();
167 
168 	fn1 = convert_and_check_filename(PG_GETARG_TEXT_P(0), false);
169 	fn2 = convert_and_check_filename(PG_GETARG_TEXT_P(1), false);
170 	if (PG_ARGISNULL(2))
171 		fn3 = NULL;
172 	else
173 		fn3 = convert_and_check_filename(PG_GETARG_TEXT_P(2), false);
174 
175 	if (access(fn1, W_OK) < 0)
176 	{
177 		ereport(WARNING,
178 				(errcode_for_file_access(),
179 				 errmsg("file \"%s\" is not accessible: %m", fn1)));
180 
181 		PG_RETURN_BOOL(false);
182 	}
183 
184 	if (fn3 && access(fn2, W_OK) < 0)
185 	{
186 		ereport(WARNING,
187 				(errcode_for_file_access(),
188 				 errmsg("file \"%s\" is not accessible: %m", fn2)));
189 
190 		PG_RETURN_BOOL(false);
191 	}
192 
193 	rc = access(fn3 ? fn3 : fn2, W_OK);
194 	if (rc >= 0 || errno != ENOENT)
195 	{
196 		ereport(ERROR,
197 				(errcode(ERRCODE_DUPLICATE_FILE),
198 				 errmsg("cannot rename to target file \"%s\"",
199 						fn3 ? fn3 : fn2)));
200 	}
201 
202 	if (fn3)
203 	{
204 		if (rename(fn2, fn3) != 0)
205 		{
206 			ereport(ERROR,
207 					(errcode_for_file_access(),
208 					 errmsg("could not rename \"%s\" to \"%s\": %m",
209 							fn2, fn3)));
210 		}
211 		if (rename(fn1, fn2) != 0)
212 		{
213 			ereport(WARNING,
214 					(errcode_for_file_access(),
215 					 errmsg("could not rename \"%s\" to \"%s\": %m",
216 							fn1, fn2)));
217 
218 			if (rename(fn3, fn2) != 0)
219 			{
220 				ereport(ERROR,
221 						(errcode_for_file_access(),
222 						 errmsg("could not rename \"%s\" back to \"%s\": %m",
223 								fn3, fn2)));
224 			}
225 			else
226 			{
227 				ereport(ERROR,
228 						(errcode(ERRCODE_UNDEFINED_FILE),
229 						 errmsg("renaming \"%s\" to \"%s\" was reverted",
230 								fn2, fn3)));
231 			}
232 		}
233 	}
234 	else if (rename(fn1, fn2) != 0)
235 	{
236 		ereport(ERROR,
237 				(errcode_for_file_access(),
238 				 errmsg("could not rename \"%s\" to \"%s\": %m", fn1, fn2)));
239 	}
240 
241 	PG_RETURN_BOOL(true);
242 }
243 
244 
245 Datum
pg_file_unlink(PG_FUNCTION_ARGS)246 pg_file_unlink(PG_FUNCTION_ARGS)
247 {
248 	char	   *filename;
249 
250 	requireSuperuser();
251 
252 	filename = convert_and_check_filename(PG_GETARG_TEXT_P(0), false);
253 
254 	if (access(filename, W_OK) < 0)
255 	{
256 		if (errno == ENOENT)
257 			PG_RETURN_BOOL(false);
258 		else
259 			ereport(ERROR,
260 					(errcode_for_file_access(),
261 					 errmsg("file \"%s\" is not accessible: %m", filename)));
262 	}
263 
264 	if (unlink(filename) < 0)
265 	{
266 		ereport(WARNING,
267 				(errcode_for_file_access(),
268 				 errmsg("could not unlink file \"%s\": %m", filename)));
269 
270 		PG_RETURN_BOOL(false);
271 	}
272 	PG_RETURN_BOOL(true);
273 }
274 
275 
276 Datum
pg_logdir_ls(PG_FUNCTION_ARGS)277 pg_logdir_ls(PG_FUNCTION_ARGS)
278 {
279 	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
280 	bool		randomAccess;
281 	TupleDesc	tupdesc;
282 	Tuplestorestate *tupstore;
283 	AttInMetadata *attinmeta;
284 	DIR		   *dirdesc;
285 	struct dirent *de;
286 	MemoryContext oldcontext;
287 
288 	if (!superuser())
289 		ereport(ERROR,
290 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
291 				 (errmsg("only superuser can list the log directory"))));
292 
293 	if (strcmp(Log_filename, "postgresql-%Y-%m-%d_%H%M%S.log") != 0)
294 		ereport(ERROR,
295 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
296 				 errmsg("the log_filename parameter must equal 'postgresql-%%Y-%%m-%%d_%%H%%M%%S.log'")));
297 
298 	/* check to see if caller supports us returning a tuplestore */
299 	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
300 		ereport(ERROR,
301 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
302 				 errmsg("set-valued function called in context that cannot accept a set")));
303 	if (!(rsinfo->allowedModes & SFRM_Materialize))
304 		ereport(ERROR,
305 				(errcode(ERRCODE_SYNTAX_ERROR),
306 				 errmsg("materialize mode required, but it is not allowed in this context")));
307 
308 	/* The tupdesc and tuplestore must be created in ecxt_per_query_memory */
309 	oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
310 
311 	tupdesc = CreateTemplateTupleDesc(2, false);
312 	TupleDescInitEntry(tupdesc, (AttrNumber) 1, "starttime",
313 					   TIMESTAMPOID, -1, 0);
314 	TupleDescInitEntry(tupdesc, (AttrNumber) 2, "filename",
315 					   TEXTOID, -1, 0);
316 
317 	randomAccess = (rsinfo->allowedModes & SFRM_Materialize_Random) != 0;
318 	tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
319 	rsinfo->returnMode = SFRM_Materialize;
320 	rsinfo->setResult = tupstore;
321 	rsinfo->setDesc = tupdesc;
322 
323 	MemoryContextSwitchTo(oldcontext);
324 
325 	attinmeta = TupleDescGetAttInMetadata(tupdesc);
326 
327 	dirdesc = AllocateDir(Log_directory);
328 	while ((de = ReadDir(dirdesc, Log_directory)) != NULL)
329 	{
330 		char	   *values[2];
331 		HeapTuple	tuple;
332 		char		timestampbuf[32];
333 		char	   *field[MAXDATEFIELDS];
334 		char		lowstr[MAXDATELEN + 1];
335 		int			dtype;
336 		int			nf,
337 					ftype[MAXDATEFIELDS];
338 		fsec_t		fsec;
339 		int			tz = 0;
340 		struct pg_tm date;
341 
342 		/*
343 		 * Default format: postgresql-YYYY-MM-DD_HHMMSS.log
344 		 */
345 		if (strlen(de->d_name) != 32
346 			|| strncmp(de->d_name, "postgresql-", 11) != 0
347 			|| de->d_name[21] != '_'
348 			|| strcmp(de->d_name + 28, ".log") != 0)
349 			continue;
350 
351 		/* extract timestamp portion of filename */
352 		strcpy(timestampbuf, de->d_name + 11);
353 		timestampbuf[17] = '\0';
354 
355 		/* parse and decode expected timestamp to verify it's OK format */
356 		if (ParseDateTime(timestampbuf, lowstr, MAXDATELEN, field, ftype, MAXDATEFIELDS, &nf))
357 			continue;
358 
359 		if (DecodeDateTime(field, ftype, nf, &dtype, &date, &fsec, &tz))
360 			continue;
361 
362 		/* Seems the timestamp is OK; prepare and return tuple */
363 
364 		values[0] = timestampbuf;
365 		values[1] = psprintf("%s/%s", Log_directory, de->d_name);
366 
367 		tuple = BuildTupleFromCStrings(attinmeta, values);
368 
369 		tuplestore_puttuple(tupstore, tuple);
370 	}
371 
372 	FreeDir(dirdesc);
373 	return (Datum) 0;
374 }
375