1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2014 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Sascha Schumann <sascha@schumann.cx>                        |
16   |          Marcus Boerger <helly@php.net>                              |
17   +----------------------------------------------------------------------+
18 */
19
20/* $Id$ */
21
22#ifdef HAVE_CONFIG_H
23#include "config.h"
24#endif
25
26#include "php.h"
27
28#if HAVE_DBA
29
30#include "php_ini.h"
31#include <stdio.h>
32#include <fcntl.h>
33#ifdef HAVE_SYS_FILE_H
34#include <sys/file.h>
35#endif
36
37#include "php_dba.h"
38#include "ext/standard/info.h"
39#include "ext/standard/php_string.h"
40#include "ext/standard/flock_compat.h"
41
42#include "php_gdbm.h"
43#include "php_ndbm.h"
44#include "php_dbm.h"
45#include "php_cdb.h"
46#include "php_db1.h"
47#include "php_db2.h"
48#include "php_db3.h"
49#include "php_db4.h"
50#include "php_flatfile.h"
51#include "php_inifile.h"
52#include "php_qdbm.h"
53#include "php_tcadb.h"
54
55/* {{{ arginfo */
56ZEND_BEGIN_ARG_INFO_EX(arginfo_dba_popen, 0, 0, 2)
57    ZEND_ARG_INFO(0, path)
58    ZEND_ARG_INFO(0, mode)
59    ZEND_ARG_INFO(0, handlername)
60    ZEND_ARG_VARIADIC_INFO(0, handler_parameters)
61ZEND_END_ARG_INFO()
62
63ZEND_BEGIN_ARG_INFO_EX(arginfo_dba_open, 0, 0, 2)
64    ZEND_ARG_INFO(0, path)
65    ZEND_ARG_INFO(0, mode)
66    ZEND_ARG_INFO(0, handlername)
67    ZEND_ARG_VARIADIC_INFO(0, handler_parameters)
68ZEND_END_ARG_INFO()
69
70ZEND_BEGIN_ARG_INFO(arginfo_dba_close, 0)
71    ZEND_ARG_INFO(0, handle)
72ZEND_END_ARG_INFO()
73
74ZEND_BEGIN_ARG_INFO(arginfo_dba_exists, 0)
75    ZEND_ARG_INFO(0, key)
76    ZEND_ARG_INFO(0, handle)
77ZEND_END_ARG_INFO()
78
79ZEND_BEGIN_ARG_INFO_EX(arginfo_dba_fetch, 0, 0, 2)
80    ZEND_ARG_INFO(0, key)
81    ZEND_ARG_INFO(0, skip)
82    ZEND_ARG_INFO(0, handle)
83ZEND_END_ARG_INFO()
84
85ZEND_BEGIN_ARG_INFO(arginfo_dba_key_split, 0)
86    ZEND_ARG_INFO(0, key)
87ZEND_END_ARG_INFO()
88
89ZEND_BEGIN_ARG_INFO(arginfo_dba_firstkey, 0)
90    ZEND_ARG_INFO(0, handle)
91ZEND_END_ARG_INFO()
92
93ZEND_BEGIN_ARG_INFO(arginfo_dba_nextkey, 0)
94    ZEND_ARG_INFO(0, handle)
95ZEND_END_ARG_INFO()
96
97ZEND_BEGIN_ARG_INFO(arginfo_dba_delete, 0)
98    ZEND_ARG_INFO(0, key)
99    ZEND_ARG_INFO(0, handle)
100ZEND_END_ARG_INFO()
101
102ZEND_BEGIN_ARG_INFO(arginfo_dba_insert, 0)
103    ZEND_ARG_INFO(0, key)
104    ZEND_ARG_INFO(0, value)
105    ZEND_ARG_INFO(0, handle)
106ZEND_END_ARG_INFO()
107
108ZEND_BEGIN_ARG_INFO(arginfo_dba_replace, 0)
109    ZEND_ARG_INFO(0, key)
110    ZEND_ARG_INFO(0, value)
111    ZEND_ARG_INFO(0, handle)
112ZEND_END_ARG_INFO()
113
114ZEND_BEGIN_ARG_INFO(arginfo_dba_optimize, 0)
115    ZEND_ARG_INFO(0, handle)
116ZEND_END_ARG_INFO()
117
118ZEND_BEGIN_ARG_INFO(arginfo_dba_sync, 0)
119    ZEND_ARG_INFO(0, handle)
120ZEND_END_ARG_INFO()
121
122ZEND_BEGIN_ARG_INFO_EX(arginfo_dba_handlers, 0, 0, 0)
123    ZEND_ARG_INFO(0, full_info)
124ZEND_END_ARG_INFO()
125
126ZEND_BEGIN_ARG_INFO(arginfo_dba_list, 0)
127ZEND_END_ARG_INFO()
128
129/* }}} */
130
131/* {{{ dba_functions[]
132 */
133const zend_function_entry dba_functions[] = {
134    PHP_FE(dba_open, arginfo_dba_open)
135    PHP_FE(dba_popen, arginfo_dba_popen)
136    PHP_FE(dba_close, arginfo_dba_close)
137    PHP_FE(dba_delete, arginfo_dba_delete)
138    PHP_FE(dba_exists, arginfo_dba_exists)
139    PHP_FE(dba_fetch, arginfo_dba_fetch)
140    PHP_FE(dba_insert, arginfo_dba_insert)
141    PHP_FE(dba_replace, arginfo_dba_replace)
142    PHP_FE(dba_firstkey, arginfo_dba_firstkey)
143    PHP_FE(dba_nextkey, arginfo_dba_nextkey)
144    PHP_FE(dba_optimize, arginfo_dba_optimize)
145    PHP_FE(dba_sync, arginfo_dba_sync)
146    PHP_FE(dba_handlers, arginfo_dba_handlers)
147    PHP_FE(dba_list, arginfo_dba_list)
148    PHP_FE(dba_key_split, arginfo_dba_key_split)
149    PHP_FE_END
150};
151/* }}} */
152
153PHP_MINIT_FUNCTION(dba);
154PHP_MSHUTDOWN_FUNCTION(dba);
155PHP_MINFO_FUNCTION(dba);
156
157ZEND_BEGIN_MODULE_GLOBALS(dba)
158    char *default_handler;
159    dba_handler *default_hptr;
160ZEND_END_MODULE_GLOBALS(dba)
161
162ZEND_DECLARE_MODULE_GLOBALS(dba)
163
164#ifdef ZTS
165#define DBA_G(v) TSRMG(dba_globals_id, zend_dba_globals *, v)
166#else
167#define DBA_G(v) (dba_globals.v)
168#endif
169
170static PHP_GINIT_FUNCTION(dba);
171
172zend_module_entry dba_module_entry = {
173    STANDARD_MODULE_HEADER,
174    "dba",
175    dba_functions,
176    PHP_MINIT(dba),
177    PHP_MSHUTDOWN(dba),
178    NULL,
179    NULL,
180    PHP_MINFO(dba),
181    NO_VERSION_YET,
182    PHP_MODULE_GLOBALS(dba),
183    PHP_GINIT(dba),
184    NULL,
185    NULL,
186    STANDARD_MODULE_PROPERTIES_EX
187};
188
189#ifdef COMPILE_DL_DBA
190ZEND_GET_MODULE(dba)
191#endif
192
193/* {{{ macromania */
194
195#define DBA_ID_PARS                                             \
196    zval *id;                                                   \
197    dba_info *info = NULL;                                      \
198    int ac = ZEND_NUM_ARGS()
199
200/* these are used to get the standard arguments */
201
202/* {{{ php_dba_myke_key */
203static size_t php_dba_make_key(zval *key, char **key_str, char **key_free TSRMLS_DC)
204{
205    if (Z_TYPE_P(key) == IS_ARRAY) {
206        zval *group, *name;
207        HashPosition pos;
208        size_t len;
209
210        if (zend_hash_num_elements(Z_ARRVAL_P(key)) != 2) {
211            php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Key does not have exactly two elements: (key, name)");
212            return -1;
213        }
214        zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(key), &pos);
215        group = zend_hash_get_current_data_ex(Z_ARRVAL_P(key), &pos);
216        zend_hash_move_forward_ex(Z_ARRVAL_P(key), &pos);
217        name = zend_hash_get_current_data_ex(Z_ARRVAL_P(key), &pos);
218        convert_to_string_ex(group);
219        convert_to_string_ex(name);
220        if (Z_STRLEN_P(group) == 0) {
221            *key_str = Z_STRVAL_P(name);
222            *key_free = NULL;
223            return Z_STRLEN_P(name);
224        }
225        len = spprintf(key_str, 0, "[%s]%s", Z_STRVAL_P(group), Z_STRVAL_P(name));
226        *key_free = *key_str;
227        return len;
228    } else {
229        zval tmp;
230        int len;
231
232        ZVAL_COPY(&tmp, key);
233        convert_to_string(&tmp);
234
235        *key_free = *key_str = estrndup(Z_STRVAL(tmp), Z_STRLEN(tmp));
236        len = Z_STRLEN(tmp);
237
238        zval_ptr_dtor(&tmp);
239        return len;
240    }
241}
242/* }}} */
243
244#define DBA_GET2                                                \
245    zval *key;                                                  \
246    char *key_str, *key_free;                                   \
247    size_t key_len;                                             \
248    if (zend_parse_parameters(ac TSRMLS_CC, "zr", &key, &id) == FAILURE) {  \
249        return;                                                 \
250    }                                                           \
251    if ((key_len = php_dba_make_key(key, &key_str, &key_free TSRMLS_CC)) == 0) {\
252        RETURN_FALSE;                                           \
253    }
254
255#define DBA_GET2_3                                              \
256    zval *key;                                                  \
257    char *key_str, *key_free;                                   \
258    size_t key_len;                                             \
259    zend_long skip = 0;                                             \
260    switch(ac) {                                                \
261    case 2:                                                     \
262        if (zend_parse_parameters(ac TSRMLS_CC, "zr", &key, &id) == FAILURE) { \
263            return;                                             \
264        }                                                       \
265        break;                                                  \
266    case 3:                                                     \
267        if (zend_parse_parameters(ac TSRMLS_CC, "zlr", &key, &skip, &id) == FAILURE) { \
268            return;                                             \
269        }                                                       \
270        break;                                                  \
271    default:                                                    \
272        WRONG_PARAM_COUNT;                                      \
273    }                                                           \
274    if ((key_len = php_dba_make_key(key, &key_str, &key_free TSRMLS_CC)) == 0) {\
275        RETURN_FALSE;                                           \
276    }
277
278
279#define DBA_FETCH_RESOURCE(info, id)    \
280    ZEND_FETCH_RESOURCE2(info, dba_info *, id, -1, "DBA identifier", le_db, le_pdb);
281
282#define DBA_ID_GET2   DBA_ID_PARS; DBA_GET2;   DBA_FETCH_RESOURCE(info, id)
283#define DBA_ID_GET2_3 DBA_ID_PARS; DBA_GET2_3; DBA_FETCH_RESOURCE(info, id)
284
285#define DBA_ID_DONE                                             \
286    if (key_free) efree(key_free)
287/* a DBA handler must have specific routines */
288
289#define DBA_NAMED_HND(alias, name, flags) \
290{\
291    #alias, flags, dba_open_##name, dba_close_##name, dba_fetch_##name, dba_update_##name, \
292    dba_exists_##name, dba_delete_##name, dba_firstkey_##name, dba_nextkey_##name, \
293    dba_optimize_##name, dba_sync_##name, dba_info_##name \
294},
295
296#define DBA_HND(name, flags) DBA_NAMED_HND(name, name, flags)
297
298/* check whether the user has write access */
299#define DBA_WRITE_CHECK \
300    if(info->mode != DBA_WRITER && info->mode != DBA_TRUNC && info->mode != DBA_CREAT) { \
301        php_error_docref(NULL TSRMLS_CC, E_WARNING, "You cannot perform a modification to a database without proper access"); \
302        RETURN_FALSE; \
303    }
304
305/* the same check, but with a call to DBA_ID_DONE before returning */
306#define DBA_WRITE_CHECK_WITH_ID \
307    if(info->mode != DBA_WRITER && info->mode != DBA_TRUNC && info->mode != DBA_CREAT) { \
308        php_error_docref(NULL TSRMLS_CC, E_WARNING, "You cannot perform a modification to a database without proper access"); \
309        DBA_ID_DONE; \
310        RETURN_FALSE; \
311    }
312
313/* }}} */
314
315/* {{{ globals */
316
317static dba_handler handler[] = {
318#if DBA_GDBM
319    DBA_HND(gdbm, DBA_LOCK_EXT) /* Locking done in library if set */
320#endif
321#if DBA_DBM
322    DBA_HND(dbm, DBA_LOCK_ALL) /* No lock in lib */
323#endif
324#if DBA_NDBM
325    DBA_HND(ndbm, DBA_LOCK_ALL) /* Could be done in library: filemode = 0644 + S_ENFMT */
326#endif
327#if DBA_CDB
328    DBA_HND(cdb, DBA_STREAM_OPEN|DBA_LOCK_ALL) /* No lock in lib */
329#endif
330#if DBA_CDB_BUILTIN
331    DBA_NAMED_HND(cdb_make, cdb, DBA_STREAM_OPEN|DBA_LOCK_ALL) /* No lock in lib */
332#endif
333#if DBA_DB1
334    DBA_HND(db1, DBA_LOCK_ALL) /* No lock in lib */
335#endif
336#if DBA_DB2
337    DBA_HND(db2, DBA_LOCK_ALL) /* No lock in lib */
338#endif
339#if DBA_DB3
340    DBA_HND(db3, DBA_LOCK_ALL) /* No lock in lib */
341#endif
342#if DBA_DB4
343    DBA_HND(db4, DBA_LOCK_ALL) /* No lock in lib */
344#endif
345#if DBA_INIFILE
346    DBA_HND(inifile, DBA_STREAM_OPEN|DBA_LOCK_ALL|DBA_CAST_AS_FD) /* No lock in lib */
347#endif
348#if DBA_FLATFILE
349    DBA_HND(flatfile, DBA_STREAM_OPEN|DBA_LOCK_ALL|DBA_NO_APPEND) /* No lock in lib */
350#endif
351#if DBA_QDBM
352    DBA_HND(qdbm, DBA_LOCK_EXT)
353#endif
354#if DBA_TCADB
355    DBA_HND(tcadb, DBA_LOCK_ALL)
356#endif
357    { NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
358};
359
360#if DBA_FLATFILE
361#define DBA_DEFAULT "flatfile"
362#elif DBA_DB4
363#define DBA_DEFAULT "db4"
364#elif DBA_DB3
365#define DBA_DEFAULT "db3"
366#elif DBA_DB2
367#define DBA_DEFAULT "db2"
368#elif DBA_DB1
369#define DBA_DEFAULT "db1"
370#elif DBA_GDBM
371#define DBA_DEFAULT "gdbm"
372#elif DBA_NBBM
373#define DBA_DEFAULT "ndbm"
374#elif DBA_DBM
375#define DBA_DEFAULT "dbm"
376#elif DBA_QDBM
377#define DBA_DEFAULT "qdbm"
378#elif DBA_TCADB
379#define DBA_DEFAULT "tcadb"
380#else
381#define DBA_DEFAULT ""
382#endif
383/* cdb/cdb_make and ini are no option here */
384
385static int le_db;
386static int le_pdb;
387/* }}} */
388
389/* {{{ dba_fetch_resource
390PHPAPI void dba_fetch_resource(dba_info **pinfo, zval **id TSRMLS_DC)
391{
392    dba_info *info;
393    DBA_ID_FETCH
394    *pinfo = info;
395}
396*/
397/* }}} */
398
399/* {{{ dba_get_handler
400PHPAPI dba_handler *dba_get_handler(const char* handler_name)
401{
402    dba_handler *hptr;
403    for (hptr = handler; hptr->name && strcasecmp(hptr->name, handler_name); hptr++);
404    return hptr;
405}
406*/
407/* }}} */
408
409/* {{{ dba_close
410 */
411static void dba_close(dba_info *info TSRMLS_DC)
412{
413    if (info->hnd) {
414        info->hnd->close(info TSRMLS_CC);
415    }
416    if (info->path) {
417        pefree(info->path, info->flags&DBA_PERSISTENT);
418    }
419    if (info->fp && info->fp != info->lock.fp) {
420        if (info->flags & DBA_PERSISTENT) {
421            php_stream_pclose(info->fp);
422        } else {
423            php_stream_close(info->fp);
424        }
425    }
426    if (info->lock.fp) {
427        if (info->flags & DBA_PERSISTENT) {
428            php_stream_pclose(info->lock.fp);
429        } else {
430            php_stream_close(info->lock.fp);
431        }
432    }
433    if (info->lock.name) {
434        pefree(info->lock.name, info->flags&DBA_PERSISTENT);
435    }
436    pefree(info, info->flags&DBA_PERSISTENT);
437}
438/* }}} */
439
440/* {{{ dba_close_rsrc
441 */
442static void dba_close_rsrc(zend_resource *rsrc TSRMLS_DC)
443{
444    dba_info *info = (dba_info *)rsrc->ptr;
445
446    dba_close(info TSRMLS_CC);
447}
448/* }}} */
449
450/* {{{ dba_close_pe_rsrc_deleter */
451int dba_close_pe_rsrc_deleter(zval *el, void *pDba TSRMLS_DC)
452{
453    return ((zend_resource *)Z_PTR_P(el))->ptr == pDba ? ZEND_HASH_APPLY_REMOVE: ZEND_HASH_APPLY_KEEP;
454}
455/* }}} */
456
457/* {{{ dba_close_pe_rsrc */
458static void dba_close_pe_rsrc(zend_resource *rsrc TSRMLS_DC)
459{
460    dba_info *info = (dba_info *)rsrc->ptr;
461
462    /* closes the resource by calling dba_close_rsrc() */
463    zend_hash_apply_with_argument(&EG(persistent_list), dba_close_pe_rsrc_deleter, info TSRMLS_CC);
464}
465/* }}} */
466
467/* {{{ PHP_INI
468 */
469ZEND_INI_MH(OnUpdateDefaultHandler)
470{
471    dba_handler *hptr;
472
473    if (!new_value->len) {
474        DBA_G(default_hptr) = NULL;
475        return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
476    }
477
478    for (hptr = handler; hptr->name && strcasecmp(hptr->name, new_value->val); hptr++);
479
480    if (!hptr->name) {
481        php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such handler: %s", new_value->val);
482        return FAILURE;
483    }
484    DBA_G(default_hptr) = hptr;
485    return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
486}
487
488PHP_INI_BEGIN()
489    STD_PHP_INI_ENTRY("dba.default_handler", DBA_DEFAULT, PHP_INI_ALL, OnUpdateDefaultHandler, default_handler,    zend_dba_globals, dba_globals)
490PHP_INI_END()
491/* }}} */
492
493/* {{{ PHP_GINIT_FUNCTION
494 */
495static PHP_GINIT_FUNCTION(dba)
496{
497    dba_globals->default_handler = "";
498    dba_globals->default_hptr    = NULL;
499}
500/* }}} */
501
502/* {{{ PHP_MINIT_FUNCTION
503 */
504PHP_MINIT_FUNCTION(dba)
505{
506    REGISTER_INI_ENTRIES();
507    le_db = zend_register_list_destructors_ex(dba_close_rsrc, NULL, "dba", module_number);
508    le_pdb = zend_register_list_destructors_ex(dba_close_pe_rsrc, dba_close_rsrc, "dba persistent", module_number);
509    return SUCCESS;
510}
511/* }}} */
512
513/* {{{ PHP_MSHUTDOWN_FUNCTION
514 */
515PHP_MSHUTDOWN_FUNCTION(dba)
516{
517    UNREGISTER_INI_ENTRIES();
518    return SUCCESS;
519}
520/* }}} */
521
522#include "ext/standard/php_smart_str.h"
523
524/* {{{ PHP_MINFO_FUNCTION
525 */
526PHP_MINFO_FUNCTION(dba)
527{
528    dba_handler *hptr;
529    smart_str handlers = {0};
530
531    for(hptr = handler; hptr->name; hptr++) {
532        smart_str_appends(&handlers, hptr->name);
533        smart_str_appendc(&handlers, ' ');
534    }
535
536    php_info_print_table_start();
537    php_info_print_table_row(2, "DBA support", "enabled");
538    if (handlers.s) {
539        smart_str_0(&handlers);
540        php_info_print_table_row(2, "Supported handlers", handlers.s->val);
541        smart_str_free(&handlers);
542    } else {
543        php_info_print_table_row(2, "Supported handlers", "none");
544    }
545    php_info_print_table_end();
546    DISPLAY_INI_ENTRIES();
547}
548/* }}} */
549
550/* {{{ php_dba_update
551 */
552static void php_dba_update(INTERNAL_FUNCTION_PARAMETERS, int mode)
553{
554    size_t val_len;
555    zval *id;
556    dba_info *info = NULL;
557    int ac = ZEND_NUM_ARGS();
558    zval *key;
559    char *val;
560    char *key_str, *key_free;
561    size_t key_len;
562
563    if (zend_parse_parameters(ac TSRMLS_CC, "zsr", &key, &val, &val_len, &id) == FAILURE) {
564        return;
565    }
566
567    if ((key_len = php_dba_make_key(key, &key_str, &key_free TSRMLS_CC)) == 0) {
568        RETURN_FALSE;
569    }
570
571    DBA_FETCH_RESOURCE(info, id);
572
573    DBA_WRITE_CHECK_WITH_ID;
574
575    if (info->hnd->update(info, key_str, key_len, val, val_len, mode TSRMLS_CC) == SUCCESS) {
576        DBA_ID_DONE;
577        RETURN_TRUE;
578    }
579
580    DBA_ID_DONE;
581    RETURN_FALSE;
582}
583/* }}} */
584
585#define FREENOW if(args) {int i; for (i=0; i<ac; i++) { zval_ptr_dtor(&args[i]); } efree(args);} if(key) efree(key)
586
587/* {{{ php_find_dbm
588 */
589dba_info *php_dba_find(const char* path TSRMLS_DC)
590{
591    zend_resource *le;
592    dba_info *info;
593    int numitems, i;
594
595    numitems = zend_hash_next_free_element(&EG(regular_list));
596    for (i=1; i<numitems; i++) {
597        if ((le = zend_hash_index_find_ptr(&EG(regular_list), i)) == NULL) {
598            continue;
599        }
600        if (le->type == le_db || le->type == le_pdb) {
601            info = (dba_info *)(le->ptr);
602            if (!strcmp(info->path, path)) {
603                return (dba_info *)(le->ptr);
604            }
605        }
606    }
607
608    return NULL;
609}
610/* }}} */
611
612/* {{{ php_dba_open
613 */
614static void php_dba_open(INTERNAL_FUNCTION_PARAMETERS, int persistent)
615{
616    zval *args = NULL;
617    int ac = ZEND_NUM_ARGS();
618    dba_mode_t modenr;
619    dba_info *info, *other;
620    dba_handler *hptr;
621    char *key = NULL, *error = NULL;
622    int keylen = 0;
623    int i;
624    int lock_mode, lock_flag, lock_dbf = 0;
625    char *file_mode;
626    char mode[4], *pmode, *lock_file_mode = NULL;
627    int persistent_flag = persistent ? STREAM_OPEN_PERSISTENT : 0;
628    char *opened_path = NULL;
629    char *lock_name;
630
631    if (ac < 2) {
632        WRONG_PARAM_COUNT;
633    }
634
635    /* we pass additional args to the respective handler */
636    args = safe_emalloc(ac, sizeof(zval), 0);
637    if (zend_get_parameters_array_ex(ac, args) != SUCCESS) {
638        efree(args);
639        WRONG_PARAM_COUNT;
640    }
641
642    /* we only take string arguments */
643    for (i = 0; i < ac; i++) {
644        if (Z_TYPE(args[i]) != IS_STRING) {
645            convert_to_string_ex(&args[i]);
646        } else if (Z_REFCOUNTED(args[i])) {
647            Z_ADDREF(args[i]);
648        }
649        keylen += Z_STRLEN(args[i]);
650    }
651
652    if (persistent) {
653        zend_resource *le;
654
655        /* calculate hash */
656        key = safe_emalloc(keylen, 1, 1);
657        key[keylen] = '\0';
658        keylen = 0;
659
660        for(i = 0; i < ac; i++) {
661            memcpy(key+keylen, Z_STRVAL(args[i]), Z_STRLEN(args[i]));
662            keylen += Z_STRLEN(args[i]);
663        }
664
665        /* try to find if we already have this link in our persistent list */
666        if ((le = zend_hash_str_find_ptr(&EG(persistent_list), key, keylen)) != NULL) {
667            FREENOW;
668
669            if (le->type != le_pdb) {
670                RETURN_FALSE;
671            }
672
673            info = (dba_info *)le->ptr;
674
675            GC_REFCOUNT(le)++;
676            RETURN_RES(le);
677            return;
678        }
679    }
680
681    if (ac==2) {
682        hptr = DBA_G(default_hptr);
683        if (!hptr) {
684            php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "No default handler selected");
685            FREENOW;
686            RETURN_FALSE;
687        }
688    } else {
689        for (hptr = handler; hptr->name && strcasecmp(hptr->name, Z_STRVAL(args[2])); hptr++);
690    }
691
692    if (!hptr->name) {
693        php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "No such handler: %s", Z_STRVAL(args[2]));
694        FREENOW;
695        RETURN_FALSE;
696    }
697
698    /* Check mode: [rwnc][fl]?t?
699     * r: Read
700     * w: Write
701     * n: Create/Truncate
702     * c: Create
703     *
704     * d: force lock on database file
705     * l: force lock on lck file
706     * -: ignore locking
707     *
708     * t: test open database, warning if locked
709     */
710    strlcpy(mode, Z_STRVAL(args[1]), sizeof(mode));
711    pmode = &mode[0];
712    if (pmode[0] && (pmode[1]=='d' || pmode[1]=='l' || pmode[1]=='-')) { /* force lock on db file or lck file or disable locking */
713        switch (pmode[1]) {
714        case 'd':
715            lock_dbf = 1;
716            if ((hptr->flags & DBA_LOCK_ALL) == 0) {
717                lock_flag = (hptr->flags & DBA_LOCK_ALL);
718                break;
719            }
720            /* no break */
721        case 'l':
722            lock_flag = DBA_LOCK_ALL;
723            if ((hptr->flags & DBA_LOCK_ALL) == 0) {
724                php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_NOTICE, "Handler %s does locking internally", hptr->name);
725            }
726            break;
727        default:
728        case '-':
729            if ((hptr->flags & DBA_LOCK_ALL) == 0) {
730                php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Locking cannot be disabled for handler %s", hptr->name);
731                FREENOW;
732                RETURN_FALSE;
733            }
734            lock_flag = 0;
735            break;
736        }
737    } else {
738        lock_flag = (hptr->flags&DBA_LOCK_ALL);
739        lock_dbf = 1;
740    }
741    switch (*pmode++) {
742        case 'r':
743            modenr = DBA_READER;
744            lock_mode = (lock_flag & DBA_LOCK_READER) ? LOCK_SH : 0;
745            file_mode = "r";
746            break;
747        case 'w':
748            modenr = DBA_WRITER;
749            lock_mode = (lock_flag & DBA_LOCK_WRITER) ? LOCK_EX : 0;
750            file_mode = "r+b";
751            break;
752        case 'c':
753            modenr = DBA_CREAT;
754            lock_mode = (lock_flag & DBA_LOCK_CREAT) ? LOCK_EX : 0;
755            if (lock_mode) {
756                if (lock_dbf) {
757                    /* the create/append check will be done on the lock
758                     * when the lib opens the file it is already created
759                     */
760                    file_mode = "r+b";       /* read & write, seek 0 */
761                    lock_file_mode = "a+b";  /* append */
762                } else {
763                    file_mode = "a+b";       /* append */
764                    lock_file_mode = "w+b";  /* create/truncate */
765                }
766            } else {
767                file_mode = "a+b";
768            }
769            /* In case of the 'a+b' append mode, the handler is responsible
770             * to handle any rewind problems (see flatfile handler).
771             */
772            break;
773        case 'n':
774            modenr = DBA_TRUNC;
775            lock_mode = (lock_flag & DBA_LOCK_TRUNC) ? LOCK_EX : 0;
776            file_mode = "w+b";
777            break;
778        default:
779            php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Illegal DBA mode");
780            FREENOW;
781            RETURN_FALSE;
782    }
783    if (!lock_file_mode) {
784        lock_file_mode = file_mode;
785    }
786    if (*pmode=='d' || *pmode=='l' || *pmode=='-') {
787        pmode++; /* done already - skip here */
788    }
789    if (*pmode=='t') {
790        pmode++;
791        if (!lock_flag) {
792            php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "You cannot combine modifiers - (no lock) and t (test lock)");
793            FREENOW;
794            RETURN_FALSE;
795        }
796        if (!lock_mode) {
797            if ((hptr->flags & DBA_LOCK_ALL) == 0) {
798                php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Handler %s uses its own locking which doesn't support mode modifier t (test lock)", hptr->name);
799                FREENOW;
800                RETURN_FALSE;
801            } else {
802                php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Handler %s doesn't uses locking for this mode which makes modifier t (test lock) obsolete", hptr->name);
803                FREENOW;
804                RETURN_FALSE;
805            }
806        } else {
807            lock_mode |= LOCK_NB; /* test =: non blocking */
808        }
809    }
810    if (*pmode) {
811        php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Illegal DBA mode");
812        FREENOW;
813        RETURN_FALSE;
814    }
815
816    info = pemalloc(sizeof(dba_info), persistent);
817    memset(info, 0, sizeof(dba_info));
818    info->path = pestrdup(Z_STRVAL(args[0]), persistent);
819    info->mode = modenr;
820    info->argc = ac - 3;
821    info->argv = args + 3;
822    info->flags = (hptr->flags & ~DBA_LOCK_ALL) | (lock_flag & DBA_LOCK_ALL) | (persistent ? DBA_PERSISTENT : 0);
823    info->lock.mode = lock_mode;
824
825    /* if any open call is a locking call:
826     * check if we already habe a locking call open that should block this call
827     * the problem is some systems would allow read during write
828     */
829    if (hptr->flags & DBA_LOCK_ALL) {
830        if ((other = php_dba_find(info->path TSRMLS_CC)) != NULL) {
831            if (   ( (lock_mode&LOCK_EX)        && (other->lock.mode&(LOCK_EX|LOCK_SH)) )
832                || ( (other->lock.mode&LOCK_EX) && (lock_mode&(LOCK_EX|LOCK_SH))        )
833               ) {
834                error = "Unable to establish lock (database file already open)"; /* force failure exit */
835            }
836        }
837    }
838
839    if (!error && lock_mode) {
840        if (lock_dbf) {
841            lock_name = Z_STRVAL(args[0]);
842        } else {
843            spprintf(&lock_name, 0, "%s.lck", info->path);
844            if (!strcmp(file_mode, "r")) {
845                /* when in read only mode try to use existing .lck file first */
846                /* do not log errors for .lck file while in read ony mode on .lck file */
847                lock_file_mode = "rb";
848                info->lock.fp = php_stream_open_wrapper(lock_name, lock_file_mode, STREAM_MUST_SEEK|IGNORE_PATH|persistent_flag, &opened_path);
849            }
850            if (!info->lock.fp) {
851                /* when not in read mode or failed to open .lck file read only. now try again in create(write) mode and log errors */
852                lock_file_mode = "a+b";
853            } else {
854                if (!persistent) {
855                    info->lock.name = opened_path;
856                } else {
857                    if (opened_path) {
858                        info->lock.name = pestrdup(opened_path, persistent);
859                        efree(opened_path);
860                    }
861                }
862            }
863        }
864        if (!info->lock.fp) {
865            info->lock.fp = php_stream_open_wrapper(lock_name, lock_file_mode, STREAM_MUST_SEEK|REPORT_ERRORS|IGNORE_PATH|persistent_flag, &opened_path);
866            if (info->lock.fp) {
867                if (lock_dbf) {
868                    /* replace the path info with the real path of the opened file */
869                    pefree(info->path, persistent);
870                    info->path = pestrdup(opened_path, persistent);
871                }
872                /* now store the name of the lock */
873                if (!persistent) {
874                    info->lock.name = opened_path;
875                } else {
876                    info->lock.name = pestrdup(opened_path, persistent);
877                    efree(opened_path);
878                }
879            }
880        }
881        if (!lock_dbf) {
882            efree(lock_name);
883        }
884        if (!info->lock.fp) {
885            dba_close(info TSRMLS_CC);
886            /* stream operation already wrote an error message */
887            FREENOW;
888            RETURN_FALSE;
889        }
890        if (!php_stream_supports_lock(info->lock.fp)) {
891            error = "Stream does not support locking";
892        }
893        if (php_stream_lock(info->lock.fp, lock_mode)) {
894            error = "Unable to establish lock"; /* force failure exit */
895        }
896    }
897
898    /* centralised open stream for builtin */
899    if (!error && (hptr->flags&DBA_STREAM_OPEN)==DBA_STREAM_OPEN) {
900        if (info->lock.fp && lock_dbf) {
901            info->fp = info->lock.fp; /* use the same stream for locking and database access */
902        } else {
903            info->fp = php_stream_open_wrapper(info->path, file_mode, STREAM_MUST_SEEK|REPORT_ERRORS|IGNORE_PATH|persistent_flag, NULL);
904        }
905        if (!info->fp) {
906            dba_close(info TSRMLS_CC);
907            /* stream operation already wrote an error message */
908            FREENOW;
909            RETURN_FALSE;
910        }
911        if (hptr->flags & (DBA_NO_APPEND|DBA_CAST_AS_FD)) {
912            /* Needed because some systems do not allow to write to the original
913             * file contents with O_APPEND being set.
914             */
915            if (SUCCESS != php_stream_cast(info->fp, PHP_STREAM_AS_FD, (void*)&info->fd, 1)) {
916                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not cast stream");
917                dba_close(info TSRMLS_CC);
918                FREENOW;
919                RETURN_FALSE;
920#ifdef F_SETFL
921            } else if (modenr == DBA_CREAT) {
922                int flags = fcntl(info->fd, F_SETFL);
923                fcntl(info->fd, F_SETFL, flags & ~O_APPEND);
924#endif
925            }
926
927        }
928    }
929
930    if (error || hptr->open(info, &error TSRMLS_CC) != SUCCESS) {
931        dba_close(info TSRMLS_CC);
932        php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Driver initialization failed for handler: %s%s%s", hptr->name, error?": ":"", error?error:"");
933        FREENOW;
934        RETURN_FALSE;
935    }
936
937    info->hnd = hptr;
938    info->argc = 0;
939    info->argv = NULL;
940
941    if (persistent) {
942        zend_resource new_le;
943
944        new_le.type = le_pdb;
945        new_le.ptr = info;
946        if (zend_hash_str_update_mem(&EG(persistent_list), key, keylen, &new_le, sizeof(zend_resource)) == NULL) {
947            dba_close(info TSRMLS_CC);
948            php_error_docref2(NULL TSRMLS_CC, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Could not register persistent resource");
949            FREENOW;
950            RETURN_FALSE;
951        }
952    }
953
954    ZEND_REGISTER_RESOURCE(return_value, info, (persistent ? le_pdb : le_db));
955    FREENOW;
956}
957/* }}} */
958#undef FREENOW
959
960/* {{{ proto resource dba_popen(string path, string mode [, string handlername, string ...])
961   Opens path using the specified handler in mode persistently */
962PHP_FUNCTION(dba_popen)
963{
964    php_dba_open(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
965}
966/* }}} */
967
968/* {{{ proto resource dba_open(string path, string mode [, string handlername, string ...])
969   Opens path using the specified handler in mode*/
970PHP_FUNCTION(dba_open)
971{
972    php_dba_open(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
973}
974/* }}} */
975
976/* {{{ proto void dba_close(resource handle)
977   Closes database */
978PHP_FUNCTION(dba_close)
979{
980    zval *id;
981    dba_info *info = NULL;
982
983    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &id) == FAILURE) {
984        return;
985    }
986
987    DBA_FETCH_RESOURCE(info, id);
988
989    zend_list_close(Z_RES_P(id));
990}
991/* }}} */
992
993/* {{{ proto bool dba_exists(string key, resource handle)
994   Checks, if the specified key exists */
995PHP_FUNCTION(dba_exists)
996{
997    DBA_ID_GET2;
998
999    if(info->hnd->exists(info, key_str, key_len TSRMLS_CC) == SUCCESS) {
1000        DBA_ID_DONE;
1001        RETURN_TRUE;
1002    }
1003    DBA_ID_DONE;
1004    RETURN_FALSE;
1005}
1006/* }}} */
1007
1008/* {{{ proto string dba_fetch(string key, [int skip ,] resource handle)
1009   Fetches the data associated with key */
1010PHP_FUNCTION(dba_fetch)
1011{
1012    char *val;
1013    int len = 0;
1014    DBA_ID_GET2_3;
1015
1016    if (ac==3) {
1017        if (!strcmp(info->hnd->name, "cdb")) {
1018            if (skip < 0) {
1019                php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Handler %s accepts only skip values greater than or equal to zero, using skip=0", info->hnd->name);
1020                skip = 0;
1021            }
1022        } else if (!strcmp(info->hnd->name, "inifile")) {
1023            /* "-1" is compareable to 0 but allows a non restrictive
1024             * access which is fater. For example 'inifile' uses this
1025             * to allow faster access when the key was already found
1026             * using firstkey/nextkey. However explicitly setting the
1027             * value to 0 ensures the first value.
1028             */
1029            if (skip < -1) {
1030                php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Handler %s accepts only skip value -1 and greater, using skip=0", info->hnd->name);
1031                skip = 0;
1032            }
1033        } else {
1034            php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Handler %s does not support optional skip parameter, the value will be ignored", info->hnd->name);
1035            skip = 0;
1036        }
1037    } else {
1038        skip = 0;
1039    }
1040    if((val = info->hnd->fetch(info, key_str, key_len, skip, &len TSRMLS_CC)) != NULL) {
1041        DBA_ID_DONE;
1042        RETVAL_STRINGL(val, len);
1043        efree(val);
1044        return;
1045    }
1046    DBA_ID_DONE;
1047    RETURN_FALSE;
1048}
1049/* }}} */
1050
1051/* {{{ proto array|false dba_key_split(string key)
1052   Splits an inifile key into an array of the form array(0=>group,1=>value_name) but returns false if input is false or null */
1053PHP_FUNCTION(dba_key_split)
1054{
1055    zval *zkey;
1056    char *key, *name;
1057    size_t key_len;
1058
1059    if (ZEND_NUM_ARGS() != 1) {
1060        WRONG_PARAM_COUNT;
1061    }
1062    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &zkey) == SUCCESS) {
1063        if (Z_TYPE_P(zkey) == IS_NULL || (Z_TYPE_P(zkey) == IS_FALSE)) {
1064            RETURN_BOOL(0);
1065        }
1066    }
1067    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &key, &key_len) == FAILURE) {
1068        RETURN_BOOL(0);
1069    }
1070    array_init(return_value);
1071    if (key[0] == '[' && (name = strchr(key, ']')) != NULL) {
1072        add_next_index_stringl(return_value, key+1, name - (key + 1));
1073        add_next_index_stringl(return_value, name+1, key_len - (name - key + 1));
1074    } else {
1075        add_next_index_stringl(return_value, "", 0);
1076        add_next_index_stringl(return_value, key, key_len);
1077    }
1078}
1079/* }}} */
1080
1081/* {{{ proto string dba_firstkey(resource handle)
1082   Resets the internal key pointer and returns the first key */
1083PHP_FUNCTION(dba_firstkey)
1084{
1085    char *fkey;
1086    int len;
1087    zval *id;
1088    dba_info *info = NULL;
1089
1090    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &id) == FAILURE) {
1091        return;
1092    }
1093
1094    DBA_FETCH_RESOURCE(info, id);
1095
1096    fkey = info->hnd->firstkey(info, &len TSRMLS_CC);
1097
1098    if (fkey) {
1099        RETVAL_STRINGL(fkey, len);
1100        efree(fkey);
1101        return;
1102    }
1103
1104    RETURN_FALSE;
1105}
1106/* }}} */
1107
1108/* {{{ proto string dba_nextkey(resource handle)
1109   Returns the next key */
1110PHP_FUNCTION(dba_nextkey)
1111{
1112    char *nkey;
1113    int len;
1114    zval *id;
1115    dba_info *info = NULL;
1116
1117    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &id) == FAILURE) {
1118        return;
1119    }
1120
1121    DBA_FETCH_RESOURCE(info, id);
1122
1123    nkey = info->hnd->nextkey(info, &len TSRMLS_CC);
1124
1125    if (nkey) {
1126        RETVAL_STRINGL(nkey, len);
1127        efree(nkey);
1128        return;
1129    }
1130
1131    RETURN_FALSE;
1132}
1133/* }}} */
1134
1135/* {{{ proto bool dba_delete(string key, resource handle)
1136   Deletes the entry associated with key
1137   If inifile: remove all other key lines */
1138PHP_FUNCTION(dba_delete)
1139{
1140    DBA_ID_GET2;
1141
1142    DBA_WRITE_CHECK_WITH_ID;
1143
1144    if(info->hnd->delete(info, key_str, key_len TSRMLS_CC) == SUCCESS)
1145    {
1146        DBA_ID_DONE;
1147        RETURN_TRUE;
1148    }
1149    DBA_ID_DONE;
1150    RETURN_FALSE;
1151}
1152/* }}} */
1153
1154/* {{{ proto bool dba_insert(string key, string value, resource handle)
1155   If not inifile: Insert value as key, return false, if key exists already
1156   If inifile: Add vakue as key (next instance of key) */
1157PHP_FUNCTION(dba_insert)
1158{
1159    php_dba_update(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1160}
1161/* }}} */
1162
1163/* {{{ proto bool dba_replace(string key, string value, resource handle)
1164   Inserts value as key, replaces key, if key exists already
1165   If inifile: remove all other key lines */
1166PHP_FUNCTION(dba_replace)
1167{
1168    php_dba_update(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1169}
1170/* }}} */
1171
1172/* {{{ proto bool dba_optimize(resource handle)
1173   Optimizes (e.g. clean up, vacuum) database */
1174PHP_FUNCTION(dba_optimize)
1175{
1176    zval *id;
1177    dba_info *info = NULL;
1178
1179    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &id) == FAILURE) {
1180        return;
1181    }
1182
1183    DBA_FETCH_RESOURCE(info, id);
1184
1185    DBA_WRITE_CHECK;
1186
1187    if (info->hnd->optimize(info TSRMLS_CC) == SUCCESS) {
1188        RETURN_TRUE;
1189    }
1190
1191    RETURN_FALSE;
1192}
1193/* }}} */
1194
1195/* {{{ proto bool dba_sync(resource handle)
1196   Synchronizes database */
1197PHP_FUNCTION(dba_sync)
1198{
1199    zval *id;
1200    dba_info *info = NULL;
1201
1202    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &id) == FAILURE) {
1203        return;
1204    }
1205
1206    DBA_FETCH_RESOURCE(info, id);
1207
1208    if (info->hnd->sync(info TSRMLS_CC) == SUCCESS) {
1209        RETURN_TRUE;
1210    }
1211
1212    RETURN_FALSE;
1213}
1214/* }}} */
1215
1216/* {{{ proto array dba_handlers([bool full_info])
1217   List configured database handlers */
1218PHP_FUNCTION(dba_handlers)
1219{
1220    dba_handler *hptr;
1221    zend_bool full_info = 0;
1222
1223    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &full_info) == FAILURE) {
1224        RETURN_FALSE;
1225    }
1226
1227    array_init(return_value);
1228
1229    for(hptr = handler; hptr->name; hptr++) {
1230        if (full_info) {
1231            // TODO: avoid reallocation ???
1232            char *str = hptr->info(hptr, NULL TSRMLS_CC);
1233            add_assoc_string(return_value, hptr->name, str);
1234            efree(str);
1235        } else {
1236            add_next_index_string(return_value, hptr->name);
1237        }
1238    }
1239}
1240/* }}} */
1241
1242/* {{{ proto array dba_list()
1243   List opened databases */
1244PHP_FUNCTION(dba_list)
1245{
1246    zend_ulong numitems, i;
1247    zend_resource *le;
1248    dba_info *info;
1249
1250    if (zend_parse_parameters_none() == FAILURE) {
1251        RETURN_FALSE;
1252    }
1253
1254    array_init(return_value);
1255
1256    numitems = zend_hash_next_free_element(&EG(regular_list));
1257    for (i=1; i<numitems; i++) {
1258        if ((le = zend_hash_index_find_ptr(&EG(regular_list), i)) == NULL) {
1259            continue;
1260        }
1261        if (le->type == le_db || le->type == le_pdb) {
1262            info = (dba_info *)(le->ptr);
1263            add_index_string(return_value, i, info->path);
1264        }
1265    }
1266}
1267/* }}} */
1268
1269#endif /* HAVE_DBA */
1270
1271/*
1272 * Local variables:
1273 * tab-width: 4
1274 * c-basic-offset: 4
1275 * End:
1276 * vim600: sw=4 ts=4 fdm=marker
1277 * vim<600: sw=4 ts=4
1278 */
1279