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   | Author: Ard Biesheuvel <abies@php.net>                               |
14   +----------------------------------------------------------------------+
15 */
16 
17 #ifdef HAVE_CONFIG_H
18 #include <config.h>
19 #endif
20 
21 #ifndef _GNU_SOURCE
22 # define _GNU_SOURCE
23 #endif
24 
25 #include "php.h"
26 #include "zend_exceptions.h"
27 #include "php_ini.h"
28 #include "ext/standard/info.h"
29 #include "ext/pdo/php_pdo.h"
30 #include "ext/pdo/php_pdo_driver.h"
31 #include "php_pdo_firebird.h"
32 #include "php_pdo_firebird_int.h"
33 #include "pdo_firebird_utils.h"
34 
35 static int php_firebird_alloc_prepare_stmt(pdo_dbh_t*, const zend_string*, XSQLDA*, isc_stmt_handle*,
36 	HashTable*);
37 static bool php_firebird_rollback_transaction(pdo_dbh_t *dbh);
38 
39 const char CHR_LETTER = 1;
40 const char CHR_DIGIT = 2;
41 const char CHR_IDENT = 4;
42 const char CHR_QUOTE = 8;
43 const char CHR_WHITE = 16;
44 const char CHR_HEX = 32;
45 const char CHR_INTRODUCER = 64;
46 
47 static const char classes_array[] = {
48 	/* 000     */ 0,
49 	/* 001     */ 0,
50 	/* 002     */ 0,
51 	/* 003     */ 0,
52 	/* 004     */ 0,
53 	/* 005     */ 0,
54 	/* 006     */ 0,
55 	/* 007     */ 0,
56 	/* 008     */ 0,
57 	/* 009     */ 16, /* CHR_WHITE */
58 	/* 010     */ 16, /* CHR_WHITE */
59 	/* 011     */ 0,
60 	/* 012     */ 0,
61 	/* 013     */ 16, /* CHR_WHITE */
62 	/* 014     */ 0,
63 	/* 015     */ 0,
64 	/* 016     */ 0,
65 	/* 017     */ 0,
66 	/* 018     */ 0,
67 	/* 019     */ 0,
68 	/* 020     */ 0,
69 	/* 021     */ 0,
70 	/* 022     */ 0,
71 	/* 023     */ 0,
72 	/* 024     */ 0,
73 	/* 025     */ 0,
74 	/* 026     */ 0,
75 	/* 027     */ 0,
76 	/* 028     */ 0,
77 	/* 029     */ 0,
78 	/* 030     */ 0,
79 	/* 031     */ 0,
80 	/* 032     */ 16, /* CHR_WHITE */
81 	/* 033  !  */ 0,
82 	/* 034  "  */ 8, /* CHR_QUOTE */
83 	/* 035  #  */ 0,
84 	/* 036  $  */ 4, /* CHR_IDENT */
85 	/* 037  %  */ 0,
86 	/* 038  &  */ 0,
87 	/* 039  '  */ 8, /* CHR_QUOTE */
88 	/* 040  (  */ 0,
89 	/* 041  )  */ 0,
90 	/* 042  *  */ 0,
91 	/* 043  +  */ 0,
92 	/* 044  ,  */ 0,
93 	/* 045  -  */ 0,
94 	/* 046  .  */ 0,
95 	/* 047  /  */ 0,
96 	/* 048  0  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
97 	/* 049  1  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
98 	/* 050  2  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
99 	/* 051  3  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
100 	/* 052  4  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
101 	/* 053  5  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
102 	/* 054  6  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
103 	/* 055  7  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
104 	/* 056  8  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
105 	/* 057  9  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
106 	/* 058  :  */ 0,
107 	/* 059  ;  */ 0,
108 	/* 060  <  */ 0,
109 	/* 061  =  */ 0,
110 	/* 062  >  */ 0,
111 	/* 063  ?  */ 0,
112 	/* 064  @  */ 0,
113 	/* 065  A  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
114 	/* 066  B  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
115 	/* 067  C  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
116 	/* 068  D  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
117 	/* 069  E  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
118 	/* 070  F  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
119 	/* 071  G  */ 5, /* CHR_LETTER | CHR_IDENT */
120 	/* 072  H  */ 5, /* CHR_LETTER | CHR_IDENT */
121 	/* 073  I  */ 5, /* CHR_LETTER | CHR_IDENT */
122 	/* 074  J  */ 5, /* CHR_LETTER | CHR_IDENT */
123 	/* 075  K  */ 5, /* CHR_LETTER | CHR_IDENT */
124 	/* 076  L  */ 5, /* CHR_LETTER | CHR_IDENT */
125 	/* 077  M  */ 5, /* CHR_LETTER | CHR_IDENT */
126 	/* 078  N  */ 5, /* CHR_LETTER | CHR_IDENT */
127 	/* 079  O  */ 5, /* CHR_LETTER | CHR_IDENT */
128 	/* 080  P  */ 5, /* CHR_LETTER | CHR_IDENT */
129 	/* 081  Q  */ 5, /* CHR_LETTER | CHR_IDENT */
130 	/* 082  R  */ 5, /* CHR_LETTER | CHR_IDENT */
131 	/* 083  S  */ 5, /* CHR_LETTER | CHR_IDENT */
132 	/* 084  T  */ 5, /* CHR_LETTER | CHR_IDENT */
133 	/* 085  U  */ 5, /* CHR_LETTER | CHR_IDENT */
134 	/* 086  V  */ 5, /* CHR_LETTER | CHR_IDENT */
135 	/* 087  W  */ 5, /* CHR_LETTER | CHR_IDENT */
136 	/* 088  X  */ 5, /* CHR_LETTER | CHR_IDENT */
137 	/* 089  Y  */ 5, /* CHR_LETTER | CHR_IDENT */
138 	/* 090  Z  */ 5, /* CHR_LETTER | CHR_IDENT */
139 	/* 091  [  */ 0,
140 	/* 092  \  */ 0,
141 	/* 093  ]  */ 0,
142 	/* 094  ^  */ 0,
143 	/* 095  _  */ 68, /* CHR_IDENT | CHR_INTRODUCER */
144 	/* 096  `  */ 0,
145 	/* 097  a  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
146 	/* 098  b  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
147 	/* 099  c  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
148 	/* 100  d  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
149 	/* 101  e  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
150 	/* 102  f  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
151 	/* 103  g  */ 5, /* CHR_LETTER | CHR_IDENT */
152 	/* 104  h  */ 5, /* CHR_LETTER | CHR_IDENT */
153 	/* 105  i  */ 5, /* CHR_LETTER | CHR_IDENT */
154 	/* 106  j  */ 5, /* CHR_LETTER | CHR_IDENT */
155 	/* 107  k  */ 5, /* CHR_LETTER | CHR_IDENT */
156 	/* 108  l  */ 5, /* CHR_LETTER | CHR_IDENT */
157 	/* 109  m  */ 5, /* CHR_LETTER | CHR_IDENT */
158 	/* 110  n  */ 5, /* CHR_LETTER | CHR_IDENT */
159 	/* 111  o  */ 5, /* CHR_LETTER | CHR_IDENT */
160 	/* 112  p  */ 5, /* CHR_LETTER | CHR_IDENT */
161 	/* 113  q  */ 5, /* CHR_LETTER | CHR_IDENT */
162 	/* 114  r  */ 5, /* CHR_LETTER | CHR_IDENT */
163 	/* 115  s  */ 5, /* CHR_LETTER | CHR_IDENT */
164 	/* 116  t  */ 5, /* CHR_LETTER | CHR_IDENT */
165 	/* 117  u  */ 5, /* CHR_LETTER | CHR_IDENT */
166 	/* 118  v  */ 5, /* CHR_LETTER | CHR_IDENT */
167 	/* 119  w  */ 5, /* CHR_LETTER | CHR_IDENT */
168 	/* 120  x  */ 5, /* CHR_LETTER | CHR_IDENT */
169 	/* 121  y  */ 5, /* CHR_LETTER | CHR_IDENT */
170 	/* 122  z  */ 5, /* CHR_LETTER | CHR_IDENT */
171 	/* 123  {  */ 5, /* CHR_LETTER | CHR_IDENT */
172 	/* 124  |  */ 0,
173 	/* 125  }  */ 5, /* CHR_LETTER | CHR_IDENT */
174 	/* 126  ~  */ 0,
175 	/* 127     */ 0
176 };
177 
php_firebird_classes(char idx)178 static inline char php_firebird_classes(char idx)
179 {
180 	unsigned char uidx = (unsigned char) idx;
181 	if (uidx > 127) return 0;
182 	return classes_array[uidx];
183 }
184 
185 typedef enum {
186 	ttNone,
187 	ttWhite,
188 	ttComment,
189 	ttBrokenComment,
190 	ttString,
191 	ttParamMark,
192 	ttIdent,
193 	ttOther
194 } FbTokenType;
195 
php_firebird_get_token(const char ** begin,const char * end)196 static FbTokenType php_firebird_get_token(const char** begin, const char* end)
197 {
198 	FbTokenType ret = ttNone;
199 	const char* p = *begin;
200 
201 	char c = *p++;
202 	switch (c)
203 	{
204 	case ':':
205 	case '?':
206 		ret = ttParamMark;
207 		break;
208 
209 	case '\'':
210 	case '"':
211 		while (p < end)
212 		{
213 			if (*p++ == c)
214 			{
215 				ret = ttString;
216 				break;
217 			}
218 		}
219 		break;
220 
221 	case '/':
222 		if (p < end && *p == '*')
223 		{
224 			ret = ttBrokenComment;
225 			p++;
226 			while (p < end)
227 			{
228 				if (*p++ == '*' && p < end && *p == '/')
229 				{
230 					p++;
231 					ret = ttComment;
232 					break;
233 				}
234 			}
235 		}
236 		else {
237 			ret = ttOther;
238 		}
239 		break;
240 
241 	case '-':
242 		if (p < end && *p == '-')
243 		{
244 			while (++p < end)
245 			{
246 				if (*p == '\r')
247 				{
248 					p++;
249 					if (p < end && *p == '\n')
250 						p++;
251 					break;
252 				}
253 				else if (*p == '\n')
254 					break;
255 			}
256 
257 			ret = ttComment;
258 		}
259 		else
260 			ret = ttOther;
261 		break;
262 
263 	default:
264 		if (php_firebird_classes(c) & CHR_DIGIT)
265 		{
266 			while (p < end && (php_firebird_classes(*p) & CHR_DIGIT))
267 				p++;
268 			ret = ttOther;
269 		}
270 		else if (php_firebird_classes(c) & CHR_IDENT)
271 		{
272 			while (p < end && (php_firebird_classes(*p) & CHR_IDENT))
273 				p++;
274 			ret = ttIdent;
275 		}
276 		else if (php_firebird_classes(c) & CHR_WHITE)
277 		{
278 			while (p < end && (php_firebird_classes(*p) & CHR_WHITE))
279 				p++;
280 			ret = ttWhite;
281 		}
282 		else
283 		{
284 			while (p < end && !(php_firebird_classes(*p) & (CHR_DIGIT | CHR_IDENT | CHR_WHITE)) &&
285 				(*p != '/') && (*p != '-') && (*p != ':') && (*p != '?') &&
286 				(*p != '\'') && (*p != '"'))
287 			{
288 				p++;
289 			}
290 			ret = ttOther;
291 		}
292 	}
293 
294 	*begin = p;
295 	return ret;
296 }
297 
php_firebird_preprocess(const zend_string * sql,char * sql_out,HashTable * named_params)298 static int php_firebird_preprocess(const zend_string* sql, char* sql_out, HashTable* named_params)
299 {
300 	bool passAsIs = 1, execBlock = 0;
301 	zend_long pindex = -1;
302 	char pname[254], ident[253], ident2[253];
303 	unsigned int l;
304 	const char* p = ZSTR_VAL(sql), * end = ZSTR_VAL(sql) + ZSTR_LEN(sql);
305 	const char* start = p;
306 	FbTokenType tok = php_firebird_get_token(&p, end);
307 
308 	const char* i = start;
309 	while (p < end && (tok == ttComment || tok == ttWhite))
310 	{
311 		i = p;
312 		tok = php_firebird_get_token(&p, end);
313 	}
314 
315 	if (p >= end || tok != ttIdent)
316 	{
317 		/* Execute statement preprocess SQL error */
318 		/* Statement expected */
319 		return 0;
320 	}
321 	/* skip leading comments ?? */
322 	start = i;
323 	l = p - i;
324 	/* check the length of the identifier */
325 	/* in Firebird 4.0 it is 63 characters, in previous versions 31 bytes */
326 	if (l > 252) {
327 		return 0;
328 	}
329 	strncpy(ident, i, l);
330 	ident[l] = '\0';
331 	if (!strcasecmp(ident, "EXECUTE"))
332 	{
333 		/* For EXECUTE PROCEDURE and EXECUTE BLOCK statements, named parameters must be processed. */
334 		/* However, in EXECUTE BLOCK this is done in a special way. */
335 		const char* i2 = p;
336 		tok = php_firebird_get_token(&p, end);
337 		while (p < end && (tok == ttComment || tok == ttWhite))
338 		{
339 			i2 = p;
340 			tok = php_firebird_get_token(&p, end);
341 		}
342 		if (p >= end || tok != ttIdent)
343 		{
344 			/* Execute statement preprocess SQL error */
345 			/* Statement expected */
346 			return 0;
347 		}
348 		l = p - i2;
349 		/* check the length of the identifier */
350 		/* in Firebird 4.0 it is 63 characters, in previous versions 31 bytes */
351 		if (l > 252) {
352 			return 0;
353 		}
354 		strncpy(ident2, i2, l);
355 		ident2[l] = '\0';
356 		execBlock = !strcasecmp(ident2, "BLOCK");
357 		passAsIs = 0;
358 	}
359 	else
360 	{
361 		/* Named parameters must be processed in the INSERT, UPDATE, DELETE, MERGE statements. */
362 		/* If CTEs are present in the query, they begin with the WITH keyword. */
363 		passAsIs = strcasecmp(ident, "INSERT") && strcasecmp(ident, "UPDATE") &&
364 			strcasecmp(ident, "DELETE") && strcasecmp(ident, "MERGE") &&
365 			strcasecmp(ident, "SELECT") && strcasecmp(ident, "WITH");
366 	}
367 
368 	if (passAsIs)
369 	{
370 		strcpy(sql_out, ZSTR_VAL(sql));
371 		return 1;
372 	}
373 
374 	strncat(sql_out, start, p - start);
375 
376 	while (p < end)
377 	{
378 		start = p;
379 		tok = php_firebird_get_token(&p, end);
380 		switch (tok)
381 		{
382 		case ttParamMark:
383 			tok = php_firebird_get_token(&p, end);
384 			if (tok == ttIdent /*|| tok == ttString*/)
385 			{
386 				++pindex;
387 				l = p - start;
388 				/* check the length of the identifier */
389 				/* in Firebird 4.0 it is 63 characters, in previous versions 31 bytes */
390 				/* + symbol ":" */
391 				if (l > 253) {
392 					return 0;
393 				}
394 				strncpy(pname, start, l);
395 				pname[l] = '\0';
396 
397 				if (named_params) {
398 					zval tmp;
399 					ZVAL_LONG(&tmp, pindex);
400 					zend_hash_str_update(named_params, pname, l, &tmp);
401 				}
402 
403 				strcat(sql_out, "?");
404 			}
405 			else
406 			{
407 				if (strncmp(start, "?", 1)) {
408 					/* Execute statement preprocess SQL error */
409 					/* Parameter name expected */
410 					return 0;
411 				}
412 				++pindex;
413 				strncat(sql_out, start, p - start);
414 			}
415 			break;
416 
417 		case ttIdent:
418 			if (execBlock)
419 			{
420 				/* In the EXECUTE BLOCK statement, processing must be */
421 				/* carried out up to the keyword AS. */
422 				l = p - start;
423 				/* check the length of the identifier */
424 				/* in Firebird 4.0 it is 63 characters, in previous versions 31 bytes */
425 				if (l > 252) {
426 					return 0;
427 				}
428 				strncpy(ident, start, l);
429 				ident[l] = '\0';
430 				if (!strcasecmp(ident, "AS"))
431 				{
432 					strncat(sql_out, start, end - start);
433 					return 1;
434 				}
435 			}
436 			/* TODO Check this is correct? */
437 			ZEND_FALLTHROUGH;
438 
439 		case ttWhite:
440 		case ttComment:
441 		case ttString:
442 		case ttOther:
443 			strncat(sql_out, start, p - start);
444 			break;
445 
446 		case ttBrokenComment:
447 		{
448 			/* Execute statement preprocess SQL error */
449 			/* Unclosed comment found near ''@1'' */
450 			return 0;
451 		}
452 		break;
453 
454 
455 		case ttNone:
456 			/* Execute statement preprocess SQL error */
457 			return 0;
458 			break;
459 		}
460 	}
461 	return 1;
462 }
463 
464 #if FB_API_VER >= 40
465 /* set coercing a data type */
set_coercing_output_data_types(XSQLDA * sqlda)466 static void set_coercing_output_data_types(XSQLDA* sqlda)
467 {
468 	/* Data types introduced in Firebird 4.0 are difficult to process using the Firebird Legacy API. */
469 	/* These data types include DECFLOAT(16), DECFLOAT(34), INT128 (NUMERIC/DECIMAL(38, x)). */
470 	/* In any case, at this data types can only be mapped to strings. */
471 	/* This function allows you to ensure minimal performance of queries if they contain columns of the above types. */
472 	unsigned int i;
473 	short dtype;
474 	short nullable;
475 	XSQLVAR* var;
476 	unsigned fb_client_version = fb_get_client_version();
477 	unsigned fb_client_major_version = (fb_client_version >> 8) & 0xFF;
478 	for (i=0, var = sqlda->sqlvar; i < sqlda->sqld; i++, var++) {
479 		dtype = (var->sqltype & ~1); /* drop flag bit  */
480 		nullable = (var->sqltype & 1);
481 		switch(dtype) {
482 			case SQL_INT128:
483 				var->sqltype = SQL_VARYING + nullable;
484 				var->sqllen = 46;
485 				var->sqlscale = 0;
486 				break;
487 
488 			case SQL_DEC16:
489 				var->sqltype = SQL_VARYING + nullable;
490 				var->sqllen = 24;
491 				break;
492 
493 			case SQL_DEC34:
494 				var->sqltype = SQL_VARYING + nullable;
495 				var->sqllen = 43;
496 				break;
497 
498 			case SQL_TIMESTAMP_TZ:
499 			    if (fb_client_major_version < 4) {
500 					/* If the client version is below 4.0, then it is impossible to handle time zones natively, */
501 					/* so we convert these types to a string. */
502 					var->sqltype = SQL_VARYING + nullable;
503 					var->sqllen = 58;
504 				}
505 				break;
506 
507 			case SQL_TIME_TZ:
508 				if (fb_client_major_version < 4) {
509 					/* If the client version is below 4.0, then it is impossible to handle time zones natively, */
510 					/* so we convert these types to a string. */
511 					var->sqltype = SQL_VARYING + nullable;
512 					var->sqllen = 46;
513 				}
514 				break;
515 
516 			default:
517 				break;
518 		}
519 	}
520 }
521 #endif
522 
523 /* map driver specific error message to PDO error */
php_firebird_set_error(pdo_dbh_t * dbh,pdo_stmt_t * stmt,const char * state,const size_t state_len,const char * msg,const size_t msg_len)524 void php_firebird_set_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, const char *state, const size_t state_len,
525 	const char *msg, const size_t msg_len) /* {{{ */
526 {
527 	pdo_error_type *const error_code = stmt ? &stmt->error_code : &dbh->error_code;
528 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
529 	pdo_firebird_error_info *einfo = &H->einfo;
530 	int sqlcode = -999;
531 
532 	if (einfo->errmsg) {
533 		pefree(einfo->errmsg, dbh->is_persistent);
534 		einfo->errmsg = NULL;
535 		einfo->errmsg_length = 0;
536 	}
537 
538 	if (H->isc_status && (H->isc_status[0] == 1 && H->isc_status[1] > 0)) {
539 		char buf[512];
540 		size_t buf_size = sizeof(buf), read_len = 0;
541 		ssize_t tmp_len;
542 		const ISC_STATUS *s = H->isc_status;
543 		sqlcode = isc_sqlcode(s);
544 
545 		while ((buf_size > (read_len + 1)) && (tmp_len = fb_interpret(&buf[read_len], (buf_size - read_len - 1), &s)) && tmp_len > 0) {
546 			read_len += tmp_len;
547 			buf[read_len++] = ' ';
548 		}
549 
550 		/* remove last space */
551 		if (read_len) {
552 			buf[read_len--] = '\0';
553 		}
554 
555 		einfo->errmsg_length = read_len;
556 		einfo->errmsg = pestrndup(buf, read_len, dbh->is_persistent);
557 
558 		char sqlstate[sizeof(pdo_error_type)];
559 		fb_sqlstate(sqlstate, H->isc_status);
560 		if (sqlstate != NULL && strlen(sqlstate) < sizeof(pdo_error_type)) {
561 			strcpy(*error_code, sqlstate);
562 			goto end;
563 		}
564 	} else if (msg && msg_len) {
565 		einfo->errmsg_length = msg_len;
566 		einfo->errmsg = pestrndup(msg, einfo->errmsg_length, dbh->is_persistent);
567 	}
568 
569 	if (state && state_len && state_len < sizeof(pdo_error_type)) {
570 		memcpy(*error_code, state, state_len + 1);
571 	} else {
572 		memcpy(*error_code, "HY000", sizeof("HY000"));
573 	}
574 
575 end:
576 	einfo->sqlcode = sqlcode;
577 	if (!dbh->methods) {
578 		pdo_throw_exception(0, einfo->errmsg, error_code);
579 	}
580 }
581 /* }}} */
582 
583 /* called by PDO to close a db handle */
firebird_handle_closer(pdo_dbh_t * dbh)584 static void firebird_handle_closer(pdo_dbh_t *dbh) /* {{{ */
585 {
586 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
587 
588 	if (H->tr) {
589 		if (dbh->auto_commit) {
590 			php_firebird_commit_transaction(dbh, /* retain */ false);
591 		} else {
592 			php_firebird_rollback_transaction(dbh);
593 		}
594 	}
595 	H->in_manually_txn = 0;
596 
597 	if (isc_detach_database(H->isc_status, &H->db)) {
598 		php_firebird_error(dbh);
599 	}
600 
601 	if (H->date_format) {
602 		efree(H->date_format);
603 	}
604 	if (H->time_format) {
605 		efree(H->time_format);
606 	}
607 	if (H->timestamp_format) {
608 		efree(H->timestamp_format);
609 	}
610 
611 	if (H->einfo.errmsg) {
612 		pefree(H->einfo.errmsg, dbh->is_persistent);
613 		H->einfo.errmsg = NULL;
614 	}
615 
616 	pefree(H, dbh->is_persistent);
617 }
618 /* }}} */
619 
620 /* called by PDO to prepare an SQL query */
firebird_handle_preparer(pdo_dbh_t * dbh,zend_string * sql,pdo_stmt_t * stmt,zval * driver_options)621 static bool firebird_handle_preparer(pdo_dbh_t *dbh, zend_string *sql, /* {{{ */
622 	pdo_stmt_t *stmt, zval *driver_options)
623 {
624 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
625 	pdo_firebird_stmt *S = NULL;
626 	HashTable *np;
627 
628 	do {
629 		isc_stmt_handle s = PDO_FIREBIRD_HANDLE_INITIALIZER;
630 		XSQLDA num_sqlda;
631 		static char const info[] = { isc_info_sql_stmt_type };
632 		char result[8];
633 
634 		num_sqlda.version = PDO_FB_SQLDA_VERSION;
635 		num_sqlda.sqln = 1;
636 
637 		ALLOC_HASHTABLE(np);
638 		zend_hash_init(np, 8, NULL, NULL, 0);
639 
640 		/* allocate and prepare statement */
641 		if (!php_firebird_alloc_prepare_stmt(dbh, sql, &num_sqlda, &s, np)) {
642 			break;
643 		}
644 
645 		/* allocate a statement handle struct of the right size (struct out_sqlda is inlined) */
646 		S = ecalloc(1, sizeof(*S)-sizeof(XSQLDA) + XSQLDA_LENGTH(num_sqlda.sqld));
647 		S->H = H;
648 		S->stmt = s;
649 		S->out_sqlda.version = PDO_FB_SQLDA_VERSION;
650 		S->out_sqlda.sqln = stmt->column_count = num_sqlda.sqld;
651 		S->named_params = np;
652 
653 		/* determine the statement type */
654 		if (isc_dsql_sql_info(H->isc_status, &s, sizeof(info), const_cast(info), sizeof(result),
655 				result)) {
656 			break;
657 		}
658 		S->statement_type = result[3];
659 
660 		/* fill the output sqlda with information about the prepared query */
661 		if (isc_dsql_describe(H->isc_status, &s, PDO_FB_SQLDA_VERSION, &S->out_sqlda)) {
662 			php_firebird_error(dbh);
663 			break;
664 		}
665 
666 #if FB_API_VER >= 40
667 		/* set coercing a data type */
668 		set_coercing_output_data_types(&S->out_sqlda);
669 #endif
670 
671 		/* allocate the input descriptors */
672 		if (isc_dsql_describe_bind(H->isc_status, &s, PDO_FB_SQLDA_VERSION, &num_sqlda)) {
673 			break;
674 		}
675 
676 		if (num_sqlda.sqld) {
677 			S->in_sqlda = ecalloc(1,XSQLDA_LENGTH(num_sqlda.sqld));
678 			S->in_sqlda->version = PDO_FB_SQLDA_VERSION;
679 			S->in_sqlda->sqln = num_sqlda.sqld;
680 
681 			if (isc_dsql_describe_bind(H->isc_status, &s, PDO_FB_SQLDA_VERSION, S->in_sqlda)) {
682 				break;
683 			}
684 
685 			/* make all parameters nullable */
686 			unsigned int i;
687 			XSQLVAR* var;
688 			for (i = 0, var = S->in_sqlda->sqlvar; i < S->in_sqlda->sqld; i++, var++) {
689 				/* The low bit of sqltype indicates that the parameter can take a NULL value */
690 				var->sqltype |= 1;
691 			}
692 		}
693 
694 		stmt->driver_data = S;
695 		stmt->methods = &firebird_stmt_methods;
696 		stmt->supports_placeholders = PDO_PLACEHOLDER_POSITIONAL;
697 
698 		return true;
699 
700 	} while (0);
701 
702 	php_firebird_error(dbh);
703 
704 	zend_hash_destroy(np);
705 	FREE_HASHTABLE(np);
706 
707 	if (S) {
708 		if (S->in_sqlda) {
709 			efree(S->in_sqlda);
710 		}
711 		efree(S);
712 	}
713 
714 	return false;
715 }
716 /* }}} */
717 
718 /* called by PDO to execute a statement that doesn't produce a result set */
firebird_handle_doer(pdo_dbh_t * dbh,const zend_string * sql)719 static zend_long firebird_handle_doer(pdo_dbh_t *dbh, const zend_string *sql) /* {{{ */
720 {
721 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
722 	isc_stmt_handle stmt = PDO_FIREBIRD_HANDLE_INITIALIZER;
723 	static char const info_count[] = { isc_info_sql_records };
724 	char result[64];
725 	int ret = 0;
726 	XSQLDA in_sqlda, out_sqlda;
727 
728 	/* TODO no placeholders in exec() for now */
729 	in_sqlda.version = out_sqlda.version = PDO_FB_SQLDA_VERSION;
730 	in_sqlda.sqld = out_sqlda.sqld = 0;
731 	out_sqlda.sqln = 1;
732 
733 	/* allocate and prepare statement */
734 	if (!php_firebird_alloc_prepare_stmt(dbh, sql, &out_sqlda, &stmt, 0)) {
735 		return -1;
736 	}
737 
738 	/* execute the statement */
739 	if (isc_dsql_execute2(H->isc_status, &H->tr, &stmt, PDO_FB_SQLDA_VERSION, &in_sqlda, &out_sqlda)) {
740 		php_firebird_error(dbh);
741 		ret = -1;
742 		goto free_statement;
743 	}
744 
745 	/* find out how many rows were affected */
746 	if (isc_dsql_sql_info(H->isc_status, &stmt, sizeof(info_count), const_cast(info_count),
747 			sizeof(result),	result)) {
748 		php_firebird_error(dbh);
749 		ret = -1;
750 		goto free_statement;
751 	}
752 
753 	if (result[0] == isc_info_sql_records) {
754 		unsigned i = 3, result_size = isc_vax_integer(&result[1],2);
755 
756 		if (result_size > sizeof(result)) {
757 			ret = -1;
758 			goto free_statement;
759 		}
760 		while (result[i] != isc_info_end && i < result_size) {
761 			short len = (short)isc_vax_integer(&result[i+1],2);
762 			/* bail out on bad len */
763 			if (len != 1 && len != 2 && len != 4) {
764 				ret = -1;
765 				goto free_statement;
766 			}
767 			if (result[i] != isc_info_req_select_count) {
768 				ret += isc_vax_integer(&result[i+3],len);
769 			}
770 			i += len+3;
771 		}
772 	}
773 
774 	if (dbh->auto_commit && !H->in_manually_txn) {
775 		if (!php_firebird_commit_transaction(dbh, /* retain */ true)) {
776 			ret = -1;
777 		}
778 	}
779 
780 free_statement:
781 
782 	if (isc_dsql_free_statement(H->isc_status, &stmt, DSQL_drop)) {
783 		php_firebird_error(dbh);
784 	}
785 
786 	return ret;
787 }
788 /* }}} */
789 
790 /* called by the PDO SQL parser to add quotes to values that are copied into SQL */
firebird_handle_quoter(pdo_dbh_t * dbh,const zend_string * unquoted,enum pdo_param_type paramtype)791 static zend_string* firebird_handle_quoter(pdo_dbh_t *dbh, const zend_string *unquoted, enum pdo_param_type paramtype)
792 {
793 	int qcount = 0;
794 	char const *co, *l, *r;
795 	char *c;
796 	size_t quotedlen;
797 	zend_string *quoted_str;
798 
799 	if (ZSTR_LEN(unquoted) == 0) {
800 		return ZSTR_INIT_LITERAL("''", 0);
801 	}
802 
803 	/* Firebird only requires single quotes to be doubled if string lengths are used */
804 	/* count the number of ' characters */
805 	for (co = ZSTR_VAL(unquoted); (co = strchr(co,'\'')); qcount++, co++);
806 
807 	quotedlen = ZSTR_LEN(unquoted) + qcount + 2;
808 	quoted_str = zend_string_alloc(quotedlen, 0);
809 	c = ZSTR_VAL(quoted_str);
810 	*c++ = '\'';
811 
812 	/* foreach (chunk that ends in a quote) */
813 	for (l = ZSTR_VAL(unquoted); (r = strchr(l,'\'')); l = r+1) {
814 		strncpy(c, l, r-l+1);
815 		c += (r-l+1);
816 		/* add the second quote */
817 		*c++ = '\'';
818 	}
819 
820 	/* copy the remainder */
821 	strncpy(c, l, quotedlen-(c-ZSTR_VAL(quoted_str))-1);
822 	ZSTR_VAL(quoted_str)[quotedlen-1] = '\'';
823 	ZSTR_VAL(quoted_str)[quotedlen]   = '\0';
824 
825 	return quoted_str;
826 }
827 /* }}} */
828 
829 /* php_firebird_begin_transaction */
php_firebird_begin_transaction(pdo_dbh_t * dbh,bool is_auto_commit_txn)830 static bool php_firebird_begin_transaction(pdo_dbh_t *dbh, bool is_auto_commit_txn) /* {{{ */
831 {
832 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
833 
834 	/* isc_xxx are all 1 byte. */
835 	char tpb[4] = { isc_tpb_version3 };
836 	size_t tpb_size;
837 
838 	/* access mode. writable or readonly */
839 	tpb[1] = H->is_writable_txn ? isc_tpb_write : isc_tpb_read;
840 
841 	if (is_auto_commit_txn) {
842 		/*
843 		 * In autocommit mode, we need to always read the latest information, so we set `read committed`.
844 		 */
845 		tpb[2] = isc_tpb_read_committed;
846 		/* Ignore indeterminate data from other transactions. This option only required with `read committed`. */
847 		tpb[3] = isc_tpb_rec_version;
848 		tpb_size = 4;
849 	} else {
850 		switch (H->txn_isolation_level) {
851 			/*
852 			* firebird's `read committed` has the option to wait until other transactions
853 			* commit or rollback if there is indeterminate data.
854 			* Introducing too many configuration values at once can cause confusion, so
855 			* we don't support in PDO that feature yet.
856 			*/
857 			case PDO_FB_READ_COMMITTED:
858 				tpb[2] = isc_tpb_read_committed;
859 				/* Ignore indeterminate data from other transactions. This option only required with `read committed`. */
860 				tpb[3] = isc_tpb_rec_version;
861 				tpb_size = 4;
862 				break;
863 
864 			case PDO_FB_SERIALIZABLE:
865 				tpb[2] = isc_tpb_consistency;
866 				tpb_size = 3;
867 				break;
868 
869 			case PDO_FB_REPEATABLE_READ:
870 			default:
871 				tpb[2] = isc_tpb_concurrency;
872 				tpb_size = 3;
873 				break;
874 		}
875 	}
876 
877 	if (isc_start_transaction(H->isc_status, &H->tr, 1, &H->db, tpb_size, tpb)) {
878 		php_firebird_error(dbh);
879 		return false;
880 	}
881 	return true;
882 }
883 /* }}} */
884 
885 /* called by PDO to start a transaction */
firebird_handle_manually_begin(pdo_dbh_t * dbh)886 static bool firebird_handle_manually_begin(pdo_dbh_t *dbh) /* {{{ */
887 {
888 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
889 
890 	/**
891 	 * If in autocommit mode and in transaction, we will need to close the transaction once.
892 	 */
893 	if (dbh->auto_commit && H->tr) {
894 		if (!php_firebird_commit_transaction(dbh, /* retain */ false)) {
895 			return false;
896 		}
897 	}
898 
899 	if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ false)) {
900 		return false;
901 	}
902 	H->in_manually_txn = 1;
903 	return true;
904 }
905 /* }}} */
906 
907 /* php_firebird_commit_transaction */
php_firebird_commit_transaction(pdo_dbh_t * dbh,bool retain)908 bool php_firebird_commit_transaction(pdo_dbh_t *dbh, bool retain) /* {{{ */
909 {
910 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
911 
912 	/**
913 	 * `retaining` keeps the transaction open without closing it.
914 	 *
915 	 * firebird needs to always have a transaction open to emulate autocommit mode,
916 	 * and in autocommit mode it keeps the transaction open.
917 	 *
918 	 * Same as close and then begin again, but use retain to save overhead.
919 	 */
920 	if (retain) {
921 		if (isc_commit_retaining(H->isc_status, &H->tr)) {
922 			php_firebird_error(dbh);
923 			return false;
924 		}
925 	} else {
926 		if (isc_commit_transaction(H->isc_status, &H->tr)) {
927 			php_firebird_error(dbh);
928 			return false;
929 		}
930 	}
931 	return true;
932 }
933 /* }}} */
934 
935 /* called by PDO to commit a transaction */
firebird_handle_manually_commit(pdo_dbh_t * dbh)936 static bool firebird_handle_manually_commit(pdo_dbh_t *dbh) /* {{{ */
937 {
938 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
939 	if (!php_firebird_commit_transaction(dbh, /*release*/ false)) {
940 		return false;
941 	}
942 
943 	/**
944 	 * If in autocommit mode, begin the transaction again
945 	 * Reopen instead of retain because isolation level may change
946 	 */
947 	if (dbh->auto_commit) {
948 		if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ true)) {
949 			return false;
950 		}
951 	}
952 	H->in_manually_txn = 0;
953 	return true;
954 }
955 /* }}} */
956 
957 /* php_firebird_rollback_transaction */
php_firebird_rollback_transaction(pdo_dbh_t * dbh)958 static bool php_firebird_rollback_transaction(pdo_dbh_t *dbh) /* {{{ */
959 {
960 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
961 
962 	if (isc_rollback_transaction(H->isc_status, &H->tr)) {
963 		php_firebird_error(dbh);
964 		return false;
965 	}
966 	return true;
967 }
968 /* }}} */
969 
970 /* called by PDO to rollback a transaction */
firebird_handle_manually_rollback(pdo_dbh_t * dbh)971 static bool firebird_handle_manually_rollback(pdo_dbh_t *dbh) /* {{{ */
972 {
973 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
974 
975 	if (!php_firebird_rollback_transaction(dbh)) {
976 		return false;
977 	}
978 
979 	/**
980 	 * If in autocommit mode, begin the transaction again
981 	 * Reopen instead of retain because isolation level may change
982 	 */
983 	if (dbh->auto_commit) {
984 		if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ true)) {
985 			return false;
986 		}
987 	}
988 	H->in_manually_txn = 0;
989 	return true;
990 }
991 /* }}} */
992 
993 /* used by prepare and exec to allocate a statement handle and prepare the SQL */
php_firebird_alloc_prepare_stmt(pdo_dbh_t * dbh,const zend_string * sql,XSQLDA * out_sqlda,isc_stmt_handle * s,HashTable * named_params)994 static int php_firebird_alloc_prepare_stmt(pdo_dbh_t *dbh, const zend_string *sql,
995 	XSQLDA *out_sqlda, isc_stmt_handle *s, HashTable *named_params)
996 {
997 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
998 	char *new_sql;
999 
1000 	/* allocate the statement */
1001 	if (isc_dsql_allocate_statement(H->isc_status, &H->db, s)) {
1002 		php_firebird_error(dbh);
1003 		return 0;
1004 	}
1005 
1006 	/* in order to support named params, which Firebird itself doesn't,
1007 	   we need to replace :foo by ?, and store the name we just replaced */
1008 	new_sql = emalloc(ZSTR_LEN(sql)+1);
1009 	new_sql[0] = '\0';
1010 	if (!php_firebird_preprocess(sql, new_sql, named_params)) {
1011 		php_firebird_error_with_info(dbh, "07000", strlen("07000"), NULL, 0);
1012 		efree(new_sql);
1013 		return 0;
1014 	}
1015 
1016 	/* prepare the statement */
1017 	if (isc_dsql_prepare(H->isc_status, &H->tr, s, 0, new_sql, H->sql_dialect, out_sqlda)) {
1018 		php_firebird_error(dbh);
1019 		efree(new_sql);
1020 		return 0;
1021 	}
1022 
1023 	efree(new_sql);
1024 	return 1;
1025 }
1026 
1027 /* called by PDO to set a driver-specific dbh attribute */
pdo_firebird_set_attribute(pdo_dbh_t * dbh,zend_long attr,zval * val)1028 static bool pdo_firebird_set_attribute(pdo_dbh_t *dbh, zend_long attr, zval *val) /* {{{ */
1029 {
1030 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
1031 	bool bval;
1032 	zend_long lval;
1033 
1034 	switch (attr) {
1035 		case PDO_ATTR_AUTOCOMMIT:
1036 			{
1037 				if (!pdo_get_bool_param(&bval, val)) {
1038 					return false;
1039 				}
1040 
1041 				if (H->in_manually_txn) {
1042 					/* change auto commit mode with an open transaction is illegal, because
1043 						we won't know what to do with it */
1044 					pdo_raise_impl_error(dbh, NULL, "HY000", "Cannot change autocommit mode while a transaction is already open");
1045 					return false;
1046 				}
1047 
1048 				/* ignore if the new value equals the old one */
1049 				if (dbh->auto_commit ^ bval) {
1050 					if (bval) {
1051 						/*
1052 						 * change to auto commit mode.
1053 						 * If the transaction is not started, start it.
1054 						 */
1055 						if (!H->tr) {
1056 							if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ true)) {
1057 								return false;
1058 							}
1059 						}
1060 					} else {
1061 						/*
1062 						 * change to not auto commit mode.
1063 						 * close the transaction if exists.
1064 						 */
1065 						if (H->tr) {
1066 							if (!php_firebird_commit_transaction(dbh, /* retain */ false)) {
1067 								return false;
1068 							}
1069 						}
1070 					}
1071 					dbh->auto_commit = bval;
1072 				}
1073 			}
1074 			return true;
1075 
1076 		case PDO_ATTR_FETCH_TABLE_NAMES:
1077 			if (!pdo_get_bool_param(&bval, val)) {
1078 				return false;
1079 			}
1080 			H->fetch_table_names = bval;
1081 			return true;
1082 
1083 		case PDO_FB_ATTR_DATE_FORMAT:
1084 			{
1085 				zend_string *str = zval_try_get_string(val);
1086 				if (UNEXPECTED(!str)) {
1087 					return false;
1088 				}
1089 				if (H->date_format) {
1090 					efree(H->date_format);
1091 				}
1092 				spprintf(&H->date_format, 0, "%s", ZSTR_VAL(str));
1093 				zend_string_release_ex(str, 0);
1094 			}
1095 			return true;
1096 
1097 		case PDO_FB_ATTR_TIME_FORMAT:
1098 			{
1099 				zend_string *str = zval_try_get_string(val);
1100 				if (UNEXPECTED(!str)) {
1101 					return false;
1102 				}
1103 				if (H->time_format) {
1104 					efree(H->time_format);
1105 				}
1106 				spprintf(&H->time_format, 0, "%s", ZSTR_VAL(str));
1107 				zend_string_release_ex(str, 0);
1108 			}
1109 			return true;
1110 
1111 		case PDO_FB_ATTR_TIMESTAMP_FORMAT:
1112 			{
1113 				zend_string *str = zval_try_get_string(val);
1114 				if (UNEXPECTED(!str)) {
1115 					return false;
1116 				}
1117 				if (H->timestamp_format) {
1118 					efree(H->timestamp_format);
1119 				}
1120 				spprintf(&H->timestamp_format, 0, "%s", ZSTR_VAL(str));
1121 				zend_string_release_ex(str, 0);
1122 			}
1123 			return true;
1124 
1125 		case PDO_FB_TRANSACTION_ISOLATION_LEVEL:
1126 			{
1127 				if (!pdo_get_long_param(&lval, val)) {
1128 					return false;
1129 				}
1130 
1131 				if (H->in_manually_txn) {
1132 					pdo_raise_impl_error(dbh, NULL, "HY000", "Cannot change transaction isolation level while a transaction is already open");
1133 					return false;
1134 				}
1135 
1136 				/* ignore if the new value equals the old one */
1137 				if (H->txn_isolation_level != lval) {
1138 					if (lval == PDO_FB_READ_COMMITTED ||
1139 						lval == PDO_FB_REPEATABLE_READ ||
1140 						lval == PDO_FB_SERIALIZABLE
1141 					) {
1142 						/*
1143 						 * Autocommit mode is always read-committed, so this setting is used the next time
1144 						 * a manual transaction starts. Therefore, there is no need to immediately reopen the transaction.
1145 						 */
1146 						H->txn_isolation_level = lval;
1147 					} else {
1148 						zend_value_error("Pdo\\Firebird::TRANSACTION_ISOLATION_LEVEL must be a valid transaction isolation level "
1149 							"(Pdo\\Firebird::READ_COMMITTED, Pdo\\Firebird::REPEATABLE_READ, or Pdo\\Firebird::SERIALIZABLE)");
1150 						return false;
1151 					}
1152 				}
1153 			}
1154 			return true;
1155 
1156 		case PDO_FB_WRITABLE_TRANSACTION:
1157 			{
1158 				if (!pdo_get_bool_param(&bval, val)) {
1159 					return false;
1160 				}
1161 
1162 				if (H->in_manually_txn) {
1163 					pdo_raise_impl_error(dbh, NULL, "HY000", "Cannot change access mode while a transaction is already open");
1164 					return false;
1165 				}
1166 
1167 				/* ignore if the new value equals the old one */
1168 				if (H->is_writable_txn != bval) {
1169 					H->is_writable_txn = bval;
1170 					if (dbh->auto_commit) {
1171 						if (H->tr) {
1172 							if (!php_firebird_commit_transaction(dbh, /* retain */ false)) {
1173 								/* In case of error, revert the setting */
1174 								H->is_writable_txn = !bval;
1175 								return false;
1176 							}
1177 						}
1178 						if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ true)) {
1179 							/* In case of error, revert the setting */
1180 							H->is_writable_txn = !bval;
1181 							return false;
1182 						}
1183 					}
1184 				}
1185 			}
1186 			return true;
1187 	}
1188 	return false;
1189 }
1190 /* }}} */
1191 
1192 #define INFO_BUF_LEN 512
1193 
1194 /* callback to used to report database server info */
php_firebird_info_cb(void * arg,char const * s)1195 static void php_firebird_info_cb(void *arg, char const *s) /* {{{ */
1196 {
1197 	if (arg) {
1198 		if (*(char*)arg) { /* second call */
1199 			strlcat(arg, " ", INFO_BUF_LEN);
1200 		}
1201 		strlcat(arg, s, INFO_BUF_LEN);
1202 	}
1203 }
1204 /* }}} */
1205 
1206 /* called by PDO to get a driver-specific dbh attribute */
pdo_firebird_get_attribute(pdo_dbh_t * dbh,zend_long attr,zval * val)1207 static int pdo_firebird_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *val) /* {{{ */
1208 {
1209 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
1210 
1211 	switch (attr) {
1212 		char tmp[INFO_BUF_LEN];
1213 
1214 		case PDO_ATTR_AUTOCOMMIT:
1215 			ZVAL_BOOL(val,dbh->auto_commit);
1216 			return 1;
1217 
1218 		case PDO_ATTR_CONNECTION_STATUS:
1219 			ZVAL_BOOL(val, !isc_version(&H->db, php_firebird_info_cb, NULL));
1220 			return 1;
1221 
1222 		case PDO_ATTR_CLIENT_VERSION: {
1223 #if defined(__GNUC__) || defined(PHP_WIN32)
1224 			info_func_t info_func = NULL;
1225 #ifdef __GNUC__
1226 			info_func = (info_func_t)dlsym(RTLD_DEFAULT, "isc_get_client_version");
1227 #else
1228 			HMODULE l = GetModuleHandle("fbclient");
1229 
1230 			if (!l) {
1231 				break;
1232 			}
1233 			info_func = (info_func_t)GetProcAddress(l, "isc_get_client_version");
1234 #endif
1235 			if (info_func) {
1236 				info_func(tmp);
1237 				ZVAL_STRING(val, tmp);
1238 			}
1239 #else
1240 			ZVAL_NULL(val);
1241 #endif
1242 			}
1243 			return 1;
1244 
1245 		case PDO_ATTR_SERVER_VERSION:
1246 		case PDO_ATTR_SERVER_INFO:
1247 			*tmp = 0;
1248 
1249 			if (!isc_version(&H->db, php_firebird_info_cb, (void*)tmp)) {
1250 				ZVAL_STRING(val, tmp);
1251 				return 1;
1252 			}
1253 			return -1;
1254 
1255 		case PDO_ATTR_FETCH_TABLE_NAMES:
1256 			ZVAL_BOOL(val, H->fetch_table_names);
1257 			return 1;
1258 
1259 		case PDO_FB_ATTR_DATE_FORMAT:
1260 			ZVAL_STRING(val, H->date_format ? H->date_format : PDO_FB_DEF_DATE_FMT);
1261 			return 1;
1262 
1263 		case PDO_FB_ATTR_TIME_FORMAT:
1264 			ZVAL_STRING(val, H->time_format ? H->time_format : PDO_FB_DEF_TIME_FMT);
1265 			return 1;
1266 
1267 		case PDO_FB_ATTR_TIMESTAMP_FORMAT:
1268 			ZVAL_STRING(val, H->timestamp_format ? H->timestamp_format : PDO_FB_DEF_TIMESTAMP_FMT);
1269 			return 1;
1270 
1271 		case PDO_FB_TRANSACTION_ISOLATION_LEVEL:
1272 			ZVAL_LONG(val, H->txn_isolation_level);
1273 			return 1;
1274 
1275 		case PDO_FB_WRITABLE_TRANSACTION:
1276 			ZVAL_BOOL(val, H->is_writable_txn);
1277 			return 1;
1278 	}
1279 	return 0;
1280 }
1281 /* }}} */
1282 
1283 /* called by PDO to check liveness */
pdo_firebird_check_liveness(pdo_dbh_t * dbh)1284 static zend_result pdo_firebird_check_liveness(pdo_dbh_t *dbh) /* {{{ */
1285 {
1286 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
1287 
1288 	/* fb_ping return 0 if the connection is alive */
1289 	return fb_ping(H->isc_status, &H->db) ? FAILURE : SUCCESS;
1290 }
1291 /* }}} */
1292 
1293 /* called by PDO to retrieve driver-specific information about an error that has occurred */
pdo_firebird_fetch_error_func(pdo_dbh_t * dbh,pdo_stmt_t * stmt,zval * info)1294 static void pdo_firebird_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info) /* {{{ */
1295 {
1296 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
1297 	if (H->einfo.sqlcode != IS_NULL) {
1298 		add_next_index_long(info, H->einfo.sqlcode);
1299 	}
1300 	if (H->einfo.errmsg && H->einfo.errmsg_length) {
1301 		add_next_index_stringl(info, H->einfo.errmsg, H->einfo.errmsg_length);
1302 	}
1303 }
1304 /* }}} */
1305 
1306 /* {{{ firebird_in_manually_transaction */
pdo_firebird_in_manually_transaction(pdo_dbh_t * dbh)1307 static bool pdo_firebird_in_manually_transaction(pdo_dbh_t *dbh)
1308 {
1309 	/**
1310 	 * we can tell if a transaction exists now by checking H->tr,
1311 	 * but which will always be true in autocommit mode.
1312 	 * So this function checks if there is currently a "manually begun transaction".
1313 	 */
1314 	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
1315 	return H->in_manually_txn;
1316 }
1317 /* }}} */
1318 
1319 static const struct pdo_dbh_methods firebird_methods = { /* {{{ */
1320 	firebird_handle_closer,
1321 	firebird_handle_preparer,
1322 	firebird_handle_doer,
1323 	firebird_handle_quoter,
1324 	firebird_handle_manually_begin,
1325 	firebird_handle_manually_commit,
1326 	firebird_handle_manually_rollback,
1327 	pdo_firebird_set_attribute,
1328 	NULL, /* last_id not supported */
1329 	pdo_firebird_fetch_error_func,
1330 	pdo_firebird_get_attribute,
1331 	pdo_firebird_check_liveness,
1332 	NULL, /* get driver methods */
1333 	NULL, /* request shutdown */
1334 	pdo_firebird_in_manually_transaction,
1335 	NULL, /* get gc */
1336 	NULL /* scanner */
1337 };
1338 /* }}} */
1339 
1340 /* the driver-specific PDO handle constructor */
pdo_firebird_handle_factory(pdo_dbh_t * dbh,zval * driver_options)1341 static int pdo_firebird_handle_factory(pdo_dbh_t *dbh, zval *driver_options) /* {{{ */
1342 {
1343 	struct pdo_data_src_parser vars[] = {
1344 		{ "dbname", NULL, 0 },
1345 		{ "charset",  NULL,	0 },
1346 		{ "role", NULL,	0 },
1347 		{ "dialect", "3", 0 },
1348 		{ "user", NULL, 0 },
1349 		{ "password", NULL, 0 }
1350 	};
1351 	int i, ret = 0;
1352 	short buf_len = 256, dpb_len;
1353 
1354 	pdo_firebird_db_handle *H = dbh->driver_data = pecalloc(1,sizeof(*H),dbh->is_persistent);
1355 
1356 	php_pdo_parse_data_source(dbh->data_source, dbh->data_source_len, vars, 6);
1357 
1358 	if (!dbh->username && vars[4].optval) {
1359 		dbh->username = pestrdup(vars[4].optval, dbh->is_persistent);
1360 	}
1361 
1362 	if (!dbh->password && vars[5].optval) {
1363 		dbh->password = pestrdup(vars[5].optval, dbh->is_persistent);
1364 	}
1365 
1366 	H->in_manually_txn = 0;
1367 	H->is_writable_txn = pdo_attr_lval(driver_options, PDO_FB_WRITABLE_TRANSACTION, 1);
1368 	zend_long txn_isolation_level = pdo_attr_lval(driver_options, PDO_FB_TRANSACTION_ISOLATION_LEVEL, PDO_FB_REPEATABLE_READ);
1369 	if (txn_isolation_level == PDO_FB_READ_COMMITTED ||
1370 		txn_isolation_level == PDO_FB_REPEATABLE_READ ||
1371 		txn_isolation_level == PDO_FB_SERIALIZABLE
1372 	) {
1373 		H->txn_isolation_level = txn_isolation_level;
1374 	} else {
1375 		zend_value_error("Pdo\\Firebird::TRANSACTION_ISOLATION_LEVEL must be a valid transaction isolation level "
1376 			"(Pdo\\Firebird::READ_COMMITTED, Pdo\\Firebird::REPEATABLE_READ, or Pdo\\Firebird::SERIALIZABLE)");
1377 		ret = 0;
1378 	}
1379 
1380 	do {
1381 		static char const dpb_flags[] = {
1382 			isc_dpb_user_name, isc_dpb_password, isc_dpb_lc_ctype, isc_dpb_sql_role_name };
1383 		char const *dpb_values[] = { dbh->username, dbh->password, vars[1].optval, vars[2].optval };
1384 		char dpb_buffer[256] = { isc_dpb_version1 }, *dpb;
1385 
1386 		dpb = dpb_buffer + 1;
1387 
1388 		/* loop through all the provided arguments and set dpb fields accordingly */
1389 		for (i = 0; i < sizeof(dpb_flags); ++i) {
1390 			if (dpb_values[i] && buf_len > 0) {
1391 				dpb_len = slprintf(dpb, buf_len, "%c%c%s", dpb_flags[i], (unsigned char)strlen(dpb_values[i]),
1392 					dpb_values[i]);
1393 				dpb += dpb_len;
1394 				buf_len -= dpb_len;
1395 			}
1396 		}
1397 
1398 		H->sql_dialect = PDO_FB_DIALECT;
1399 		if (vars[3].optval) {
1400 			H->sql_dialect = atoi(vars[3].optval);
1401 		}
1402 
1403 		/* fire it up baby! */
1404 		if (isc_attach_database(H->isc_status, 0, vars[0].optval, &H->db,(short)(dpb-dpb_buffer), dpb_buffer)) {
1405 			break;
1406 		}
1407 
1408 		dbh->methods = &firebird_methods;
1409 		dbh->native_case = PDO_CASE_UPPER;
1410 		dbh->alloc_own_columns = 1;
1411 
1412 		ret = 1;
1413 
1414 	} while (0);
1415 
1416 	for (i = 0; i < sizeof(vars)/sizeof(vars[0]); ++i) {
1417 		if (vars[i].freeme) {
1418 			efree(vars[i].optval);
1419 		}
1420 	}
1421 
1422 	if (!dbh->methods) {
1423 		char errmsg[512];
1424 		const ISC_STATUS *s = H->isc_status;
1425 		fb_interpret(errmsg, sizeof(errmsg),&s);
1426 		zend_throw_exception_ex(php_pdo_get_exception(), H->isc_status[1], "SQLSTATE[%s] [%ld] %s",
1427 				"HY000", H->isc_status[1], errmsg);
1428 	}
1429 
1430 	if (dbh->auto_commit && !H->tr) {
1431 		ret = php_firebird_begin_transaction(dbh, /* auto commit mode */ true);
1432 	}
1433 
1434 	if (!ret) {
1435 		firebird_handle_closer(dbh);
1436 	}
1437 
1438 	return ret;
1439 }
1440 /* }}} */
1441 
1442 
1443 const pdo_driver_t pdo_firebird_driver = { /* {{{ */
1444 	PDO_DRIVER_HEADER(firebird),
1445 	pdo_firebird_handle_factory
1446 };
1447 /* }}} */
1448