xref: /PHP-8.2/ext/pdo_pgsql/pgsql_driver.c (revision 15405c60)
1 /*
2   +----------------------------------------------------------------------+
3   | Copyright (c) The PHP Group                                          |
4   +----------------------------------------------------------------------+
5   | This source file is subject to version 3.01 of the PHP license,      |
6   | that is bundled with this package in the file LICENSE, and is        |
7   | available through the world-wide-web at the following url:           |
8   | https://www.php.net/license/3_01.txt                                 |
9   | If you did not receive a copy of the PHP license and are unable to   |
10   | obtain it through the world-wide-web, please send a note to          |
11   | license@php.net so we can mail you a copy immediately.               |
12   +----------------------------------------------------------------------+
13   | Authors: Edin Kadribasic <edink@emini.dk>                            |
14   |          Ilia Alshanestsky <ilia@prohost.org>                        |
15   |          Wez Furlong <wez@php.net>                                   |
16   +----------------------------------------------------------------------+
17 */
18 
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22 
23 #include "php.h"
24 #include "php_ini.h"
25 #include "ext/standard/info.h"
26 #include "ext/standard/php_string.h"
27 #include "main/php_network.h"
28 #include "pdo/php_pdo.h"
29 #include "pdo/php_pdo_driver.h"
30 #include "pdo/php_pdo_error.h"
31 #include "ext/standard/file.h"
32 #include "php_pdo_pgsql.h"
33 #include "php_pdo_pgsql_int.h"
34 #include "zend_exceptions.h"
35 #include "pgsql_driver_arginfo.h"
36 
37 static bool pgsql_handle_in_transaction(pdo_dbh_t *dbh);
38 
_pdo_pgsql_trim_message(const char * message,int persistent)39 static char * _pdo_pgsql_trim_message(const char *message, int persistent)
40 {
41 	size_t i = strlen(message)-1;
42 	char *tmp;
43 
44 	if (i>1 && (message[i-1] == '\r' || message[i-1] == '\n') && message[i] == '.') {
45 		--i;
46 	}
47 	while (i>0 && (message[i] == '\r' || message[i] == '\n')) {
48 		--i;
49 	}
50 	++i;
51 	tmp = pemalloc(i + 1, persistent);
52 	memcpy(tmp, message, i);
53 	tmp[i] = '\0';
54 
55 	return tmp;
56 }
57 
_pdo_pgsql_escape_credentials(char * str)58 static zend_string* _pdo_pgsql_escape_credentials(char *str)
59 {
60 	if (str) {
61 		return php_addcslashes_str(str, strlen(str), "\\'", sizeof("\\'"));
62 	}
63 
64 	return NULL;
65 }
66 
_pdo_pgsql_error(pdo_dbh_t * dbh,pdo_stmt_t * stmt,int errcode,const char * sqlstate,const char * msg,const char * file,int line)67 int _pdo_pgsql_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, int errcode, const char *sqlstate, const char *msg, const char *file, int line) /* {{{ */
68 {
69 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
70 	pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code;
71 	pdo_pgsql_error_info *einfo = &H->einfo;
72 	char *errmsg = PQerrorMessage(H->server);
73 
74 	einfo->errcode = errcode;
75 	einfo->file = file;
76 	einfo->line = line;
77 
78 	if (einfo->errmsg) {
79 		pefree(einfo->errmsg, dbh->is_persistent);
80 		einfo->errmsg = NULL;
81 	}
82 
83 	if (sqlstate == NULL || strlen(sqlstate) >= sizeof(pdo_error_type)) {
84 		strcpy(*pdo_err, "HY000");
85 	}
86 	else {
87 		strcpy(*pdo_err, sqlstate);
88 	}
89 
90 	if (msg) {
91 		einfo->errmsg = pestrdup(msg, dbh->is_persistent);
92 	}
93 	else if (errmsg) {
94 		einfo->errmsg = _pdo_pgsql_trim_message(errmsg, dbh->is_persistent);
95 	}
96 
97 	if (!dbh->methods) {
98 		pdo_throw_exception(einfo->errcode, einfo->errmsg, pdo_err);
99 	}
100 
101 	return errcode;
102 }
103 /* }}} */
104 
_pdo_pgsql_notice(pdo_dbh_t * dbh,const char * message)105 static void _pdo_pgsql_notice(pdo_dbh_t *dbh, const char *message) /* {{{ */
106 {
107 /*	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data; */
108 }
109 /* }}} */
110 
pdo_pgsql_fetch_error_func(pdo_dbh_t * dbh,pdo_stmt_t * stmt,zval * info)111 static void pdo_pgsql_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info) /* {{{ */
112 {
113 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
114 	pdo_pgsql_error_info *einfo = &H->einfo;
115 
116 	if (einfo->errcode) {
117 		add_next_index_long(info, einfo->errcode);
118 	} else {
119 		/* Add null to respect expected info array structure */
120 		add_next_index_null(info);
121 	}
122 	if (einfo->errmsg) {
123 		add_next_index_string(info, einfo->errmsg);
124 	}
125 }
126 /* }}} */
127 
128 /* {{{ pdo_pgsql_create_lob_stream */
pgsql_lob_write(php_stream * stream,const char * buf,size_t count)129 static ssize_t pgsql_lob_write(php_stream *stream, const char *buf, size_t count)
130 {
131 	struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
132 	return lo_write(self->conn, self->lfd, (char*)buf, count);
133 }
134 
pgsql_lob_read(php_stream * stream,char * buf,size_t count)135 static ssize_t pgsql_lob_read(php_stream *stream, char *buf, size_t count)
136 {
137 	struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
138 	return lo_read(self->conn, self->lfd, buf, count);
139 }
140 
pgsql_lob_close(php_stream * stream,int close_handle)141 static int pgsql_lob_close(php_stream *stream, int close_handle)
142 {
143 	struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
144 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)(Z_PDO_DBH_P(&self->dbh))->driver_data;
145 
146 	if (close_handle) {
147 		lo_close(self->conn, self->lfd);
148 	}
149 	zend_hash_index_del(H->lob_streams, php_stream_get_resource_id(stream));
150 	zval_ptr_dtor(&self->dbh);
151 	efree(self);
152 	return 0;
153 }
154 
pgsql_lob_flush(php_stream * stream)155 static int pgsql_lob_flush(php_stream *stream)
156 {
157 	return 0;
158 }
159 
pgsql_lob_seek(php_stream * stream,zend_off_t offset,int whence,zend_off_t * newoffset)160 static int pgsql_lob_seek(php_stream *stream, zend_off_t offset, int whence,
161 		zend_off_t *newoffset)
162 {
163 	struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
164 #if defined(HAVE_PG_LO64) && defined(ZEND_ENABLE_ZVAL_LONG64)
165 	zend_off_t pos = lo_lseek64(self->conn, self->lfd, offset, whence);
166 #else
167 	zend_off_t pos = lo_lseek(self->conn, self->lfd, offset, whence);
168 #endif
169 	*newoffset = pos;
170 	return pos >= 0 ? 0 : -1;
171 }
172 
173 const php_stream_ops pdo_pgsql_lob_stream_ops = {
174 	pgsql_lob_write,
175 	pgsql_lob_read,
176 	pgsql_lob_close,
177 	pgsql_lob_flush,
178 	"pdo_pgsql lob stream",
179 	pgsql_lob_seek,
180 	NULL,
181 	NULL,
182 	NULL
183 };
184 
pdo_pgsql_create_lob_stream(zval * dbh,int lfd,Oid oid)185 php_stream *pdo_pgsql_create_lob_stream(zval *dbh, int lfd, Oid oid)
186 {
187 	php_stream *stm;
188 	struct pdo_pgsql_lob_self *self = ecalloc(1, sizeof(*self));
189 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)(Z_PDO_DBH_P(dbh))->driver_data;
190 
191 	ZVAL_COPY_VALUE(&self->dbh, dbh);
192 	self->lfd = lfd;
193 	self->oid = oid;
194 	self->conn = H->server;
195 
196 	stm = php_stream_alloc(&pdo_pgsql_lob_stream_ops, self, 0, "r+b");
197 
198 	if (stm) {
199 		Z_ADDREF_P(dbh);
200 		zend_hash_index_add_ptr(H->lob_streams, php_stream_get_resource_id(stm), stm->res);
201 		return stm;
202 	}
203 
204 	efree(self);
205 	return NULL;
206 }
207 /* }}} */
208 
pdo_pgsql_close_lob_streams(pdo_dbh_t * dbh)209 void pdo_pgsql_close_lob_streams(pdo_dbh_t *dbh)
210 {
211 	zend_resource *res;
212 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
213 	if (H->lob_streams) {
214 		ZEND_HASH_REVERSE_FOREACH_PTR(H->lob_streams, res) {
215 			if (res->type >= 0) {
216 				zend_list_close(res);
217 			}
218 		} ZEND_HASH_FOREACH_END();
219 	}
220 }
221 
pgsql_handle_closer(pdo_dbh_t * dbh)222 static void pgsql_handle_closer(pdo_dbh_t *dbh) /* {{{ */
223 {
224 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
225 	if (H) {
226 		if (H->lob_streams) {
227 			pdo_pgsql_close_lob_streams(dbh);
228 			zend_hash_destroy(H->lob_streams);
229 			pefree(H->lob_streams, dbh->is_persistent);
230 			H->lob_streams = NULL;
231 		}
232 		if (H->server) {
233 			PQfinish(H->server);
234 			H->server = NULL;
235 		}
236 		if (H->einfo.errmsg) {
237 			pefree(H->einfo.errmsg, dbh->is_persistent);
238 			H->einfo.errmsg = NULL;
239 		}
240 		pefree(H, dbh->is_persistent);
241 		dbh->driver_data = NULL;
242 	}
243 }
244 /* }}} */
245 
pgsql_handle_preparer(pdo_dbh_t * dbh,zend_string * sql,pdo_stmt_t * stmt,zval * driver_options)246 static bool pgsql_handle_preparer(pdo_dbh_t *dbh, zend_string *sql, pdo_stmt_t *stmt, zval *driver_options)
247 {
248 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
249 	pdo_pgsql_stmt *S = ecalloc(1, sizeof(pdo_pgsql_stmt));
250 	int scrollable;
251 	int ret;
252 	zend_string *nsql = NULL;
253 	int emulate = 0;
254 	int execute_only = 0;
255 
256 	S->H = H;
257 	stmt->driver_data = S;
258 	stmt->methods = &pgsql_stmt_methods;
259 
260 	scrollable = pdo_attr_lval(driver_options, PDO_ATTR_CURSOR,
261 		PDO_CURSOR_FWDONLY) == PDO_CURSOR_SCROLL;
262 
263 	if (scrollable) {
264 		if (S->cursor_name) {
265 			efree(S->cursor_name);
266 		}
267 		spprintf(&S->cursor_name, 0, "pdo_crsr_%08x", ++H->stmt_counter);
268 		emulate = 1;
269 	} else if (driver_options) {
270 		if (pdo_attr_lval(driver_options, PDO_ATTR_EMULATE_PREPARES, H->emulate_prepares) == 1) {
271 			emulate = 1;
272 		}
273 		if (pdo_attr_lval(driver_options, PDO_PGSQL_ATTR_DISABLE_PREPARES, H->disable_prepares) == 1) {
274 			execute_only = 1;
275 		}
276 	} else {
277 		emulate = H->disable_native_prepares || H->emulate_prepares;
278 		execute_only = H->disable_prepares;
279 	}
280 
281 	if (!emulate && PQprotocolVersion(H->server) <= 2) {
282 		emulate = 1;
283 	}
284 
285 	if (emulate) {
286 		stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;
287 	} else {
288 		stmt->supports_placeholders = PDO_PLACEHOLDER_NAMED;
289 		stmt->named_rewrite_template = "$%d";
290 	}
291 
292 	ret = pdo_parse_params(stmt, sql, &nsql);
293 
294 	if (ret == -1) {
295 		/* couldn't grok it */
296 		strcpy(dbh->error_code, stmt->error_code);
297 		return false;
298 	} else if (ret == 1) {
299 		/* query was re-written */
300 		S->query = nsql;
301 	} else {
302 		S->query = zend_string_copy(sql);
303 	}
304 
305 	if (!emulate && !execute_only) {
306 		/* prepared query: set the query name and defer the
307 		   actual prepare until the first execute call */
308 		spprintf(&S->stmt_name, 0, "pdo_stmt_%08x", ++H->stmt_counter);
309 	}
310 
311 	return true;
312 }
313 
pgsql_handle_doer(pdo_dbh_t * dbh,const zend_string * sql)314 static zend_long pgsql_handle_doer(pdo_dbh_t *dbh, const zend_string *sql)
315 {
316 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
317 	PGresult *res;
318 	zend_long ret = 1;
319 	ExecStatusType qs;
320 
321 	bool in_trans = pgsql_handle_in_transaction(dbh);
322 
323 	if (!(res = PQexec(H->server, ZSTR_VAL(sql)))) {
324 		/* fatal error */
325 		pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
326 		return -1;
327 	}
328 	qs = PQresultStatus(res);
329 	if (qs != PGRES_COMMAND_OK && qs != PGRES_TUPLES_OK) {
330 		pdo_pgsql_error(dbh, qs, pdo_pgsql_sqlstate(res));
331 		PQclear(res);
332 		return -1;
333 	}
334 	H->pgoid = PQoidValue(res);
335 	if (qs == PGRES_COMMAND_OK) {
336 		ret = ZEND_ATOL(PQcmdTuples(res));
337 	} else {
338 		ret = Z_L(0);
339 	}
340 	PQclear(res);
341 	if (in_trans && !pgsql_handle_in_transaction(dbh)) {
342 		pdo_pgsql_close_lob_streams(dbh);
343 	}
344 
345 	return ret;
346 }
347 
pgsql_handle_quoter(pdo_dbh_t * dbh,const zend_string * unquoted,enum pdo_param_type paramtype)348 static zend_string* pgsql_handle_quoter(pdo_dbh_t *dbh, const zend_string *unquoted, enum pdo_param_type paramtype)
349 {
350 	unsigned char *escaped;
351 	char *quoted;
352 	size_t quotedlen;
353 	zend_string *quoted_str;
354 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
355 	size_t tmp_len;
356 
357 	switch (paramtype) {
358 		case PDO_PARAM_LOB:
359 			/* escapedlen returned by PQescapeBytea() accounts for trailing 0 */
360 			escaped = PQescapeByteaConn(H->server, (unsigned char *)ZSTR_VAL(unquoted), ZSTR_LEN(unquoted), &tmp_len);
361 			quotedlen = tmp_len + 1;
362 			quoted = emalloc(quotedlen + 1);
363 			memcpy(quoted+1, escaped, quotedlen-2);
364 			quoted[0] = '\'';
365 			quoted[quotedlen-1] = '\'';
366 			quoted[quotedlen] = '\0';
367 			PQfreemem(escaped);
368 			break;
369 		default:
370 			quoted = safe_emalloc(2, ZSTR_LEN(unquoted), 3);
371 			quoted[0] = '\'';
372 			quotedlen = PQescapeStringConn(H->server, quoted + 1, ZSTR_VAL(unquoted), ZSTR_LEN(unquoted), NULL);
373 			quoted[quotedlen + 1] = '\'';
374 			quoted[quotedlen + 2] = '\0';
375 			quotedlen += 2;
376 	}
377 
378 	quoted_str = zend_string_init(quoted, quotedlen, 0);
379 	efree(quoted);
380 	return quoted_str;
381 }
382 
pdo_pgsql_last_insert_id(pdo_dbh_t * dbh,const zend_string * name)383 static zend_string *pdo_pgsql_last_insert_id(pdo_dbh_t *dbh, const zend_string *name)
384 {
385 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
386 	zend_string *id = NULL;
387 	PGresult *res;
388 	ExecStatusType status;
389 
390 	if (name == NULL) {
391 		res = PQexec(H->server, "SELECT LASTVAL()");
392 	} else {
393 		const char *q[1];
394 		q[0] = ZSTR_VAL(name);
395 
396 		res = PQexecParams(H->server, "SELECT CURRVAL($1)", 1, NULL, q, NULL, NULL, 0);
397 	}
398 	status = PQresultStatus(res);
399 
400 	if (res && (status == PGRES_TUPLES_OK)) {
401 		id = zend_string_init((char *)PQgetvalue(res, 0, 0), PQgetlength(res, 0, 0), 0);
402 	} else {
403 		pdo_pgsql_error(dbh, status, pdo_pgsql_sqlstate(res));
404 	}
405 
406 	if (res) {
407 		PQclear(res);
408 	}
409 
410 	return id;
411 }
412 
pdo_libpq_version(char * buf,size_t len)413 void pdo_libpq_version(char *buf, size_t len)
414 {
415 	int version = PQlibVersion();
416 	int major = version / 10000;
417 	if (major >= 10) {
418 		int minor = version % 10000;
419 		snprintf(buf, len, "%d.%d", major, minor);
420 	} else {
421 		int minor = version / 100 % 100;
422 		int revision = version % 100;
423 		snprintf(buf, len, "%d.%d.%d", major, minor, revision);
424 	}
425 }
426 
pdo_pgsql_get_attribute(pdo_dbh_t * dbh,zend_long attr,zval * return_value)427 static int pdo_pgsql_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value)
428 {
429 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
430 
431 	switch (attr) {
432 		case PDO_ATTR_EMULATE_PREPARES:
433 			ZVAL_BOOL(return_value, H->emulate_prepares);
434 			break;
435 
436 		case PDO_PGSQL_ATTR_DISABLE_PREPARES:
437 			ZVAL_BOOL(return_value, H->disable_prepares);
438 			break;
439 
440 		case PDO_ATTR_CLIENT_VERSION: {
441 			char buf[16];
442 			pdo_libpq_version(buf, sizeof(buf));
443 			ZVAL_STRING(return_value, buf);
444 			break;
445 		}
446 
447 		case PDO_ATTR_SERVER_VERSION:
448 			if (PQprotocolVersion(H->server) >= 3) { /* PostgreSQL 7.4 or later */
449 				ZVAL_STRING(return_value, (char*)PQparameterStatus(H->server, "server_version"));
450 			} else /* emulate above via a query */
451 			{
452 				PGresult *res = PQexec(H->server, "SELECT VERSION()");
453 				if (res && PQresultStatus(res) == PGRES_TUPLES_OK) {
454 					ZVAL_STRING(return_value, (char *)PQgetvalue(res, 0, 0));
455 				}
456 
457 				if (res) {
458 					PQclear(res);
459 				}
460 			}
461 			break;
462 
463 		case PDO_ATTR_CONNECTION_STATUS:
464 			switch (PQstatus(H->server)) {
465 				case CONNECTION_STARTED:
466 					ZVAL_STRINGL(return_value, "Waiting for connection to be made.", sizeof("Waiting for connection to be made.")-1);
467 					break;
468 
469 				case CONNECTION_MADE:
470 				case CONNECTION_OK:
471 					ZVAL_STRINGL(return_value, "Connection OK; waiting to send.", sizeof("Connection OK; waiting to send.")-1);
472 					break;
473 
474 				case CONNECTION_AWAITING_RESPONSE:
475 					ZVAL_STRINGL(return_value, "Waiting for a response from the server.", sizeof("Waiting for a response from the server.")-1);
476 					break;
477 
478 				case CONNECTION_AUTH_OK:
479 					ZVAL_STRINGL(return_value, "Received authentication; waiting for backend start-up to finish.", sizeof("Received authentication; waiting for backend start-up to finish.")-1);
480 					break;
481 #ifdef CONNECTION_SSL_STARTUP
482 				case CONNECTION_SSL_STARTUP:
483 					ZVAL_STRINGL(return_value, "Negotiating SSL encryption.", sizeof("Negotiating SSL encryption.")-1);
484 					break;
485 #endif
486 				case CONNECTION_SETENV:
487 					ZVAL_STRINGL(return_value, "Negotiating environment-driven parameter settings.", sizeof("Negotiating environment-driven parameter settings.")-1);
488 					break;
489 
490 				case CONNECTION_BAD:
491 				default:
492 					ZVAL_STRINGL(return_value, "Bad connection.", sizeof("Bad connection.")-1);
493 					break;
494 			}
495 			break;
496 
497 		case PDO_ATTR_SERVER_INFO: {
498 			int spid = PQbackendPID(H->server);
499 
500 
501 			zend_string *str_info =
502 				strpprintf(0,
503 					"PID: %d; Client Encoding: %s; Is Superuser: %s; Session Authorization: %s; Date Style: %s",
504 					spid,
505 					(char*)PQparameterStatus(H->server, "client_encoding"),
506 					(char*)PQparameterStatus(H->server, "is_superuser"),
507 					(char*)PQparameterStatus(H->server, "session_authorization"),
508 					(char*)PQparameterStatus(H->server, "DateStyle"));
509 
510 			ZVAL_STR(return_value, str_info);
511 			break;
512 		}
513 
514 		default:
515 			return 0;
516 	}
517 
518 	return 1;
519 }
520 
521 /* {{{ */
pdo_pgsql_check_liveness(pdo_dbh_t * dbh)522 static zend_result pdo_pgsql_check_liveness(pdo_dbh_t *dbh)
523 {
524 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
525 	if (!PQconsumeInput(H->server) || PQstatus(H->server) == CONNECTION_BAD) {
526 		PQreset(H->server);
527 	}
528 	return (PQstatus(H->server) == CONNECTION_OK) ? SUCCESS : FAILURE;
529 }
530 /* }}} */
531 
pgsql_handle_in_transaction(pdo_dbh_t * dbh)532 static bool pgsql_handle_in_transaction(pdo_dbh_t *dbh)
533 {
534 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
535 
536 	return PQtransactionStatus(H->server) > PQTRANS_IDLE;
537 }
538 
pdo_pgsql_transaction_cmd(const char * cmd,pdo_dbh_t * dbh)539 static bool pdo_pgsql_transaction_cmd(const char *cmd, pdo_dbh_t *dbh)
540 {
541 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
542 	PGresult *res;
543 	bool ret = true;
544 
545 	res = PQexec(H->server, cmd);
546 
547 	if (PQresultStatus(res) != PGRES_COMMAND_OK) {
548 		pdo_pgsql_error(dbh, PQresultStatus(res), pdo_pgsql_sqlstate(res));
549 		ret = false;
550 	}
551 
552 	PQclear(res);
553 	return ret;
554 }
555 
pgsql_handle_begin(pdo_dbh_t * dbh)556 static bool pgsql_handle_begin(pdo_dbh_t *dbh)
557 {
558 	return pdo_pgsql_transaction_cmd("BEGIN", dbh);
559 }
560 
pgsql_handle_commit(pdo_dbh_t * dbh)561 static bool pgsql_handle_commit(pdo_dbh_t *dbh)
562 {
563 	bool ret = pdo_pgsql_transaction_cmd("COMMIT", dbh);
564 
565 	/* When deferred constraints are used the commit could
566 	   fail, and a ROLLBACK implicitly ran. See bug #67462 */
567 	if (ret) {
568 		pdo_pgsql_close_lob_streams(dbh);
569 	} else {
570 		dbh->in_txn = pgsql_handle_in_transaction(dbh);
571 	}
572 
573 	return ret;
574 }
575 
pgsql_handle_rollback(pdo_dbh_t * dbh)576 static bool pgsql_handle_rollback(pdo_dbh_t *dbh)
577 {
578 	int ret = pdo_pgsql_transaction_cmd("ROLLBACK", dbh);
579 
580 	if (ret) {
581 		pdo_pgsql_close_lob_streams(dbh);
582 	}
583 
584 	return ret;
585 }
586 
587 /* {{{ Returns true if the copy worked fine or false if error */
PHP_METHOD(PDO_PGSql_Ext,pgsqlCopyFromArray)588 PHP_METHOD(PDO_PGSql_Ext, pgsqlCopyFromArray)
589 {
590 	pdo_dbh_t *dbh;
591 	pdo_pgsql_db_handle *H;
592 
593 	zval *pg_rows;
594 
595 	char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
596 	size_t table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
597 	char *query;
598 
599 	PGresult *pgsql_result;
600 	ExecStatusType status;
601 
602 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sa|sss!",
603 					&table_name, &table_name_len, &pg_rows,
604 					&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
605 		RETURN_THROWS();
606 	}
607 
608 	if (!zend_hash_num_elements(Z_ARRVAL_P(pg_rows))) {
609 		zend_argument_value_error(2, "cannot be empty");
610 		RETURN_THROWS();
611 	}
612 
613 	dbh = Z_PDO_DBH_P(ZEND_THIS);
614 	PDO_CONSTRUCT_CHECK;
615 	PDO_DBH_CLEAR_ERR();
616 
617 	/* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
618 	if (pg_fields) {
619 		spprintf(&query, 0, "COPY %s (%s) FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
620 	} else {
621 		spprintf(&query, 0, "COPY %s FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
622 	}
623 
624 	/* Obtain db Handle */
625 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
626 
627 	while ((pgsql_result = PQgetResult(H->server))) {
628 		PQclear(pgsql_result);
629 	}
630 	pgsql_result = PQexec(H->server, query);
631 
632 	efree(query);
633 	query = NULL;
634 
635 	if (pgsql_result) {
636 		status = PQresultStatus(pgsql_result);
637 	} else {
638 		status = (ExecStatusType) PQstatus(H->server);
639 	}
640 
641 	if (status == PGRES_COPY_IN && pgsql_result) {
642 		int command_failed = 0;
643 		size_t buffer_len = 0;
644 		zval *tmp;
645 
646 		PQclear(pgsql_result);
647 		ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), tmp) {
648 			size_t query_len;
649 			if (!try_convert_to_string(tmp)) {
650 				efree(query);
651 				RETURN_THROWS();
652 			}
653 
654 			if (buffer_len < Z_STRLEN_P(tmp)) {
655 				buffer_len = Z_STRLEN_P(tmp);
656 				query = erealloc(query, buffer_len + 2); /* room for \n\0 */
657 			}
658 			memcpy(query, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
659 			query_len = Z_STRLEN_P(tmp);
660 			if (query[query_len - 1] != '\n') {
661 				query[query_len++] = '\n';
662 			}
663 			query[query_len] = '\0';
664 			if (PQputCopyData(H->server, query, query_len) != 1) {
665 				efree(query);
666 				pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
667 				PDO_HANDLE_DBH_ERR();
668 				RETURN_FALSE;
669 			}
670 		} ZEND_HASH_FOREACH_END();
671 		if (query) {
672 			efree(query);
673 		}
674 
675 		if (PQputCopyEnd(H->server, NULL) != 1) {
676 			pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
677 			PDO_HANDLE_DBH_ERR();
678 			RETURN_FALSE;
679 		}
680 
681 		while ((pgsql_result = PQgetResult(H->server))) {
682 			if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
683 				pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
684 				command_failed = 1;
685 			}
686 			PQclear(pgsql_result);
687 		}
688 
689 		PDO_HANDLE_DBH_ERR();
690 		RETURN_BOOL(!command_failed);
691 	} else {
692 		pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
693 		PQclear(pgsql_result);
694 		PDO_HANDLE_DBH_ERR();
695 		RETURN_FALSE;
696 	}
697 }
698 /* }}} */
699 
700 /* {{{ Returns true if the copy worked fine or false if error */
PHP_METHOD(PDO_PGSql_Ext,pgsqlCopyFromFile)701 PHP_METHOD(PDO_PGSql_Ext, pgsqlCopyFromFile)
702 {
703 	pdo_dbh_t *dbh;
704 	pdo_pgsql_db_handle *H;
705 
706 	char *table_name, *filename, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
707 	size_t  table_name_len, filename_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
708 	char *query;
709 	PGresult *pgsql_result;
710 	ExecStatusType status;
711 	php_stream *stream;
712 
713 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sp|sss!",
714 				&table_name, &table_name_len, &filename, &filename_len,
715 				&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
716 		RETURN_THROWS();
717 	}
718 
719 	/* Obtain db Handler */
720 	dbh = Z_PDO_DBH_P(ZEND_THIS);
721 	PDO_CONSTRUCT_CHECK;
722 	PDO_DBH_CLEAR_ERR();
723 
724 	stream = php_stream_open_wrapper_ex(filename, "rb", 0, NULL, FG(default_context));
725 	if (!stream) {
726 		pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to open the file");
727 		PDO_HANDLE_DBH_ERR();
728 		RETURN_FALSE;
729 	}
730 
731 	/* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
732 	if (pg_fields) {
733 		spprintf(&query, 0, "COPY %s (%s) FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
734 	} else {
735 		spprintf(&query, 0, "COPY %s FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
736 	}
737 
738 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
739 
740 	while ((pgsql_result = PQgetResult(H->server))) {
741 		PQclear(pgsql_result);
742 	}
743 	pgsql_result = PQexec(H->server, query);
744 
745 	efree(query);
746 
747 	if (pgsql_result) {
748 		status = PQresultStatus(pgsql_result);
749 	} else {
750 		status = (ExecStatusType) PQstatus(H->server);
751 	}
752 
753 	if (status == PGRES_COPY_IN && pgsql_result) {
754 		char *buf;
755 		int command_failed = 0;
756 		size_t line_len = 0;
757 
758 		PQclear(pgsql_result);
759 		while ((buf = php_stream_get_line(stream, NULL, 0, &line_len)) != NULL) {
760 			if (PQputCopyData(H->server, buf, line_len) != 1) {
761 				efree(buf);
762 				pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
763 				php_stream_close(stream);
764 				PDO_HANDLE_DBH_ERR();
765 				RETURN_FALSE;
766 			}
767 			efree(buf);
768 		}
769 		php_stream_close(stream);
770 
771 		if (PQputCopyEnd(H->server, NULL) != 1) {
772 			pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
773 			PDO_HANDLE_DBH_ERR();
774 			RETURN_FALSE;
775 		}
776 
777 		while ((pgsql_result = PQgetResult(H->server))) {
778 			if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
779 				pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
780 				command_failed = 1;
781 			}
782 			PQclear(pgsql_result);
783 		}
784 
785 		PDO_HANDLE_DBH_ERR();
786 		RETURN_BOOL(!command_failed);
787 	} else {
788 		php_stream_close(stream);
789 		pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
790 		PQclear(pgsql_result);
791 		PDO_HANDLE_DBH_ERR();
792 		RETURN_FALSE;
793 	}
794 }
795 /* }}} */
796 
797 
798 /* {{{ Returns true if the copy worked fine or false if error */
PHP_METHOD(PDO_PGSql_Ext,pgsqlCopyToFile)799 PHP_METHOD(PDO_PGSql_Ext, pgsqlCopyToFile)
800 {
801 	pdo_dbh_t *dbh;
802 	pdo_pgsql_db_handle *H;
803 
804 	char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL, *filename = NULL;
805 	size_t table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len, filename_len;
806 	char *query;
807 
808 	PGresult *pgsql_result;
809 	ExecStatusType status;
810 
811 	php_stream *stream;
812 
813 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sp|sss!",
814 					&table_name, &table_name_len, &filename, &filename_len,
815 					&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
816 		RETURN_THROWS();
817 	}
818 
819 	dbh = Z_PDO_DBH_P(ZEND_THIS);
820 	PDO_CONSTRUCT_CHECK;
821 	PDO_DBH_CLEAR_ERR();
822 
823 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
824 
825 	stream = php_stream_open_wrapper_ex(filename, "wb", 0, NULL, FG(default_context));
826 	if (!stream) {
827 		pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to open the file for writing");
828 		PDO_HANDLE_DBH_ERR();
829 		RETURN_FALSE;
830 	}
831 
832 	while ((pgsql_result = PQgetResult(H->server))) {
833 		PQclear(pgsql_result);
834 	}
835 
836 	/* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
837 	if (pg_fields) {
838 		spprintf(&query, 0, "COPY %s (%s) TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
839 	} else {
840 		spprintf(&query, 0, "COPY %s TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
841 	}
842 	pgsql_result = PQexec(H->server, query);
843 	efree(query);
844 
845 	if (pgsql_result) {
846 		status = PQresultStatus(pgsql_result);
847 	} else {
848 		status = (ExecStatusType) PQstatus(H->server);
849 	}
850 
851 	if (status == PGRES_COPY_OUT && pgsql_result) {
852 		PQclear(pgsql_result);
853 		while (1) {
854 			char *csv = NULL;
855 			int ret = PQgetCopyData(H->server, &csv, 0);
856 
857 			if (ret == -1) {
858 				break; /* done */
859 			} else if (ret > 0) {
860 				if (php_stream_write(stream, csv, ret) != (size_t)ret) {
861 					pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to write to file");
862 					PQfreemem(csv);
863 					php_stream_close(stream);
864 					PDO_HANDLE_DBH_ERR();
865 					RETURN_FALSE;
866 				} else {
867 					PQfreemem(csv);
868 				}
869 			} else {
870 				pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
871 				php_stream_close(stream);
872 				PDO_HANDLE_DBH_ERR();
873 				RETURN_FALSE;
874 			}
875 		}
876 		php_stream_close(stream);
877 
878 		while ((pgsql_result = PQgetResult(H->server))) {
879 			PQclear(pgsql_result);
880 		}
881 		RETURN_TRUE;
882 	} else {
883 		php_stream_close(stream);
884 		pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
885 		PQclear(pgsql_result);
886 		PDO_HANDLE_DBH_ERR();
887 		RETURN_FALSE;
888 	}
889 }
890 /* }}} */
891 
892 /* {{{ Returns true if the copy worked fine or false if error */
PHP_METHOD(PDO_PGSql_Ext,pgsqlCopyToArray)893 PHP_METHOD(PDO_PGSql_Ext, pgsqlCopyToArray)
894 {
895 	pdo_dbh_t *dbh;
896 	pdo_pgsql_db_handle *H;
897 
898 	char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
899 	size_t table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
900 	char *query;
901 
902 	PGresult *pgsql_result;
903 	ExecStatusType status;
904 
905 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|sss!",
906 		&table_name, &table_name_len,
907 		&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
908 		RETURN_THROWS();
909 	}
910 
911 	dbh = Z_PDO_DBH_P(ZEND_THIS);
912 	PDO_CONSTRUCT_CHECK;
913 	PDO_DBH_CLEAR_ERR();
914 
915 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
916 
917 	while ((pgsql_result = PQgetResult(H->server))) {
918 		PQclear(pgsql_result);
919 	}
920 
921 	/* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
922 	if (pg_fields) {
923 		spprintf(&query, 0, "COPY %s (%s) TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
924 	} else {
925 		spprintf(&query, 0, "COPY %s TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
926 	}
927 	pgsql_result = PQexec(H->server, query);
928 	efree(query);
929 
930 	if (pgsql_result) {
931 		status = PQresultStatus(pgsql_result);
932 	} else {
933 		status = (ExecStatusType) PQstatus(H->server);
934 	}
935 
936 	if (status == PGRES_COPY_OUT && pgsql_result) {
937 		PQclear(pgsql_result);
938                 array_init(return_value);
939 
940 		while (1) {
941 			char *csv = NULL;
942 			int ret = PQgetCopyData(H->server, &csv, 0);
943 			if (ret == -1) {
944 				break; /* copy done */
945 			} else if (ret > 0) {
946 				add_next_index_stringl(return_value, csv, ret);
947 				PQfreemem(csv);
948 			} else {
949 				pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
950 				PDO_HANDLE_DBH_ERR();
951 				RETURN_FALSE;
952 			}
953 		}
954 
955 		while ((pgsql_result = PQgetResult(H->server))) {
956 			PQclear(pgsql_result);
957 		}
958 	} else {
959 		pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
960 		PQclear(pgsql_result);
961 		PDO_HANDLE_DBH_ERR();
962 		RETURN_FALSE;
963 	}
964 }
965 /* }}} */
966 
967 
968 /* {{{ Creates a new large object, returning its identifier.  Must be called inside a transaction. */
PHP_METHOD(PDO_PGSql_Ext,pgsqlLOBCreate)969 PHP_METHOD(PDO_PGSql_Ext, pgsqlLOBCreate)
970 {
971 	pdo_dbh_t *dbh;
972 	pdo_pgsql_db_handle *H;
973 	Oid lfd;
974 
975 	ZEND_PARSE_PARAMETERS_NONE();
976 
977 	dbh = Z_PDO_DBH_P(ZEND_THIS);
978 	PDO_CONSTRUCT_CHECK;
979 	PDO_DBH_CLEAR_ERR();
980 
981 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
982 	lfd = lo_creat(H->server, INV_READ|INV_WRITE);
983 
984 	if (lfd != InvalidOid) {
985 		zend_string *buf = strpprintf(0, ZEND_ULONG_FMT, (zend_long) lfd);
986 
987 		RETURN_STR(buf);
988 	}
989 
990 	pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
991 	PDO_HANDLE_DBH_ERR();
992 	RETURN_FALSE;
993 }
994 /* }}} */
995 
996 /* {{{ Opens an existing large object stream.  Must be called inside a transaction. */
PHP_METHOD(PDO_PGSql_Ext,pgsqlLOBOpen)997 PHP_METHOD(PDO_PGSql_Ext, pgsqlLOBOpen)
998 {
999 	pdo_dbh_t *dbh;
1000 	pdo_pgsql_db_handle *H;
1001 	Oid oid;
1002 	int lfd;
1003 	char *oidstr;
1004 	size_t oidstrlen;
1005 	char *modestr = "rb";
1006 	size_t modestrlen;
1007 	int mode = INV_READ;
1008 	char *end_ptr;
1009 
1010 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s|s",
1011 				&oidstr, &oidstrlen, &modestr, &modestrlen)) {
1012 		RETURN_THROWS();
1013 	}
1014 
1015 	oid = (Oid)strtoul(oidstr, &end_ptr, 10);
1016 	if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
1017 		RETURN_FALSE;
1018 	}
1019 
1020 	if (strpbrk(modestr, "+w")) {
1021 		mode = INV_READ|INV_WRITE;
1022 	}
1023 
1024 	dbh = Z_PDO_DBH_P(ZEND_THIS);
1025 	PDO_CONSTRUCT_CHECK;
1026 	PDO_DBH_CLEAR_ERR();
1027 
1028 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
1029 
1030 	lfd = lo_open(H->server, oid, mode);
1031 
1032 	if (lfd >= 0) {
1033 		php_stream *stream = pdo_pgsql_create_lob_stream(ZEND_THIS, lfd, oid);
1034 		if (stream) {
1035 			php_stream_to_zval(stream, return_value);
1036 			return;
1037 		}
1038 	} else {
1039 		pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1040 	}
1041 
1042 	PDO_HANDLE_DBH_ERR();
1043 	RETURN_FALSE;
1044 }
1045 /* }}} */
1046 
1047 /* {{{ Deletes the large object identified by oid.  Must be called inside a transaction. */
PHP_METHOD(PDO_PGSql_Ext,pgsqlLOBUnlink)1048 PHP_METHOD(PDO_PGSql_Ext, pgsqlLOBUnlink)
1049 {
1050 	pdo_dbh_t *dbh;
1051 	pdo_pgsql_db_handle *H;
1052 	Oid oid;
1053 	char *oidstr, *end_ptr;
1054 	size_t oidlen;
1055 
1056 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s",
1057 				&oidstr, &oidlen)) {
1058 		RETURN_THROWS();
1059 	}
1060 
1061 	oid = (Oid)strtoul(oidstr, &end_ptr, 10);
1062 	if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
1063 		RETURN_FALSE;
1064 	}
1065 
1066 	dbh = Z_PDO_DBH_P(ZEND_THIS);
1067 	PDO_CONSTRUCT_CHECK;
1068 	PDO_DBH_CLEAR_ERR();
1069 
1070 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
1071 
1072 	if (1 == lo_unlink(H->server, oid)) {
1073 		RETURN_TRUE;
1074 	}
1075 
1076 	pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1077 	PDO_HANDLE_DBH_ERR();
1078 	RETURN_FALSE;
1079 }
1080 /* }}} */
1081 
1082 /* {{{ Get asynchronous notification */
PHP_METHOD(PDO_PGSql_Ext,pgsqlGetNotify)1083 PHP_METHOD(PDO_PGSql_Ext, pgsqlGetNotify)
1084 {
1085 	pdo_dbh_t *dbh;
1086 	pdo_pgsql_db_handle *H;
1087 	zend_long result_type = PDO_FETCH_USE_DEFAULT;
1088 	zend_long ms_timeout = 0;
1089 	PGnotify *pgsql_notify;
1090 
1091 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "|ll",
1092 				&result_type, &ms_timeout)) {
1093 		RETURN_THROWS();
1094 	}
1095 
1096 	dbh = Z_PDO_DBH_P(ZEND_THIS);
1097 	PDO_CONSTRUCT_CHECK;
1098 
1099 	if (result_type == PDO_FETCH_USE_DEFAULT) {
1100 		result_type = dbh->default_fetch_type;
1101 	}
1102 
1103 	if (result_type != PDO_FETCH_BOTH && result_type != PDO_FETCH_ASSOC && result_type != PDO_FETCH_NUM) {
1104 		zend_argument_value_error(1, "must be one of PDO::FETCH_BOTH, PDO::FETCH_ASSOC, or PDO::FETCH_NUM");
1105 		RETURN_THROWS();
1106 	}
1107 
1108 	if (ms_timeout < 0) {
1109 		zend_argument_value_error(2, "must be greater than or equal to 0");
1110 		RETURN_THROWS();
1111 #ifdef ZEND_ENABLE_ZVAL_LONG64
1112 	} else if (ms_timeout > INT_MAX) {
1113 		php_error_docref(NULL, E_WARNING, "Timeout was shrunk to %d", INT_MAX);
1114 		ms_timeout = INT_MAX;
1115 #endif
1116 	}
1117 
1118 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
1119 
1120 	if (!PQconsumeInput(H->server)) {
1121 		pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1122 		PDO_HANDLE_DBH_ERR();
1123 		RETURN_FALSE;
1124 	}
1125 	pgsql_notify = PQnotifies(H->server);
1126 
1127 	if (ms_timeout && !pgsql_notify) {
1128 		php_pollfd_for_ms(PQsocket(H->server), PHP_POLLREADABLE, (int)ms_timeout);
1129 
1130 		if (!PQconsumeInput(H->server)) {
1131 			pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1132 			PDO_HANDLE_DBH_ERR();
1133 			RETURN_FALSE;
1134 		}
1135 		pgsql_notify = PQnotifies(H->server);
1136 	}
1137 
1138 	if (!pgsql_notify) {
1139 		RETURN_FALSE;
1140 	}
1141 
1142 	array_init(return_value);
1143 	if (result_type == PDO_FETCH_NUM || result_type == PDO_FETCH_BOTH) {
1144 		add_index_string(return_value, 0, pgsql_notify->relname);
1145 		add_index_long(return_value, 1, pgsql_notify->be_pid);
1146 		if (pgsql_notify->extra && pgsql_notify->extra[0]) {
1147 			add_index_string(return_value, 2, pgsql_notify->extra);
1148 		}
1149 	}
1150 	if (result_type == PDO_FETCH_ASSOC || result_type == PDO_FETCH_BOTH) {
1151 		add_assoc_string(return_value, "message", pgsql_notify->relname);
1152 		add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
1153 		if (pgsql_notify->extra && pgsql_notify->extra[0]) {
1154 			add_assoc_string(return_value, "payload", pgsql_notify->extra);
1155 		}
1156 	}
1157 
1158 	PQfreemem(pgsql_notify);
1159 }
1160 /* }}} */
1161 
1162 /* {{{ Get backend(server) pid */
PHP_METHOD(PDO_PGSql_Ext,pgsqlGetPid)1163 PHP_METHOD(PDO_PGSql_Ext, pgsqlGetPid)
1164 {
1165 	pdo_dbh_t *dbh;
1166 	pdo_pgsql_db_handle *H;
1167 
1168 	ZEND_PARSE_PARAMETERS_NONE();
1169 
1170 	dbh = Z_PDO_DBH_P(ZEND_THIS);
1171 	PDO_CONSTRUCT_CHECK;
1172 
1173 	H = (pdo_pgsql_db_handle *)dbh->driver_data;
1174 
1175 	RETURN_LONG(PQbackendPID(H->server));
1176 }
1177 /* }}} */
1178 
pdo_pgsql_get_driver_methods(pdo_dbh_t * dbh,int kind)1179 static const zend_function_entry *pdo_pgsql_get_driver_methods(pdo_dbh_t *dbh, int kind)
1180 {
1181 	switch (kind) {
1182 		case PDO_DBH_DRIVER_METHOD_KIND_DBH:
1183 			return class_PDO_PGSql_Ext_methods;
1184 		default:
1185 			return NULL;
1186 	}
1187 }
1188 
pdo_pgsql_set_attr(pdo_dbh_t * dbh,zend_long attr,zval * val)1189 static bool pdo_pgsql_set_attr(pdo_dbh_t *dbh, zend_long attr, zval *val)
1190 {
1191 	bool bval;
1192 	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
1193 
1194 	switch (attr) {
1195 		case PDO_ATTR_EMULATE_PREPARES:
1196 			if (!pdo_get_bool_param(&bval, val)) {
1197 				return false;
1198 			}
1199 			H->emulate_prepares = bval;
1200 			return true;
1201 		case PDO_PGSQL_ATTR_DISABLE_PREPARES:
1202 			if (!pdo_get_bool_param(&bval, val)) {
1203 				return false;
1204 			}
1205 			H->disable_prepares = bval;
1206 			return true;
1207 		default:
1208 			return false;
1209 	}
1210 }
1211 
1212 static const struct pdo_dbh_methods pgsql_methods = {
1213 	pgsql_handle_closer,
1214 	pgsql_handle_preparer,
1215 	pgsql_handle_doer,
1216 	pgsql_handle_quoter,
1217 	pgsql_handle_begin,
1218 	pgsql_handle_commit,
1219 	pgsql_handle_rollback,
1220 	pdo_pgsql_set_attr,
1221 	pdo_pgsql_last_insert_id,
1222 	pdo_pgsql_fetch_error_func,
1223 	pdo_pgsql_get_attribute,
1224 	pdo_pgsql_check_liveness,	/* check_liveness */
1225 	pdo_pgsql_get_driver_methods,  /* get_driver_methods */
1226 	NULL,
1227 	pgsql_handle_in_transaction,
1228 	NULL /* get_gc */
1229 };
1230 
pdo_pgsql_handle_factory(pdo_dbh_t * dbh,zval * driver_options)1231 static int pdo_pgsql_handle_factory(pdo_dbh_t *dbh, zval *driver_options) /* {{{ */
1232 {
1233 	pdo_pgsql_db_handle *H;
1234 	int ret = 0;
1235 	char *conn_str, *p, *e;
1236 	zend_string *tmp_user, *tmp_pass;
1237 	zend_long connect_timeout = 30;
1238 
1239 	H = pecalloc(1, sizeof(pdo_pgsql_db_handle), dbh->is_persistent);
1240 	dbh->driver_data = H;
1241 
1242 	dbh->skip_param_evt =
1243 		1 << PDO_PARAM_EVT_EXEC_POST |
1244 		1 << PDO_PARAM_EVT_FETCH_PRE |
1245 		1 << PDO_PARAM_EVT_FETCH_POST;
1246 
1247 	H->einfo.errcode = 0;
1248 	H->einfo.errmsg = NULL;
1249 
1250 	/* PostgreSQL wants params in the connect string to be separated by spaces,
1251 	 * if the PDO standard semicolons are used, we convert them to spaces
1252 	 */
1253 	e = (char *) dbh->data_source + strlen(dbh->data_source);
1254 	p = (char *) dbh->data_source;
1255 	while ((p = memchr(p, ';', (e - p)))) {
1256 		*p = ' ';
1257 	}
1258 
1259 	if (driver_options) {
1260 		connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30);
1261 	}
1262 
1263 	/* escape username and password, if provided */
1264 	tmp_user = _pdo_pgsql_escape_credentials(dbh->username);
1265 	tmp_pass = _pdo_pgsql_escape_credentials(dbh->password);
1266 
1267 	/* support both full connection string & connection string + login and/or password */
1268 	if (tmp_user && tmp_pass) {
1269 		spprintf(&conn_str, 0, "%s user='%s' password='%s' connect_timeout=" ZEND_LONG_FMT, (char *) dbh->data_source, ZSTR_VAL(tmp_user), ZSTR_VAL(tmp_pass), connect_timeout);
1270 	} else if (tmp_user) {
1271 		spprintf(&conn_str, 0, "%s user='%s' connect_timeout=" ZEND_LONG_FMT, (char *) dbh->data_source, ZSTR_VAL(tmp_user), connect_timeout);
1272 	} else if (tmp_pass) {
1273 		spprintf(&conn_str, 0, "%s password='%s' connect_timeout=" ZEND_LONG_FMT, (char *) dbh->data_source, ZSTR_VAL(tmp_pass), connect_timeout);
1274 	} else {
1275 		spprintf(&conn_str, 0, "%s connect_timeout=" ZEND_LONG_FMT, (char *) dbh->data_source, connect_timeout);
1276 	}
1277 
1278 	H->server = PQconnectdb(conn_str);
1279 	H->lob_streams = (HashTable *) pemalloc(sizeof(HashTable), dbh->is_persistent);
1280 	zend_hash_init(H->lob_streams, 0, NULL, NULL, 1);
1281 
1282 	if (tmp_user) {
1283 		zend_string_release_ex(tmp_user, 0);
1284 	}
1285 	if (tmp_pass) {
1286 		zend_string_release_ex(tmp_pass, 0);
1287 	}
1288 
1289 	efree(conn_str);
1290 
1291 	if (PQstatus(H->server) != CONNECTION_OK) {
1292 		pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, PHP_PDO_PGSQL_CONNECTION_FAILURE_SQLSTATE);
1293 		goto cleanup;
1294 	}
1295 
1296 	PQsetNoticeProcessor(H->server, (void(*)(void*,const char*))_pdo_pgsql_notice, (void *)&dbh);
1297 
1298 	H->attached = 1;
1299 	H->pgoid = -1;
1300 
1301 	dbh->methods = &pgsql_methods;
1302 	dbh->alloc_own_columns = 1;
1303 	dbh->max_escaped_char_length = 2;
1304 
1305 	ret = 1;
1306 
1307 cleanup:
1308 	dbh->methods = &pgsql_methods;
1309 	if (!ret) {
1310 		pgsql_handle_closer(dbh);
1311 	}
1312 
1313 	return ret;
1314 }
1315 /* }}} */
1316 
1317 const pdo_driver_t pdo_pgsql_driver = {
1318 	PDO_DRIVER_HEADER(pgsql),
1319 	pdo_pgsql_handle_factory
1320 };
1321