Skip to content

Commit e03c6d9

Browse files
committed
Fix pg_file_write() error handling.
Detect fclose() failures; given "ln -s /dev/full $PGDATA/devfull", "pg_file_write('devfull', 'x', true)" now fails as it should. Don't leak a stream when fwrite() fails. Remove a born-ineffective test that aimed to skip zero-length writes. Back-patch to 9.2 (all supported versions).
1 parent f6cfc14 commit e03c6d9

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

contrib/adminpack/adminpack.c

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -141,27 +141,22 @@ pg_file_write(PG_FUNCTION_ARGS)
141141
(ERRCODE_DUPLICATE_FILE,
142142
errmsg("file \"%s\" exists", filename)));
143143

144-
f = fopen(filename, "wb");
144+
f = AllocateFile(filename, "wb");
145145
}
146146
else
147-
f = fopen(filename, "ab");
147+
f = AllocateFile(filename, "ab");
148148

149149
if (!f)
150150
ereport(ERROR,
151151
(errcode_for_file_access(),
152152
errmsg("could not open file \"%s\" for writing: %m",
153153
filename)));
154154

155-
if (VARSIZE(data) != 0)
156-
{
157-
count = fwrite(VARDATA(data), 1, VARSIZE(data) - VARHDRSZ, f);
158-
159-
if (count != VARSIZE(data) - VARHDRSZ)
160-
ereport(ERROR,
161-
(errcode_for_file_access(),
162-
errmsg("could not write file \"%s\": %m", filename)));
163-
}
164-
fclose(f);
155+
count = fwrite(VARDATA(data), 1, VARSIZE(data) - VARHDRSZ, f);
156+
if (count != VARSIZE(data) - VARHDRSZ || FreeFile(f))
157+
ereport(ERROR,
158+
(errcode_for_file_access(),
159+
errmsg("could not write file \"%s\": %m", filename)));
165160

166161
PG_RETURN_INT64(count);
167162
}

0 commit comments

Comments
 (0)