forked from FirebirdSQL/php-firebird
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfbird_events.c
More file actions
executable file
·633 lines (545 loc) · 18 KB
/
fbird_events.c
File metadata and controls
executable file
·633 lines (545 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/* SPDX-License-Identifier: PHP-3.01
* SPDX-FileCopyrightText: The PHP Group and contributors (see CREDITS) */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_FIREBIRD
#include "php_firebird.h"
#include "php_fbird_includes.h"
#include "fbird_classes.h"
#include "firebird_utils.h"
#ifndef PHP_WIN32
#include <signal.h>
#include <setjmp.h>
#include <errno.h>
#endif
int le_event;
/**
* ============================================================================
* THREAD-SAFETY REDESIGN (PHP 8.1+)
* ============================================================================
*
* PROBLEM:
* The old implementation used isc_que_events() with a C callback that was
* invoked from Firebird's internal thread. This callback called PHP functions
* (call_user_function) from a non-PHP thread, which is fundamentally unsafe:
* - No PHP request context exists on the Firebird thread
* - TSRM macros are empty in PHP 8.1+ (TSRMLS_FETCH_FROM_CTX does nothing)
* - Causes random crashes, memory corruption, and undefined behavior
*
* SOLUTION (Polling Model):
* - fbird_set_event_handler() registers the event and stores the callback
* but does NOT use async callbacks from isc_que_events()
* - fbird_poll_event() uses isc_wait_for_event() synchronously to check
* for events and calls the PHP callback from the PHP thread (safe!)
* - fbird_wait_event() continues to work as before (blocking sync)
*
* This ensures all PHP callbacks execute in the correct PHP thread context.
* ============================================================================
*/
static void _php_fbird_event_free(unsigned char *event_buf, unsigned char *result_buf)
{
if (event_buf) {
fbe_event_free(event_buf);
}
if (result_buf) {
fbe_event_free(result_buf);
}
}
void _php_fbird_free_event(fbird_event *event)
{
unsigned short i;
event->state = DEAD;
if (event->fbe_events) {
fbe_cancel(IBG(master_instance), event->fbe_events, NULL);
fbe_free(event->fbe_events);
event->fbe_events = NULL;
}
if (event->link != NULL) {
fbird_event **node;
/* Remove this event from the link's event list */
for (node = &event->link->event_head; *node && *node != event; node = &(*node)->event_next) {
/* iterate */
}
if (*node == event) {
*node = event->event_next;
}
/* Release reference to the DB link resource */
if (event->link_res) {
if (GC_DELREF(event->link_res) == 0) {
zend_list_delete(event->link_res);
}
event->link_res = NULL;
}
event->link = NULL;
}
if (Z_TYPE(event->callback) != IS_UNDEF) {
zval_ptr_dtor(&event->callback);
ZVAL_UNDEF(&event->callback);
if (event->event_buffer || event->result_buffer) {
_php_fbird_event_free(event->event_buffer, event->result_buffer);
event->event_buffer = NULL;
event->result_buffer = NULL;
}
for (i = 0; i < event->event_count; ++i) {
if (event->events[i]) {
efree(event->events[i]);
}
}
efree(event->events);
}
}
static void _php_fbird_free_event_rsrc(zend_resource *rsrc)
{
fbird_event *e = (fbird_event *) rsrc->ptr;
_php_fbird_free_event(e);
efree(e);
}
void php_fbird_events_minit(INIT_FUNC_ARGS)
{
le_event = zend_register_list_destructors_ex(_php_fbird_free_event_rsrc, NULL,
LE_EVENT, module_number);
}
/**
* Build event buffers for event operations.
* This creates the event_buffer and result_buffer needed for isc_wait_for_event.
*/
static void _php_fbird_event_block(unsigned short count, char **events,
unsigned short *l, unsigned char **event_buf, unsigned char **result_buf)
{
/**
* The Interbase API uses variadic arguments which we can't easily
* construct at runtime, but the maximum is 15 events.
*/
*l = (unsigned short) fbe_event_block(event_buf, result_buf, count,
events[0], events[1], events[2], events[3], events[4],
events[5], events[6], events[7], events[8], events[9],
events[10], events[11], events[12], events[13], events[14]);
}
PHP_FUNCTION(fbird_wait_event)
{
zval *args;
fbird_db_link *ib_link;
int num_args;
unsigned char *event_buffer, *result_buffer;
char *events[15];
uint32_t i = 0;
unsigned short event_count = 0, buffer_size;
ISC_ULONG occurred_event[15];
RESET_ERRMSG;
/* Validate argument count: 1-16 (optional link + 1-15 event names) */
if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 16) {
WRONG_PARAM_COUNT;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &num_args) == FAILURE) {
return;
}
/* Determine if first argument is a link resource or Firebird\Connection object */
if (Z_TYPE(args[0]) == IS_RESOURCE) {
if ((ib_link = (fbird_db_link *)zend_fetch_resource2_ex(&args[0], "Firebird link", le_link, le_plink)) == NULL) {
RETURN_FALSE;
}
i = 1;
} else if (Z_TYPE(args[0]) == IS_OBJECT &&
instanceof_function(Z_OBJCE_P(&args[0]), fbird_connection_ce)) {
/* M3: Accept Firebird\Connection objects */
zend_resource *_conn_res = fbird_connection_get_resource(Z_OBJ_P(&args[0]));
if (!_conn_res || !_conn_res->ptr) {
php_error_docref(NULL, E_WARNING,
"fbird_wait_event(): Firebird\\Connection object has no valid resource");
RETURN_FALSE;
}
ib_link = (fbird_db_link *)_conn_res->ptr;
i = 1;
} else {
/* First arg is neither a resource nor a Firebird\Connection object.
* If it's any other object type, throw TypeError — don't fall through
* to default-link which would block waiting for events on the wrong connection. */
if (Z_TYPE(args[0]) == IS_OBJECT) {
zend_type_error("fbird_wait_event(): Argument #1 must be of type "
"Firebird\\Connection|resource|string, %s given",
ZSTR_VAL(Z_OBJCE_P(&args[0])->name));
RETURN_THROWS();
}
if (ZEND_NUM_ARGS() > 15) {
WRONG_PARAM_COUNT;
}
if ((ib_link = (fbird_db_link *)zend_fetch_resource2(IBG(default_link), "Firebird link", le_link, le_plink)) == NULL) {
RETURN_FALSE;
}
}
/* Initialize the events array to NULL */
for (unsigned short j = 0; j < 15; ++j) {
events[j] = NULL;
}
/* Collect event names */
for (; i < ZEND_NUM_ARGS(); ++i) {
convert_to_string_ex(&args[i]);
events[event_count++] = Z_STRVAL(args[i]);
}
/* Build event buffers */
_php_fbird_event_block(event_count, events, &buffer_size, &event_buffer, &result_buffer);
/**
* Initialize the event buffers with a preliminary wait.
* This is required because isc_event_block() initializes counters to 0,
* and isc_wait_for_event() returns immediately if counters are 0.
* The first wait/count cycle establishes the baseline.
*/
{
ISC_STATUS init_status[20];
ISC_ULONG init_counts[15];
void *attachment_ptr = fbc_get_attachment(ib_link->fbc_connection);
if (fbe_wait_for_event_oo(init_status, attachment_ptr, buffer_size, event_buffer, result_buffer)) {
/* Initial wait failed - likely connection issue */
_php_fbird_error();
_php_fbird_event_free(event_buffer, result_buffer);
RETURN_FALSE;
}
fbe_event_counts(init_counts, buffer_size, event_buffer, result_buffer);
}
/* Now wait for actual events */
{
void *attachment_ptr = fbc_get_attachment(ib_link->fbc_connection);
if (fbe_wait_for_event_oo(IB_STATUS, attachment_ptr, buffer_size, event_buffer, result_buffer)) {
_php_fbird_error();
_php_fbird_event_free(event_buffer, result_buffer);
RETURN_FALSE;
}
}
/* Determine which event fired */
fbe_event_counts(occurred_event, buffer_size, event_buffer, result_buffer);
for (i = 0; i < event_count; ++i) {
if (occurred_event[i]) {
zend_string *result = zend_string_init(events[i], strlen(events[i]), 0);
_php_fbird_event_free(event_buffer, result_buffer);
RETURN_STR(result);
}
}
/* No event detected (should not happen) */
_php_fbird_event_free(event_buffer, result_buffer);
RETURN_FALSE;
}
PHP_FUNCTION(fbird_set_event_handler)
{
zval *args, *cb_arg;
fbird_db_link *ib_link;
fbird_event *event;
unsigned short i = 1, buffer_size;
int num_args;
zend_resource *link_res;
RESET_ERRMSG;
/* Validate argument count */
if (ZEND_NUM_ARGS() < 2 || ZEND_NUM_ARGS() > 17) {
WRONG_PARAM_COUNT;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &num_args) == FAILURE) {
return;
}
/* Determine argument layout: [link,] callback, event, [event, ...] */
if (Z_TYPE(args[0]) != IS_STRING) {
/* First argument is resource or Firebird\Connection object, second is callback */
if (ZEND_NUM_ARGS() < 3 || ZEND_NUM_ARGS() > 17) {
WRONG_PARAM_COUNT;
}
cb_arg = &args[1];
i = 2;
/* M3: Accept Firebird\Connection objects as well as legacy link resources */
if (Z_TYPE(args[0]) == IS_OBJECT &&
instanceof_function(Z_OBJCE_P(&args[0]), fbird_connection_ce)) {
link_res = fbird_connection_get_resource(Z_OBJ_P(&args[0]));
if (!link_res || !link_res->ptr) {
php_error_docref(NULL, E_WARNING,
"fbird_set_event_handler(): Firebird\\Connection object has no valid resource");
RETURN_FALSE;
}
ib_link = (fbird_db_link *)link_res->ptr;
} else {
if ((ib_link = (fbird_db_link *)zend_fetch_resource2_ex(&args[0], "Firebird link", le_link, le_plink)) == NULL) {
RETURN_FALSE;
}
link_res = Z_RES(args[0]);
}
} else {
/* First argument is callback (use default link) */
if (ZEND_NUM_ARGS() < 2 || ZEND_NUM_ARGS() > 16) {
WRONG_PARAM_COUNT;
}
cb_arg = &args[0];
if ((ib_link = (fbird_db_link *)zend_fetch_resource2(IBG(default_link), "Firebird link", le_link, le_plink)) == NULL) {
RETURN_FALSE;
}
link_res = IBG(default_link);
}
/* Validate callback is callable */
if (!zend_is_callable(cb_arg, 0, NULL)) {
zend_string *cb_name = zend_get_callable_name(cb_arg);
_php_fbird_module_error("Callback argument %s is not a callable function", ZSTR_VAL(cb_name));
zend_string_release_ex(cb_name, 0);
RETURN_FALSE;
}
/* Allocate and initialize event structure */
event = (fbird_event *) safe_emalloc(sizeof(fbird_event), 1, 0);
event->link_res = link_res;
GC_ADDREF(link_res);
event->link = ib_link;
event->event_count = 0;
event->state = NEW;
event->needs_reregistration = 0;
event->buffer_size = 0;
event->callback_count = 0;
event->max_callbacks = 1000; /* Safety limit for polling */
event->event_id = 0;
event->event_buffer = NULL;
event->result_buffer = NULL;
event->thread_ctx = NULL; /* Not used in polling model */
event->fbe_events = NULL; /* Phase 7: OO API event wrapper (future async support) */
event->events = (char **) safe_emalloc(sizeof(char *), 15, 0);
/* Store callback reference */
ZVAL_DUP(&event->callback, cb_arg);
/* Collect event names */
for (; i < 15; ++i) {
if (i < ZEND_NUM_ARGS()) {
zend_string *str = zval_get_string(&args[i]);
event->events[event->event_count++] = estrdup(ZSTR_VAL(str));
zend_string_release(str);
} else {
event->events[i] = NULL;
}
}
/* Build event buffers */
_php_fbird_event_block(event->event_count, event->events,
&buffer_size, &event->event_buffer, &event->result_buffer);
event->buffer_size = buffer_size;
/**
* NOTE: We do NOT call isc_wait_for_event() here because it blocks.
* The baseline initialization will happen on the first fbird_poll_event() call.
* The event handler is ready to use immediately.
*/
event->needs_reregistration = 1; /* Flag: first poll needs baseline init */
/* Mark as active and add to link's event list */
event->state = ACTIVE;
event->event_next = ib_link->event_head;
ib_link->event_head = event;
/* M3 Phase H3: return Firebird\Event object — object owns fbird_event* directly.
* fbird_event_free_obj() will call _php_fbird_free_event() + efree() on GC. */
fbird_setup_event_object(return_value, event);
}
#ifndef PHP_WIN32
/* Signal handler for alarm-based timeout */
static volatile sig_atomic_t fbird_timeout_occurred = 0;
static void fbird_timeout_handler(int sig) {
(void)sig;
fbird_timeout_occurred = 1;
}
#endif
PHP_FUNCTION(fbird_poll_event)
{
zval *event_arg;
zend_long timeout_ms = -1; /* Default: block forever */
fbird_event *event;
ISC_ULONG occurred_event[15];
unsigned short i;
ISC_STATUS wait_result;
#ifndef PHP_WIN32
struct sigaction sa_new, sa_old;
unsigned int alarm_remaining = 0;
int use_timeout = 0;
int had_old_handler = 0;
#endif
RESET_ERRMSG;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|l", &event_arg, &timeout_ms) == FAILURE) {
RETURN_FALSE;
}
/* M3 Phase H: accept Firebird\Event objects alongside le_event resources */
FBIRD_VALIDATE_EVENT_EX(event_arg, 1, event);
/* Check if event handler is still valid */
if (event->state == DEAD) {
RETURN_NULL(); /* Handler was cancelled */
}
if (!event->link || !fbc_is_connected(event->link->fbc_connection)) {
event->state = DEAD;
RETURN_FALSE; /* Connection lost */
}
/* Safety limit check */
if (event->callback_count >= event->max_callbacks) {
event->state = DEAD;
_php_fbird_module_error("Event callback limit exceeded");
RETURN_FALSE;
}
#ifndef PHP_WIN32
/**
* Set up alarm-based timeout for Unix systems BEFORE any blocking calls.
* This ensures the timeout covers both baseline initialization and the main
* wait, since isc_wait_for_event() blocks until interrupted by SIGALRM.
*/
if (timeout_ms >= 0) {
use_timeout = 1;
fbird_timeout_occurred = 0;
memset(&sa_new, 0, sizeof(sa_new));
sa_new.sa_handler = fbird_timeout_handler;
sigemptyset(&sa_new.sa_mask);
sa_new.sa_flags = 0; /* No SA_RESTART - we want EINTR */
if (sigaction(SIGALRM, &sa_new, &sa_old) == 0) {
had_old_handler = 1;
}
alarm_remaining = alarm(0);
/* Convert ms to seconds (minimum 1s — alarm(0) cancels) */
if (timeout_ms == 0) {
alarm(1);
} else {
unsigned int timeout_sec = (unsigned int)((timeout_ms + 999) / 1000);
if (timeout_sec == 0) {
timeout_sec = 1;
}
alarm(timeout_sec);
}
}
#endif
/**
* For zero timeout (immediate check), skip ALL blocking calls.
* isc_wait_for_event() cannot be interrupted reliably by SIGALRM when the
* Firebird client library uses SA_RESTART internally. Returning
* PHP_FBIRD_EVENT_TIMEOUT immediately is semantically correct for timeout_ms==0:
* "checked right now, no event detected, timed out."
*/
if (timeout_ms == 0) {
#ifndef PHP_WIN32
if (use_timeout) {
alarm(0);
if (had_old_handler) {
sigaction(SIGALRM, &sa_old, NULL);
}
if (alarm_remaining > 0) {
alarm(alarm_remaining);
}
}
#endif
RETURN_LONG(PHP_FBIRD_EVENT_TIMEOUT);
}
/**
* Handle baseline initialization on first poll.
* isc_event_block() initializes counters to 0, and isc_wait_for_event()
* establishes the baseline event count. This call is protected by the
* SIGALRM timeout set above so it cannot block indefinitely.
*/
if (event->needs_reregistration) {
ISC_STATUS init_status[20];
ISC_ULONG init_counts[15];
void *attachment_ptr = fbc_get_attachment(event->link->fbc_connection);
if (fbe_wait_for_event_oo(init_status, attachment_ptr,
event->buffer_size, event->event_buffer, event->result_buffer)) {
/* Wait failed - check if our timeout interrupted it */
#ifndef PHP_WIN32
if (use_timeout) {
alarm(0);
if (had_old_handler) {
sigaction(SIGALRM, &sa_old, NULL);
}
if (alarm_remaining > 0) {
alarm(alarm_remaining);
}
if (fbird_timeout_occurred) {
RETURN_LONG(PHP_FBIRD_EVENT_TIMEOUT);
}
}
#endif
_php_fbird_error();
event->state = DEAD;
RETURN_FALSE;
}
fbe_event_counts(init_counts, event->buffer_size,
event->event_buffer, event->result_buffer);
event->needs_reregistration = 0;
}
/**
* Use isc_wait_for_event() synchronously.
* This blocks until an event fires OR until interrupted by SIGALRM.
*/
wait_result = fbe_wait_for_event_oo(IB_STATUS, fbc_get_attachment(event->link->fbc_connection),
event->buffer_size, event->event_buffer, event->result_buffer);
#ifndef PHP_WIN32
/* Clean up timeout handling */
if (use_timeout) {
/* Cancel our alarm */
alarm(0);
/* Restore previous signal handler */
if (had_old_handler) {
sigaction(SIGALRM, &sa_old, NULL);
}
/* Restore any previous alarm that was pending */
if (alarm_remaining > 0) {
alarm(alarm_remaining);
}
/* Check if timeout occurred */
if (fbird_timeout_occurred) {
RETURN_LONG(PHP_FBIRD_EVENT_TIMEOUT);
}
}
#endif
/* Check for errors from isc_wait_for_event */
if (wait_result != 0) {
#ifndef PHP_WIN32
/* On Unix, EINTR from timeout is handled above via fbird_timeout_occurred flag.
* If we get here with an error, it's a real error. */
#endif
_php_fbird_error();
event->state = DEAD;
RETURN_FALSE;
}
/* Get event counts to determine which event fired */
fbe_event_counts(occurred_event, event->buffer_size,
event->event_buffer, event->result_buffer);
/* Find the event that occurred */
for (i = 0; i < event->event_count; ++i) {
if (occurred_event[i]) {
zval return_value_cb, args[1];
ZVAL_UNDEF(&return_value_cb);
ZVAL_STRING(&args[0], event->events[i]);
event->callback_count++;
/**
* Call the PHP callback - THREAD-SAFE!
* We're executing in the PHP thread, so call_user_function is safe.
*/
if (FAILURE == call_user_function(NULL, NULL, &event->callback,
&return_value_cb, 1, args)) {
_php_fbird_module_error("Error calling event callback");
zval_ptr_dtor(&args[0]);
event->state = DEAD;
RETURN_FALSE;
}
/* Check if callback wants to cancel future events */
if (Z_TYPE(return_value_cb) != IS_UNDEF && !zend_is_true(&return_value_cb)) {
event->state = DEAD;
}
/* Clean up */
zval_ptr_dtor(&args[0]);
zval_ptr_dtor(&return_value_cb);
/* Return the event name that fired */
RETURN_STRING(event->events[i]);
}
}
/* No event detected in this poll cycle */
RETURN_NULL();
}
PHP_FUNCTION(fbird_free_event_handler)
{
zval *event_arg;
RESET_ERRMSG;
if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS(), "z", &event_arg)) {
fbird_event *event;
/* M3 Phase H: accept Firebird\Event objects alongside le_event resources */
FBIRD_VALIDATE_EVENT_EX(event_arg, 1, event);
event->state = DEAD;
/* Resource path: trigger destructor via zend_list_delete.
* Object path: state = DEAD is sufficient; GC handles cleanup when
* the Firebird\Event object goes out of scope. */
if (Z_TYPE_P(event_arg) == IS_RESOURCE) {
zend_list_delete(Z_RES_P(event_arg));
}
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
#endif /* HAVE_FIREBIRD */