Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * streamutil.c - utility functions for pg_basebackup, pg_receivewal and
4 : : * pg_recvlogical
5 : : *
6 : : * Author: Magnus Hagander <magnus@hagander.net>
7 : : *
8 : : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
9 : : *
10 : : * IDENTIFICATION
11 : : * src/bin/pg_basebackup/streamutil.c
12 : : *-------------------------------------------------------------------------
13 : : */
14 : :
15 : : #include "postgres_fe.h"
16 : :
17 : : #include <sys/time.h>
18 : : #include <unistd.h>
19 : :
20 : : #include "access/xlog_internal.h"
21 : : #include "common/connect.h"
22 : : #include "common/file_perm.h"
23 : : #include "common/logging.h"
24 : : #include "common/string.h"
25 : : #include "datatype/timestamp.h"
26 : : #include "port/pg_bswap.h"
27 : : #include "pqexpbuffer.h"
28 : : #include "streamutil.h"
29 : :
30 : : #define ERRCODE_DUPLICATE_OBJECT "42710"
31 : :
32 : : int WalSegSz;
33 : :
34 : : static bool RetrieveDataDirCreatePerm(PGconn *conn);
35 : :
36 : : /* SHOW command for replication connection was introduced in version 10 */
37 : : #define MINIMUM_VERSION_FOR_SHOW_CMD 100000
38 : :
39 : : /*
40 : : * Group access is supported from version 11.
41 : : */
42 : : #define MINIMUM_VERSION_FOR_GROUP_ACCESS 110000
43 : :
44 : : const char *progname;
45 : : char *connection_string = NULL;
46 : : char *dbhost = NULL;
47 : : char *dbuser = NULL;
48 : : char *dbport = NULL;
49 : : char *dbname = NULL;
50 : : int dbgetpassword = 0; /* 0=auto, -1=never, 1=always */
51 : : static char *password = NULL;
52 : : PGconn *conn = NULL;
53 : :
54 : : /*
55 : : * Connect to the server. Returns a valid PGconn pointer if connected,
56 : : * or NULL on non-permanent error. On permanent error, the function will
57 : : * call exit(1) directly.
58 : : */
59 : : PGconn *
5064 magnus@hagander.net 60 :CBC 343 : GetConnection(void)
61 : : {
62 : : PGconn *tmpconn;
4576 heikki.linnakangas@i 63 : 343 : int argcount = 7; /* dbname, replication, fallback_app_name,
64 : : * host, user, port, password */
65 : : int i;
66 : : const char **keywords;
67 : : const char **values;
68 : : const char *tmpparam;
69 : : bool need_password;
70 : 343 : PQconninfoOption *conn_opts = NULL;
71 : : PQconninfoOption *conn_opt;
72 : 343 : char *err_msg = NULL;
73 : :
74 : : /*
75 : : * pg_recvlogical uses dbname only; others use connection_string only.
76 : : * (Note: both variables will be NULL if there's no command line options.)
77 : : */
3316 noah@leadboat.com 78 [ + + - + ]: 343 : Assert(dbname == NULL || connection_string == NULL);
79 : :
80 : : /*
81 : : * Merge the connection info inputs given in form of connection string,
82 : : * options and default values (dbname=replication, replication=true, etc.)
83 : : */
4576 heikki.linnakangas@i 84 : 343 : i = 0;
85 [ + + ]: 343 : if (connection_string)
86 : : {
87 : 4 : conn_opts = PQconninfoParse(connection_string, &err_msg);
88 [ - + ]: 4 : if (conn_opts == NULL)
1247 tgl@sss.pgh.pa.us 89 :UBC 0 : pg_fatal("%s", err_msg);
90 : :
4576 heikki.linnakangas@i 91 [ + + ]:CBC 208 : for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
92 : : {
716 dgustafsson@postgres 93 [ + + + - ]: 204 : if (conn_opt->val != NULL && conn_opt->val[0] != '\0')
4576 heikki.linnakangas@i 94 : 8 : argcount++;
95 : : }
96 : :
97 : 4 : keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
98 : 4 : values = pg_malloc0((argcount + 1) * sizeof(*values));
99 : :
100 : : /*
101 : : * Set dbname here already, so it can be overridden by a dbname in the
102 : : * connection string.
103 : : */
716 dgustafsson@postgres 104 : 4 : keywords[i] = "dbname";
105 : 4 : values[i] = "replication";
106 : 4 : i++;
107 : :
4576 heikki.linnakangas@i 108 [ + + ]: 208 : for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
109 : : {
716 dgustafsson@postgres 110 [ + + + - ]: 204 : if (conn_opt->val != NULL && conn_opt->val[0] != '\0')
111 : : {
4576 heikki.linnakangas@i 112 : 8 : keywords[i] = conn_opt->keyword;
113 : 8 : values[i] = conn_opt->val;
114 : 8 : i++;
115 : : }
116 : : }
117 : : }
118 : : else
119 : : {
120 : 339 : keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
121 : 339 : values = pg_malloc0((argcount + 1) * sizeof(*values));
716 dgustafsson@postgres 122 : 339 : keywords[i] = "dbname";
306 tgl@sss.pgh.pa.us 123 [ + + ]: 339 : values[i] = (dbname == NULL) ? "replication" : dbname;
716 dgustafsson@postgres 124 : 339 : i++;
125 : : }
126 : :
4576 heikki.linnakangas@i 127 : 343 : keywords[i] = "replication";
306 tgl@sss.pgh.pa.us 128 [ + + ]: 343 : values[i] = (dbname == NULL) ? "true" : "database";
4576 heikki.linnakangas@i 129 : 343 : i++;
130 : 343 : keywords[i] = "fallback_application_name";
131 : 343 : values[i] = progname;
132 : 343 : i++;
133 : :
5064 magnus@hagander.net 134 [ + + ]: 343 : if (dbhost)
135 : : {
136 : 129 : keywords[i] = "host";
137 : 129 : values[i] = dbhost;
138 : 129 : i++;
139 : : }
140 [ + + ]: 343 : if (dbuser)
141 : : {
142 : 7 : keywords[i] = "user";
143 : 7 : values[i] = dbuser;
144 : 7 : i++;
145 : : }
146 [ + + ]: 343 : if (dbport)
147 : : {
148 : 129 : keywords[i] = "port";
149 : 129 : values[i] = dbport;
150 : 129 : i++;
151 : : }
152 : :
153 : : /* If -W was given, force prompt for password, but only the first time */
1829 tgl@sss.pgh.pa.us 154 [ - + - - ]: 343 : need_password = (dbgetpassword == 1 && !password);
155 : :
156 : : do
157 : : {
158 : : /* Get a new password if appropriate */
4313 159 [ - + ]: 343 : if (need_password)
160 : : {
1178 peter@eisentraut.org 161 :UBC 0 : free(password);
1829 tgl@sss.pgh.pa.us 162 : 0 : password = simple_prompt("Password: ", false);
4313 163 : 0 : need_password = false;
164 : : }
165 : :
166 : : /* Use (or reuse, on a subsequent connection) password if we have it */
1829 tgl@sss.pgh.pa.us 167 [ - + ]:CBC 343 : if (password)
168 : : {
4576 heikki.linnakangas@i 169 :UBC 0 : keywords[i] = "password";
3294 tgl@sss.pgh.pa.us 170 : 0 : values[i] = password;
171 : : }
172 : : else
173 : : {
4313 tgl@sss.pgh.pa.us 174 :CBC 343 : keywords[i] = NULL;
175 : 343 : values[i] = NULL;
176 : : }
177 : :
178 : : /*
179 : : * Only expand dbname when we did not already parse the argument as a
180 : : * connection string ourselves.
181 : : */
716 dgustafsson@postgres 182 : 343 : tmpconn = PQconnectdbParams(keywords, values, !connection_string);
183 : :
184 : : /*
185 : : * If there is too little memory even to allocate the PGconn object
186 : : * and PQconnectdbParams returns NULL, we call exit(1) directly.
187 : : */
4804 magnus@hagander.net 188 [ - + ]: 343 : if (!tmpconn)
1247 tgl@sss.pgh.pa.us 189 :UBC 0 : pg_fatal("could not connect to server");
190 : :
191 : : /* If we need a password and -w wasn't given, loop back and get one */
5064 magnus@hagander.net 192 [ + + - + ]:CBC 345 : if (PQstatus(tmpconn) == CONNECTION_BAD &&
193 : 2 : PQconnectionNeedsPassword(tmpconn) &&
5064 magnus@hagander.net 194 [ # # ]:UBC 0 : dbgetpassword != -1)
195 : : {
4804 196 : 0 : PQfinish(tmpconn);
4313 tgl@sss.pgh.pa.us 197 : 0 : need_password = true;
198 : : }
199 : : }
4307 peter_e@gmx.net 200 [ - + ]:CBC 343 : while (need_password);
201 : :
4313 tgl@sss.pgh.pa.us 202 [ + + ]: 343 : if (PQstatus(tmpconn) != CONNECTION_OK)
203 : : {
1764 peter@eisentraut.org 204 : 2 : pg_log_error("%s", PQerrorMessage(tmpconn));
4313 tgl@sss.pgh.pa.us 205 : 2 : PQfinish(tmpconn);
5064 magnus@hagander.net 206 : 2 : free(values);
207 : 2 : free(keywords);
1161 peter@eisentraut.org 208 : 2 : PQconninfoFree(conn_opts);
4313 tgl@sss.pgh.pa.us 209 : 2 : return NULL;
210 : : }
211 : :
212 : : /* Connection ok! */
213 : 341 : free(values);
214 : 341 : free(keywords);
1161 peter@eisentraut.org 215 : 341 : PQconninfoFree(conn_opts);
216 : :
217 : : /*
218 : : * Set always-secure search path, so malicious users can't get control.
219 : : * The capacity to run normal SQL queries was added in PostgreSQL 10, so
220 : : * the search path cannot be changed (by us or attackers) on earlier
221 : : * versions.
222 : : */
2691 noah@leadboat.com 223 [ + + + - ]: 341 : if (dbname != NULL && PQserverVersion(tmpconn) >= 100000)
224 : : {
225 : : PGresult *res;
226 : :
2749 227 : 10 : res = PQexec(tmpconn, ALWAYS_SECURE_SEARCH_PATH_SQL);
228 [ - + ]: 10 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
229 : : {
477 peter@eisentraut.org 230 :UBC 0 : pg_log_error("could not clear \"search_path\": %s",
231 : : PQerrorMessage(tmpconn));
2749 noah@leadboat.com 232 : 0 : PQclear(res);
233 : 0 : PQfinish(tmpconn);
234 : 0 : exit(1);
235 : : }
2749 noah@leadboat.com 236 :CBC 10 : PQclear(res);
237 : : }
238 : :
239 : : /*
240 : : * Ensure we have the same value of integer_datetimes (now always "on") as
241 : : * the server we are connecting to.
242 : : */
4313 tgl@sss.pgh.pa.us 243 : 341 : tmpparam = PQparameterStatus(tmpconn, "integer_datetimes");
244 [ - + ]: 341 : if (!tmpparam)
245 : : {
477 peter@eisentraut.org 246 :UBC 0 : pg_log_error("could not determine server setting for \"integer_datetimes\"");
4313 tgl@sss.pgh.pa.us 247 : 0 : PQfinish(tmpconn);
248 : 0 : exit(1);
249 : : }
250 : :
4313 tgl@sss.pgh.pa.us 251 [ - + ]:CBC 341 : if (strcmp(tmpparam, "on") != 0)
252 : : {
477 peter@eisentraut.org 253 :UBC 0 : pg_log_error("\"integer_datetimes\" compile flag does not match server");
4313 tgl@sss.pgh.pa.us 254 : 0 : PQfinish(tmpconn);
255 : 0 : exit(1);
256 : : }
257 : :
258 : : /*
259 : : * Retrieve the source data directory mode and use it to construct a umask
260 : : * for creating directories and files.
261 : : */
2709 sfrost@snowman.net 262 [ - + ]:CBC 341 : if (!RetrieveDataDirCreatePerm(tmpconn))
263 : : {
2709 sfrost@snowman.net 264 :UBC 0 : PQfinish(tmpconn);
265 : 0 : exit(1);
266 : : }
267 : :
4313 tgl@sss.pgh.pa.us 268 :CBC 341 : return tmpconn;
269 : : }
270 : :
271 : : /*
272 : : * From version 10, explicitly set wal segment size using SHOW wal_segment_size
273 : : * since ControlFile is not accessible here.
274 : : */
275 : : bool
2909 andres@anarazel.de 276 : 193 : RetrieveWalSegSize(PGconn *conn)
277 : : {
278 : : PGresult *res;
279 : : char xlog_unit[3];
280 : : int xlog_val,
281 : 193 : multiplier = 1;
282 : :
283 : : /* check connection existence */
284 [ - + ]: 193 : Assert(conn != NULL);
285 : :
286 : : /* for previous versions set the default xlog seg size */
287 [ - + ]: 193 : if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_SHOW_CMD)
288 : : {
2909 andres@anarazel.de 289 :UBC 0 : WalSegSz = DEFAULT_XLOG_SEG_SIZE;
290 : 0 : return true;
291 : : }
292 : :
2909 andres@anarazel.de 293 :CBC 193 : res = PQexec(conn, "SHOW wal_segment_size");
294 [ - + ]: 193 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
295 : : {
2350 peter@eisentraut.org 296 :UBC 0 : pg_log_error("could not send replication command \"%s\": %s",
297 : : "SHOW wal_segment_size", PQerrorMessage(conn));
298 : :
2909 andres@anarazel.de 299 : 0 : PQclear(res);
300 : 0 : return false;
301 : : }
2909 andres@anarazel.de 302 [ + - - + ]:CBC 193 : if (PQntuples(res) != 1 || PQnfields(res) < 1)
303 : : {
2350 peter@eisentraut.org 304 :UBC 0 : pg_log_error("could not fetch WAL segment size: got %d rows and %d fields, expected %d rows and %d or more fields",
305 : : PQntuples(res), PQnfields(res), 1, 1);
306 : :
2909 andres@anarazel.de 307 : 0 : PQclear(res);
308 : 0 : return false;
309 : : }
310 : :
311 : : /* fetch xlog value and unit from the result */
1418 dgustafsson@postgres 312 [ - + ]:CBC 193 : if (sscanf(PQgetvalue(res, 0, 0), "%d%2s", &xlog_val, xlog_unit) != 2)
313 : : {
2350 peter@eisentraut.org 314 :UBC 0 : pg_log_error("WAL segment size could not be parsed");
1968 michael@paquier.xyz 315 : 0 : PQclear(res);
2909 andres@anarazel.de 316 : 0 : return false;
317 : : }
318 : :
1968 michael@paquier.xyz 319 :CBC 193 : PQclear(res);
320 : :
321 : : /* set the multiplier based on unit to convert xlog_val to bytes */
2909 andres@anarazel.de 322 [ + - ]: 193 : if (strcmp(xlog_unit, "MB") == 0)
323 : 193 : multiplier = 1024 * 1024;
2909 andres@anarazel.de 324 [ # # ]:UBC 0 : else if (strcmp(xlog_unit, "GB") == 0)
325 : 0 : multiplier = 1024 * 1024 * 1024;
326 : :
327 : : /* convert and set WalSegSz */
2909 andres@anarazel.de 328 :CBC 193 : WalSegSz = xlog_val * multiplier;
329 : :
330 [ + - + - : 193 : if (!IsValidWalSegSize(WalSegSz))
+ - - + ]
331 : : {
740 peter@eisentraut.org 332 :UBC 0 : pg_log_error(ngettext("remote server reported invalid WAL segment size (%d byte)",
333 : : "remote server reported invalid WAL segment size (%d bytes)",
334 : : WalSegSz),
335 : : WalSegSz);
336 : 0 : pg_log_error_detail("The WAL segment size must be a power of two between 1 MB and 1 GB.");
2909 andres@anarazel.de 337 : 0 : return false;
338 : : }
339 : :
2909 andres@anarazel.de 340 :CBC 193 : return true;
341 : : }
342 : :
343 : : /*
344 : : * RetrieveDataDirCreatePerm
345 : : *
346 : : * This function is used to determine the privileges on the server's PG data
347 : : * directory and, based on that, set what the permissions will be for
348 : : * directories and files we create.
349 : : *
350 : : * PG11 added support for (optionally) group read/execute rights to be set on
351 : : * the data directory. Prior to PG11, only the owner was allowed to have rights
352 : : * on the data directory.
353 : : */
354 : : static bool
2709 sfrost@snowman.net 355 : 341 : RetrieveDataDirCreatePerm(PGconn *conn)
356 : : {
357 : : PGresult *res;
358 : : int data_directory_mode;
359 : :
360 : : /* check connection existence */
361 [ - + ]: 341 : Assert(conn != NULL);
362 : :
363 : : /* for previous versions leave the default group access */
364 [ - + ]: 341 : if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_GROUP_ACCESS)
2709 sfrost@snowman.net 365 :UBC 0 : return true;
366 : :
2709 sfrost@snowman.net 367 :CBC 341 : res = PQexec(conn, "SHOW data_directory_mode");
368 [ - + ]: 341 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
369 : : {
2350 peter@eisentraut.org 370 :UBC 0 : pg_log_error("could not send replication command \"%s\": %s",
371 : : "SHOW data_directory_mode", PQerrorMessage(conn));
372 : :
2709 sfrost@snowman.net 373 : 0 : PQclear(res);
374 : 0 : return false;
375 : : }
2709 sfrost@snowman.net 376 [ + - - + ]:CBC 341 : if (PQntuples(res) != 1 || PQnfields(res) < 1)
377 : : {
2350 peter@eisentraut.org 378 :UBC 0 : pg_log_error("could not fetch group access flag: got %d rows and %d fields, expected %d rows and %d or more fields",
379 : : PQntuples(res), PQnfields(res), 1, 1);
380 : :
2709 sfrost@snowman.net 381 : 0 : PQclear(res);
382 : 0 : return false;
383 : : }
384 : :
2709 sfrost@snowman.net 385 [ - + ]:CBC 341 : if (sscanf(PQgetvalue(res, 0, 0), "%o", &data_directory_mode) != 1)
386 : : {
2350 peter@eisentraut.org 387 :UBC 0 : pg_log_error("group access flag could not be parsed: %s",
388 : : PQgetvalue(res, 0, 0));
389 : :
2709 sfrost@snowman.net 390 : 0 : PQclear(res);
391 : 0 : return false;
392 : : }
393 : :
2709 sfrost@snowman.net 394 :CBC 341 : SetDataDirectoryCreatePerm(data_directory_mode);
395 : :
396 : 341 : PQclear(res);
397 : 341 : return true;
398 : : }
399 : :
400 : : /*
401 : : * Run IDENTIFY_SYSTEM through a given connection and give back to caller
402 : : * some result information if requested:
403 : : * - System identifier
404 : : * - Current timeline ID
405 : : * - Start LSN position
406 : : * - Database name (NULL in servers prior to 9.4)
407 : : */
408 : : bool
3993 andres@anarazel.de 409 : 349 : RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
410 : : XLogRecPtr *startpos, char **db_name)
411 : : {
412 : : PGresult *res;
413 : : uint32 hi,
414 : : lo;
415 : :
416 : : /* Check connection existence */
417 [ - + ]: 349 : Assert(conn != NULL);
418 : :
419 : 349 : res = PQexec(conn, "IDENTIFY_SYSTEM");
420 [ - + ]: 349 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
421 : : {
2350 peter@eisentraut.org 422 :UBC 0 : pg_log_error("could not send replication command \"%s\": %s",
423 : : "IDENTIFY_SYSTEM", PQerrorMessage(conn));
424 : :
3988 sfrost@snowman.net 425 : 0 : PQclear(res);
3993 andres@anarazel.de 426 : 0 : return false;
427 : : }
3993 andres@anarazel.de 428 [ + - - + ]:CBC 349 : if (PQntuples(res) != 1 || PQnfields(res) < 3)
429 : : {
2350 peter@eisentraut.org 430 :UBC 0 : pg_log_error("could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields",
431 : : PQntuples(res), PQnfields(res), 1, 3);
432 : :
3988 sfrost@snowman.net 433 : 0 : PQclear(res);
3993 andres@anarazel.de 434 : 0 : return false;
435 : : }
436 : :
437 : : /* Get system identifier */
3993 andres@anarazel.de 438 [ + + ]:CBC 349 : if (sysid != NULL)
439 : 329 : *sysid = pg_strdup(PQgetvalue(res, 0, 0));
440 : :
441 : : /* Get timeline ID to start streaming from */
442 [ + + ]: 349 : if (starttli != NULL)
443 : 329 : *starttli = atoi(PQgetvalue(res, 0, 1));
444 : :
445 : : /* Get LSN start position if necessary */
446 [ + + ]: 349 : if (startpos != NULL)
447 : : {
61 alvherre@kurilemu.de 448 [ - + ]:GNC 7 : if (sscanf(PQgetvalue(res, 0, 2), "%X/%08X", &hi, &lo) != 2)
449 : : {
2350 peter@eisentraut.org 450 :UBC 0 : pg_log_error("could not parse write-ahead log location \"%s\"",
451 : : PQgetvalue(res, 0, 2));
452 : :
3988 sfrost@snowman.net 453 : 0 : PQclear(res);
3993 andres@anarazel.de 454 : 0 : return false;
455 : : }
3993 andres@anarazel.de 456 :CBC 7 : *startpos = ((uint64) hi) << 32 | lo;
457 : : }
458 : :
459 : : /* Get database name, only available in 9.4 and newer versions */
3759 bruce@momjian.us 460 [ + + ]: 349 : if (db_name != NULL)
461 : : {
3532 alvherre@alvh.no-ip. 462 : 20 : *db_name = NULL;
463 [ + - ]: 20 : if (PQserverVersion(conn) >= 90400)
464 : : {
465 [ - + ]: 20 : if (PQnfields(res) < 4)
466 : : {
2350 peter@eisentraut.org 467 :UBC 0 : pg_log_error("could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields",
468 : : PQntuples(res), PQnfields(res), 1, 4);
469 : :
3532 alvherre@alvh.no-ip. 470 : 0 : PQclear(res);
471 : 0 : return false;
472 : : }
3532 alvherre@alvh.no-ip. 473 [ + + ]:CBC 20 : if (!PQgetisnull(res, 0, 3))
474 : 10 : *db_name = pg_strdup(PQgetvalue(res, 0, 3));
475 : : }
476 : : }
477 : :
3993 andres@anarazel.de 478 : 349 : PQclear(res);
479 : 349 : return true;
480 : : }
481 : :
482 : : /*
483 : : * Run READ_REPLICATION_SLOT through a given connection and give back to
484 : : * caller some result information if requested for this slot:
485 : : * - Start LSN position, InvalidXLogRecPtr if unknown.
486 : : * - Current timeline ID, 0 if unknown.
487 : : * Returns false on failure, and true otherwise.
488 : : */
489 : : bool
1411 michael@paquier.xyz 490 : 3 : GetSlotInformation(PGconn *conn, const char *slot_name,
491 : : XLogRecPtr *restart_lsn, TimeLineID *restart_tli)
492 : : {
493 : : PGresult *res;
494 : : PQExpBuffer query;
495 : 3 : XLogRecPtr lsn_loc = InvalidXLogRecPtr;
496 : 3 : TimeLineID tli_loc = 0;
497 : :
498 [ + - ]: 3 : if (restart_lsn)
499 : 3 : *restart_lsn = lsn_loc;
500 [ + - ]: 3 : if (restart_tli)
501 : 3 : *restart_tli = tli_loc;
502 : :
503 : 3 : query = createPQExpBuffer();
504 : 3 : appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
505 : 3 : res = PQexec(conn, query->data);
506 : 3 : destroyPQExpBuffer(query);
507 : :
508 [ - + ]: 3 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
509 : : {
1411 michael@paquier.xyz 510 :UBC 0 : pg_log_error("could not send replication command \"%s\": %s",
511 : : "READ_REPLICATION_SLOT", PQerrorMessage(conn));
512 : 0 : PQclear(res);
513 : 0 : return false;
514 : : }
515 : :
516 : : /* The command should always return precisely one tuple and three fields */
1411 michael@paquier.xyz 517 [ + - - + ]:CBC 3 : if (PQntuples(res) != 1 || PQnfields(res) != 3)
518 : : {
1411 michael@paquier.xyz 519 :UBC 0 : pg_log_error("could not read replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields",
520 : : slot_name, PQntuples(res), PQnfields(res), 1, 3);
521 : 0 : PQclear(res);
522 : 0 : return false;
523 : : }
524 : :
525 : : /*
526 : : * When the slot doesn't exist, the command returns a tuple with NULL
527 : : * values. This checks only the slot type field.
528 : : */
1411 michael@paquier.xyz 529 [ + + ]:CBC 3 : if (PQgetisnull(res, 0, 0))
530 : : {
1078 peter@eisentraut.org 531 : 1 : pg_log_error("replication slot \"%s\" does not exist", slot_name);
1411 michael@paquier.xyz 532 : 1 : PQclear(res);
533 : 1 : return false;
534 : : }
535 : :
536 : : /*
537 : : * Note that this cannot happen as READ_REPLICATION_SLOT supports only
538 : : * physical slots, but play it safe.
539 : : */
540 [ - + ]: 2 : if (strcmp(PQgetvalue(res, 0, 0), "physical") != 0)
541 : : {
1411 michael@paquier.xyz 542 :UBC 0 : pg_log_error("expected a physical replication slot, got type \"%s\" instead",
543 : : PQgetvalue(res, 0, 0));
544 : 0 : PQclear(res);
545 : 0 : return false;
546 : : }
547 : :
548 : : /* restart LSN */
1411 michael@paquier.xyz 549 [ + - ]:CBC 2 : if (!PQgetisnull(res, 0, 1))
550 : : {
551 : : uint32 hi,
552 : : lo;
553 : :
61 alvherre@kurilemu.de 554 [ - + ]:GNC 2 : if (sscanf(PQgetvalue(res, 0, 1), "%X/%08X", &hi, &lo) != 2)
555 : : {
1411 michael@paquier.xyz 556 :UBC 0 : pg_log_error("could not parse restart_lsn \"%s\" for replication slot \"%s\"",
557 : : PQgetvalue(res, 0, 1), slot_name);
558 : 0 : PQclear(res);
559 : 0 : return false;
560 : : }
1411 michael@paquier.xyz 561 :CBC 2 : lsn_loc = ((uint64) hi) << 32 | lo;
562 : : }
563 : :
564 : : /* current TLI */
565 [ + - ]: 2 : if (!PQgetisnull(res, 0, 2))
392 peter@eisentraut.org 566 : 2 : tli_loc = (TimeLineID) atoll(PQgetvalue(res, 0, 2));
567 : :
1411 michael@paquier.xyz 568 : 2 : PQclear(res);
569 : :
570 : : /* Assign results if requested */
571 [ + - ]: 2 : if (restart_lsn)
572 : 2 : *restart_lsn = lsn_loc;
573 [ + - ]: 2 : if (restart_tli)
574 : 2 : *restart_tli = tli_loc;
575 : :
576 : 2 : return true;
577 : : }
578 : :
579 : : /*
580 : : * Create a replication slot for the given connection. This function
581 : : * returns true in case of success.
582 : : */
583 : : bool
3993 andres@anarazel.de 584 : 135 : CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
585 : : bool is_temporary, bool is_physical, bool reserve_wal,
586 : : bool slot_exists_ok, bool two_phase, bool failover)
587 : : {
588 : : PQExpBuffer query;
589 : : PGresult *res;
1432 rhaas@postgresql.org 590 : 135 : bool use_new_option_syntax = (PQserverVersion(conn) >= 150000);
591 : :
3993 andres@anarazel.de 592 : 135 : query = createPQExpBuffer();
593 : :
594 [ + + + - : 135 : Assert((is_physical && plugin == NULL) ||
+ - + - ]
595 : : (!is_physical && plugin != NULL));
1529 akapila@postgresql.o 596 [ + + - + ]: 135 : Assert(!(two_phase && is_physical));
155 msawada@postgresql.o 597 [ + + - + ]: 135 : Assert(!(failover && is_physical));
3993 andres@anarazel.de 598 [ - + ]: 135 : Assert(slot_name != NULL);
599 : :
600 : : /* Build base portion of query */
2902 peter_e@gmx.net 601 : 135 : appendPQExpBuffer(query, "CREATE_REPLICATION_SLOT \"%s\"", slot_name);
602 [ + + ]: 135 : if (is_temporary)
2256 drowley@postgresql.o 603 : 129 : appendPQExpBufferStr(query, " TEMPORARY");
3993 andres@anarazel.de 604 [ + + ]: 135 : if (is_physical)
2256 drowley@postgresql.o 605 : 132 : appendPQExpBufferStr(query, " PHYSICAL");
606 : : else
1432 rhaas@postgresql.org 607 : 3 : appendPQExpBuffer(query, " LOGICAL \"%s\"", plugin);
608 : :
609 : : /* Add any requested options */
610 [ + - ]: 135 : if (use_new_option_syntax)
611 : 135 : appendPQExpBufferStr(query, " (");
612 [ + + ]: 135 : if (is_physical)
613 : : {
2902 peter_e@gmx.net 614 [ + + ]: 132 : if (reserve_wal)
1432 rhaas@postgresql.org 615 : 131 : AppendPlainCommandOption(query, use_new_option_syntax,
616 : : "RESERVE_WAL");
617 : : }
618 : : else
619 : : {
155 msawada@postgresql.o 620 [ + + + - ]: 3 : if (failover && PQserverVersion(conn) >= 170000)
621 : 1 : AppendPlainCommandOption(query, use_new_option_syntax,
622 : : "FAILOVER");
623 : :
1529 akapila@postgresql.o 624 [ + + + - ]: 3 : if (two_phase && PQserverVersion(conn) >= 150000)
1432 rhaas@postgresql.org 625 : 1 : AppendPlainCommandOption(query, use_new_option_syntax,
626 : : "TWO_PHASE");
627 : :
3098 peter_e@gmx.net 628 [ + - ]: 3 : if (PQserverVersion(conn) >= 100000)
629 : : {
630 : : /* pg_recvlogical doesn't use an exported snapshot, so suppress */
1432 rhaas@postgresql.org 631 [ + - ]: 3 : if (use_new_option_syntax)
632 : 3 : AppendStringCommandOption(query, use_new_option_syntax,
633 : : "SNAPSHOT", "nothing");
634 : : else
1432 rhaas@postgresql.org 635 :UBC 0 : AppendPlainCommandOption(query, use_new_option_syntax,
636 : : "NOEXPORT_SNAPSHOT");
637 : : }
638 : : }
1432 rhaas@postgresql.org 639 [ + - ]:CBC 135 : if (use_new_option_syntax)
640 : : {
641 : : /* Suppress option list if it would be empty, otherwise terminate */
642 [ + + ]: 135 : if (query->data[query->len - 1] == '(')
643 : : {
644 : 1 : query->len -= 2;
645 : 1 : query->data[query->len] = '\0';
646 : : }
647 : : else
648 : 134 : appendPQExpBufferChar(query, ')');
649 : : }
650 : :
651 : : /* Now run the query */
3993 andres@anarazel.de 652 : 135 : res = PQexec(conn, query->data);
653 [ + + ]: 135 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
654 : : {
3709 655 : 1 : const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
656 : :
3678 657 [ - + - - ]: 1 : if (slot_exists_ok &&
3678 andres@anarazel.de 658 :UBC 0 : sqlstate &&
659 [ # # ]: 0 : strcmp(sqlstate, ERRCODE_DUPLICATE_OBJECT) == 0)
660 : : {
3709 661 : 0 : destroyPQExpBuffer(query);
662 : 0 : PQclear(res);
663 : 0 : return true;
664 : : }
665 : : else
666 : : {
2350 peter@eisentraut.org 667 :CBC 1 : pg_log_error("could not send replication command \"%s\": %s",
668 : : query->data, PQerrorMessage(conn));
669 : :
3709 andres@anarazel.de 670 : 1 : destroyPQExpBuffer(query);
671 : 1 : PQclear(res);
672 : 1 : return false;
673 : : }
674 : : }
675 : :
3993 676 [ + - - + ]: 134 : if (PQntuples(res) != 1 || PQnfields(res) != 4)
677 : : {
2350 peter@eisentraut.org 678 :UBC 0 : pg_log_error("could not create replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields",
679 : : slot_name,
680 : : PQntuples(res), PQnfields(res), 1, 4);
681 : :
3988 sfrost@snowman.net 682 : 0 : destroyPQExpBuffer(query);
683 : 0 : PQclear(res);
3993 andres@anarazel.de 684 : 0 : return false;
685 : : }
686 : :
3988 sfrost@snowman.net 687 :CBC 134 : destroyPQExpBuffer(query);
3993 andres@anarazel.de 688 : 134 : PQclear(res);
689 : 134 : return true;
690 : : }
691 : :
692 : : /*
693 : : * Drop a replication slot for the given connection. This function
694 : : * returns true in case of success.
695 : : */
696 : : bool
697 : 3 : DropReplicationSlot(PGconn *conn, const char *slot_name)
698 : : {
699 : : PQExpBuffer query;
700 : : PGresult *res;
701 : :
702 [ - + ]: 3 : Assert(slot_name != NULL);
703 : :
704 : 3 : query = createPQExpBuffer();
705 : :
706 : : /* Build query */
707 : 3 : appendPQExpBuffer(query, "DROP_REPLICATION_SLOT \"%s\"",
708 : : slot_name);
709 : 3 : res = PQexec(conn, query->data);
710 [ - + ]: 3 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
711 : : {
2350 peter@eisentraut.org 712 :UBC 0 : pg_log_error("could not send replication command \"%s\": %s",
713 : : query->data, PQerrorMessage(conn));
714 : :
3988 sfrost@snowman.net 715 : 0 : destroyPQExpBuffer(query);
716 : 0 : PQclear(res);
3993 andres@anarazel.de 717 : 0 : return false;
718 : : }
719 : :
3993 andres@anarazel.de 720 [ + - - + ]:CBC 3 : if (PQntuples(res) != 0 || PQnfields(res) != 0)
721 : : {
2350 peter@eisentraut.org 722 :UBC 0 : pg_log_error("could not drop replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields",
723 : : slot_name,
724 : : PQntuples(res), PQnfields(res), 0, 0);
725 : :
3988 sfrost@snowman.net 726 : 0 : destroyPQExpBuffer(query);
727 : 0 : PQclear(res);
3993 andres@anarazel.de 728 : 0 : return false;
729 : : }
730 : :
3709 tgl@sss.pgh.pa.us 731 :CBC 3 : destroyPQExpBuffer(query);
3993 andres@anarazel.de 732 : 3 : PQclear(res);
733 : 3 : return true;
734 : : }
735 : :
736 : : /*
737 : : * Append a "plain" option - one with no value - to a server command that
738 : : * is being constructed.
739 : : *
740 : : * In the old syntax, all options were parser keywords, so you could just
741 : : * write things like SOME_COMMAND OPTION1 OPTION2 'opt2value' OPTION3 42. The
742 : : * new syntax uses a comma-separated list surrounded by parentheses, so the
743 : : * equivalent is SOME_COMMAND (OPTION1, OPTION2 'optvalue', OPTION3 42).
744 : : */
745 : : void
1432 rhaas@postgresql.org 746 : 1372 : AppendPlainCommandOption(PQExpBuffer buf, bool use_new_option_syntax,
747 : : char *option_name)
748 : : {
749 [ + + + + ]: 1372 : if (buf->len > 0 && buf->data[buf->len - 1] != '(')
750 : : {
751 [ + - ]: 1053 : if (use_new_option_syntax)
752 : 1053 : appendPQExpBufferStr(buf, ", ");
753 : : else
1432 rhaas@postgresql.org 754 :UBC 0 : appendPQExpBufferChar(buf, ' ');
755 : : }
756 : :
1432 rhaas@postgresql.org 757 :CBC 1372 : appendPQExpBuffer(buf, " %s", option_name);
758 : 1372 : }
759 : :
760 : : /*
761 : : * Append an option with an associated string value to a server command that
762 : : * is being constructed.
763 : : *
764 : : * See comments for AppendPlainCommandOption, above.
765 : : */
766 : : void
767 : 801 : AppendStringCommandOption(PQExpBuffer buf, bool use_new_option_syntax,
768 : : char *option_name, char *option_value)
769 : : {
770 : 801 : AppendPlainCommandOption(buf, use_new_option_syntax, option_name);
771 : :
772 [ + - ]: 801 : if (option_value != NULL)
773 : : {
774 : 801 : size_t length = strlen(option_value);
775 : 801 : char *escaped_value = palloc(1 + 2 * length);
776 : :
777 : 801 : PQescapeStringConn(conn, escaped_value, option_value, length, NULL);
778 : 801 : appendPQExpBuffer(buf, " '%s'", escaped_value);
779 : 801 : pfree(escaped_value);
780 : : }
781 : 801 : }
782 : :
783 : : /*
784 : : * Append an option with an associated integer value to a server command
785 : : * is being constructed.
786 : : *
787 : : * See comments for AppendPlainCommandOption, above.
788 : : */
789 : : void
790 : 177 : AppendIntegerCommandOption(PQExpBuffer buf, bool use_new_option_syntax,
791 : : char *option_name, int32 option_value)
792 : : {
793 : 177 : AppendPlainCommandOption(buf, use_new_option_syntax, option_name);
794 : :
795 : 177 : appendPQExpBuffer(buf, " %d", option_value);
796 : 177 : }
797 : :
798 : : /*
799 : : * Frontend version of GetCurrentTimestamp(), since we are not linked with
800 : : * backend code.
801 : : */
802 : : TimestampTz
4190 803 : 1367 : feGetCurrentTimestamp(void)
804 : : {
805 : : TimestampTz result;
806 : : struct timeval tp;
807 : :
808 : 1367 : gettimeofday(&tp, NULL);
809 : :
3117 tgl@sss.pgh.pa.us 810 : 1367 : result = (TimestampTz) tp.tv_sec -
811 : : ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
4190 rhaas@postgresql.org 812 : 1367 : result = (result * USECS_PER_SEC) + tp.tv_usec;
813 : :
814 : 1367 : return result;
815 : : }
816 : :
817 : : /*
818 : : * Frontend version of TimestampDifference(), since we are not linked with
819 : : * backend code.
820 : : */
821 : : void
3117 tgl@sss.pgh.pa.us 822 : 1243 : feTimestampDifference(TimestampTz start_time, TimestampTz stop_time,
823 : : long *secs, int *microsecs)
824 : : {
825 : 1243 : TimestampTz diff = stop_time - start_time;
826 : :
4190 rhaas@postgresql.org 827 [ - + ]: 1243 : if (diff <= 0)
828 : : {
4190 rhaas@postgresql.org 829 :UBC 0 : *secs = 0;
830 : 0 : *microsecs = 0;
831 : : }
832 : : else
833 : : {
4190 rhaas@postgresql.org 834 :CBC 1243 : *secs = (long) (diff / USECS_PER_SEC);
835 : 1243 : *microsecs = (int) (diff % USECS_PER_SEC);
836 : : }
837 : 1243 : }
838 : :
839 : : /*
840 : : * Frontend version of TimestampDifferenceExceeds(), since we are not
841 : : * linked with backend code.
842 : : */
843 : : bool
3117 tgl@sss.pgh.pa.us 844 : 1344 : feTimestampDifferenceExceeds(TimestampTz start_time,
845 : : TimestampTz stop_time,
846 : : int msec)
847 : : {
848 : 1344 : TimestampTz diff = stop_time - start_time;
849 : :
4190 rhaas@postgresql.org 850 : 1344 : return (diff >= msec * INT64CONST(1000));
851 : : }
852 : :
853 : : /*
854 : : * Converts an int64 to network byte order.
855 : : */
856 : : void
857 : 588 : fe_sendint64(int64 i, char *buf)
858 : : {
2897 andres@anarazel.de 859 : 588 : uint64 n64 = pg_hton64(i);
860 : :
861 : 588 : memcpy(buf, &n64, sizeof(n64));
4190 rhaas@postgresql.org 862 : 588 : }
863 : :
864 : : /*
865 : : * Converts an int64 from network byte order to native format.
866 : : */
867 : : int64
868 : 1175 : fe_recvint64(char *buf)
869 : : {
870 : : uint64 n64;
871 : :
2897 andres@anarazel.de 872 : 1175 : memcpy(&n64, buf, sizeof(n64));
873 : :
874 : 1175 : return pg_ntoh64(n64);
875 : : }
|