1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2015 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    PHP_DBA_VERSION,
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)
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, 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, "zr", &key, &id) == FAILURE) {    \
249        return;                                                 \
250    }                                                           \
251    if ((key_len = php_dba_make_key(key, &key_str, &key_free)) == 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, "zr", &key, &id) == FAILURE) { \
263            return;                                             \
264        }                                                       \
265        break;                                                  \
266    case 3:                                                     \
267        if (zend_parse_parameters(ac, "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)) == 0) {\
275        RETURN_FALSE;                                           \
276    }
277
278
279#define DBA_FETCH_RESOURCE(info, id)    \
280    if ((info = (dba_info *)zend_fetch_resource2(Z_RES_P(id), "DBA identifier", le_db, le_pdb)) == NULL) { \
281        RETURN_FALSE; \
282    }
283
284#define DBA_ID_GET2   DBA_ID_PARS; DBA_GET2;   DBA_FETCH_RESOURCE(info, id)
285#define DBA_ID_GET2_3 DBA_ID_PARS; DBA_GET2_3; DBA_FETCH_RESOURCE(info, id)
286
287#define DBA_ID_DONE                                             \
288    if (key_free) efree(key_free)
289/* a DBA handler must have specific routines */
290
291#define DBA_NAMED_HND(alias, name, flags) \
292{\
293    #alias, flags, dba_open_##name, dba_close_##name, dba_fetch_##name, dba_update_##name, \
294    dba_exists_##name, dba_delete_##name, dba_firstkey_##name, dba_nextkey_##name, \
295    dba_optimize_##name, dba_sync_##name, dba_info_##name \
296},
297
298#define DBA_HND(name, flags) DBA_NAMED_HND(name, name, flags)
299
300/* check whether the user has write access */
301#define DBA_WRITE_CHECK \
302    if(info->mode != DBA_WRITER && info->mode != DBA_TRUNC && info->mode != DBA_CREAT) { \
303        php_error_docref(NULL, E_WARNING, "You cannot perform a modification to a database without proper access"); \
304        RETURN_FALSE; \
305    }
306
307/* the same check, but with a call to DBA_ID_DONE before returning */
308#define DBA_WRITE_CHECK_WITH_ID \
309    if(info->mode != DBA_WRITER && info->mode != DBA_TRUNC && info->mode != DBA_CREAT) { \
310        php_error_docref(NULL, E_WARNING, "You cannot perform a modification to a database without proper access"); \
311        DBA_ID_DONE; \
312        RETURN_FALSE; \
313    }
314
315/* }}} */
316
317/* {{{ globals */
318
319static dba_handler handler[] = {
320#if DBA_GDBM
321    DBA_HND(gdbm, DBA_LOCK_EXT) /* Locking done in library if set */
322#endif
323#if DBA_DBM
324    DBA_HND(dbm, DBA_LOCK_ALL) /* No lock in lib */
325#endif
326#if DBA_NDBM
327    DBA_HND(ndbm, DBA_LOCK_ALL) /* Could be done in library: filemode = 0644 + S_ENFMT */
328#endif
329#if DBA_CDB
330    DBA_HND(cdb, DBA_STREAM_OPEN|DBA_LOCK_ALL) /* No lock in lib */
331#endif
332#if DBA_CDB_BUILTIN
333    DBA_NAMED_HND(cdb_make, cdb, DBA_STREAM_OPEN|DBA_LOCK_ALL) /* No lock in lib */
334#endif
335#if DBA_DB1
336    DBA_HND(db1, DBA_LOCK_ALL) /* No lock in lib */
337#endif
338#if DBA_DB2
339    DBA_HND(db2, DBA_LOCK_ALL) /* No lock in lib */
340#endif
341#if DBA_DB3
342    DBA_HND(db3, DBA_LOCK_ALL) /* No lock in lib */
343#endif
344#if DBA_DB4
345    DBA_HND(db4, DBA_LOCK_ALL) /* No lock in lib */
346#endif
347#if DBA_INIFILE
348    DBA_HND(inifile, DBA_STREAM_OPEN|DBA_LOCK_ALL|DBA_CAST_AS_FD) /* No lock in lib */
349#endif
350#if DBA_FLATFILE
351    DBA_HND(flatfile, DBA_STREAM_OPEN|DBA_LOCK_ALL|DBA_NO_APPEND) /* No lock in lib */
352#endif
353#if DBA_QDBM
354    DBA_HND(qdbm, DBA_LOCK_EXT)
355#endif
356#if DBA_TCADB
357    DBA_HND(tcadb, DBA_LOCK_ALL)
358#endif
359    { NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
360};
361
362#if DBA_FLATFILE
363#define DBA_DEFAULT "flatfile"
364#elif DBA_DB4
365#define DBA_DEFAULT "db4"
366#elif DBA_DB3
367#define DBA_DEFAULT "db3"
368#elif DBA_DB2
369#define DBA_DEFAULT "db2"
370#elif DBA_DB1
371#define DBA_DEFAULT "db1"
372#elif DBA_GDBM
373#define DBA_DEFAULT "gdbm"
374#elif DBA_NBBM
375#define DBA_DEFAULT "ndbm"
376#elif DBA_DBM
377#define DBA_DEFAULT "dbm"
378#elif DBA_QDBM
379#define DBA_DEFAULT "qdbm"
380#elif DBA_TCADB
381#define DBA_DEFAULT "tcadb"
382#else
383#define DBA_DEFAULT ""
384#endif
385/* cdb/cdb_make and ini are no option here */
386
387static int le_db;
388static int le_pdb;
389/* }}} */
390
391/* {{{ dba_fetch_resource
392PHPAPI void dba_fetch_resource(dba_info **pinfo, zval **id)
393{
394    dba_info *info;
395    DBA_ID_FETCH
396    *pinfo = info;
397}
398*/
399/* }}} */
400
401/* {{{ dba_get_handler
402PHPAPI dba_handler *dba_get_handler(const char* handler_name)
403{
404    dba_handler *hptr;
405    for (hptr = handler; hptr->name && strcasecmp(hptr->name, handler_name); hptr++);
406    return hptr;
407}
408*/
409/* }}} */
410
411/* {{{ dba_close
412 */
413static void dba_close(dba_info *info)
414{
415    if (info->hnd) {
416        info->hnd->close(info);
417    }
418    if (info->path) {
419        pefree(info->path, info->flags&DBA_PERSISTENT);
420    }
421    if (info->fp && info->fp != info->lock.fp) {
422        if (info->flags & DBA_PERSISTENT) {
423            php_stream_pclose(info->fp);
424        } else {
425            php_stream_close(info->fp);
426        }
427    }
428    if (info->lock.fp) {
429        if (info->flags & DBA_PERSISTENT) {
430            php_stream_pclose(info->lock.fp);
431        } else {
432            php_stream_close(info->lock.fp);
433        }
434    }
435    if (info->lock.name) {
436        pefree(info->lock.name, info->flags&DBA_PERSISTENT);
437    }
438    pefree(info, info->flags&DBA_PERSISTENT);
439}
440/* }}} */
441
442/* {{{ dba_close_rsrc
443 */
444static void dba_close_rsrc(zend_resource *rsrc)
445{
446    dba_info *info = (dba_info *)rsrc->ptr;
447
448    dba_close(info);
449}
450/* }}} */
451
452/* {{{ dba_close_pe_rsrc_deleter */
453int dba_close_pe_rsrc_deleter(zval *el, void *pDba)
454{
455    if (Z_RES_P(el)->ptr == pDba) {
456        if (Z_DELREF_P(el) == 0) {
457            return ZEND_HASH_APPLY_REMOVE;
458        } else {
459            return ZEND_HASH_APPLY_KEEP | ZEND_HASH_APPLY_STOP;
460        }
461    } else {
462        return ZEND_HASH_APPLY_KEEP;
463    }
464}
465/* }}} */
466
467/* {{{ dba_close_pe_rsrc */
468static void dba_close_pe_rsrc(zend_resource *rsrc)
469{
470    dba_info *info = (dba_info *)rsrc->ptr;
471
472    /* closes the resource by calling dba_close_rsrc() */
473    zend_hash_apply_with_argument(&EG(persistent_list), dba_close_pe_rsrc_deleter, info);
474}
475/* }}} */
476
477/* {{{ PHP_INI
478 */
479ZEND_INI_MH(OnUpdateDefaultHandler)
480{
481    dba_handler *hptr;
482
483    if (!new_value->len) {
484        DBA_G(default_hptr) = NULL;
485        return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
486    }
487
488    for (hptr = handler; hptr->name && strcasecmp(hptr->name, new_value->val); hptr++);
489
490    if (!hptr->name) {
491        php_error_docref(NULL, E_WARNING, "No such handler: %s", new_value->val);
492        return FAILURE;
493    }
494    DBA_G(default_hptr) = hptr;
495    return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
496}
497
498PHP_INI_BEGIN()
499    STD_PHP_INI_ENTRY("dba.default_handler", DBA_DEFAULT, PHP_INI_ALL, OnUpdateDefaultHandler, default_handler,    zend_dba_globals, dba_globals)
500PHP_INI_END()
501/* }}} */
502
503/* {{{ PHP_GINIT_FUNCTION
504 */
505static PHP_GINIT_FUNCTION(dba)
506{
507    dba_globals->default_handler = "";
508    dba_globals->default_hptr    = NULL;
509}
510/* }}} */
511
512/* {{{ PHP_MINIT_FUNCTION
513 */
514PHP_MINIT_FUNCTION(dba)
515{
516    REGISTER_INI_ENTRIES();
517    le_db = zend_register_list_destructors_ex(dba_close_rsrc, NULL, "dba", module_number);
518    le_pdb = zend_register_list_destructors_ex(dba_close_pe_rsrc, dba_close_rsrc, "dba persistent", module_number);
519    return SUCCESS;
520}
521/* }}} */
522
523/* {{{ PHP_MSHUTDOWN_FUNCTION
524 */
525PHP_MSHUTDOWN_FUNCTION(dba)
526{
527    UNREGISTER_INI_ENTRIES();
528    return SUCCESS;
529}
530/* }}} */
531
532#include "zend_smart_str.h"
533
534/* {{{ PHP_MINFO_FUNCTION
535 */
536PHP_MINFO_FUNCTION(dba)
537{
538    dba_handler *hptr;
539    smart_str handlers = {0};
540
541    for(hptr = handler; hptr->name; hptr++) {
542        smart_str_appends(&handlers, hptr->name);
543        smart_str_appendc(&handlers, ' ');
544    }
545
546    php_info_print_table_start();
547    php_info_print_table_row(2, "DBA support", "enabled");
548    if (handlers.s) {
549        smart_str_0(&handlers);
550        php_info_print_table_row(2, "Supported handlers", handlers.s->val);
551        smart_str_free(&handlers);
552    } else {
553        php_info_print_table_row(2, "Supported handlers", "none");
554    }
555    php_info_print_table_end();
556    DISPLAY_INI_ENTRIES();
557}
558/* }}} */
559
560/* {{{ php_dba_update
561 */
562static void php_dba_update(INTERNAL_FUNCTION_PARAMETERS, int mode)
563{
564    size_t val_len;
565    zval *id;
566    dba_info *info = NULL;
567    int ac = ZEND_NUM_ARGS();
568    zval *key;
569    char *val;
570    char *key_str, *key_free;
571    size_t key_len;
572
573    if (zend_parse_parameters(ac, "zsr", &key, &val, &val_len, &id) == FAILURE) {
574        return;
575    }
576
577    if ((key_len = php_dba_make_key(key, &key_str, &key_free)) == 0) {
578        RETURN_FALSE;
579    }
580
581    DBA_FETCH_RESOURCE(info, id);
582
583    DBA_WRITE_CHECK_WITH_ID;
584
585    if (info->hnd->update(info, key_str, key_len, val, val_len, mode) == SUCCESS) {
586        DBA_ID_DONE;
587        RETURN_TRUE;
588    }
589
590    DBA_ID_DONE;
591    RETURN_FALSE;
592}
593/* }}} */
594
595#define FREENOW if(args) {int i; for (i=0; i<ac; i++) { zval_ptr_dtor(&args[i]); } efree(args);} if(key) efree(key)
596
597/* {{{ php_find_dbm
598 */
599dba_info *php_dba_find(const char* path)
600{
601    zend_resource *le;
602    dba_info *info;
603    int numitems, i;
604
605    numitems = zend_hash_next_free_element(&EG(regular_list));
606    for (i=1; i<numitems; i++) {
607        if ((le = zend_hash_index_find_ptr(&EG(regular_list), i)) == NULL) {
608            continue;
609        }
610        if (le->type == le_db || le->type == le_pdb) {
611            info = (dba_info *)(le->ptr);
612            if (!strcmp(info->path, path)) {
613                return (dba_info *)(le->ptr);
614            }
615        }
616    }
617
618    return NULL;
619}
620/* }}} */
621
622/* {{{ php_dba_open
623 */
624static void php_dba_open(INTERNAL_FUNCTION_PARAMETERS, int persistent)
625{
626    zval *args = NULL;
627    int ac = ZEND_NUM_ARGS();
628    dba_mode_t modenr;
629    dba_info *info, *other;
630    dba_handler *hptr;
631    char *key = NULL, *error = NULL;
632    int keylen = 0;
633    int i;
634    int lock_mode, lock_flag, lock_dbf = 0;
635    char *file_mode;
636    char mode[4], *pmode, *lock_file_mode = NULL;
637    int persistent_flag = persistent ? STREAM_OPEN_PERSISTENT : 0;
638    zend_string *opened_path = NULL;
639    char *lock_name;
640
641    if (ac < 2) {
642        WRONG_PARAM_COUNT;
643    }
644
645    /* we pass additional args to the respective handler */
646    args = safe_emalloc(ac, sizeof(zval), 0);
647    if (zend_get_parameters_array_ex(ac, args) != SUCCESS) {
648        efree(args);
649        WRONG_PARAM_COUNT;
650    }
651
652    /* we only take string arguments */
653    for (i = 0; i < ac; i++) {
654        if (Z_TYPE(args[i]) != IS_STRING) {
655            convert_to_string_ex(&args[i]);
656        } else if (Z_REFCOUNTED(args[i])) {
657            Z_ADDREF(args[i]);
658        }
659        keylen += Z_STRLEN(args[i]);
660    }
661
662    if (persistent) {
663        zend_resource *le;
664
665        /* calculate hash */
666        key = safe_emalloc(keylen, 1, 1);
667        key[keylen] = '\0';
668        keylen = 0;
669
670        for(i = 0; i < ac; i++) {
671            memcpy(key+keylen, Z_STRVAL(args[i]), Z_STRLEN(args[i]));
672            keylen += Z_STRLEN(args[i]);
673        }
674
675        /* try to find if we already have this link in our persistent list */
676        if ((le = zend_hash_str_find_ptr(&EG(persistent_list), key, keylen)) != NULL) {
677            FREENOW;
678
679            if (le->type != le_pdb) {
680                RETURN_FALSE;
681            }
682
683            info = (dba_info *)le->ptr;
684
685            GC_REFCOUNT(le)++;
686            RETURN_RES(zend_register_resource(info, le_pdb));
687            return;
688        }
689    }
690
691    if (ac==2) {
692        hptr = DBA_G(default_hptr);
693        if (!hptr) {
694            php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "No default handler selected");
695            FREENOW;
696            RETURN_FALSE;
697        }
698    } else {
699        for (hptr = handler; hptr->name && strcasecmp(hptr->name, Z_STRVAL(args[2])); hptr++);
700    }
701
702    if (!hptr->name) {
703        php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "No such handler: %s", Z_STRVAL(args[2]));
704        FREENOW;
705        RETURN_FALSE;
706    }
707
708    /* Check mode: [rwnc][fl]?t?
709     * r: Read
710     * w: Write
711     * n: Create/Truncate
712     * c: Create
713     *
714     * d: force lock on database file
715     * l: force lock on lck file
716     * -: ignore locking
717     *
718     * t: test open database, warning if locked
719     */
720    strlcpy(mode, Z_STRVAL(args[1]), sizeof(mode));
721    pmode = &mode[0];
722    if (pmode[0] && (pmode[1]=='d' || pmode[1]=='l' || pmode[1]=='-')) { /* force lock on db file or lck file or disable locking */
723        switch (pmode[1]) {
724        case 'd':
725            lock_dbf = 1;
726            if ((hptr->flags & DBA_LOCK_ALL) == 0) {
727                lock_flag = (hptr->flags & DBA_LOCK_ALL);
728                break;
729            }
730            /* no break */
731        case 'l':
732            lock_flag = DBA_LOCK_ALL;
733            if ((hptr->flags & DBA_LOCK_ALL) == 0) {
734                php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_NOTICE, "Handler %s does locking internally", hptr->name);
735            }
736            break;
737        default:
738        case '-':
739            if ((hptr->flags & DBA_LOCK_ALL) == 0) {
740                php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Locking cannot be disabled for handler %s", hptr->name);
741                FREENOW;
742                RETURN_FALSE;
743            }
744            lock_flag = 0;
745            break;
746        }
747    } else {
748        lock_flag = (hptr->flags&DBA_LOCK_ALL);
749        lock_dbf = 1;
750    }
751    switch (*pmode++) {
752        case 'r':
753            modenr = DBA_READER;
754            lock_mode = (lock_flag & DBA_LOCK_READER) ? LOCK_SH : 0;
755            file_mode = "r";
756            break;
757        case 'w':
758            modenr = DBA_WRITER;
759            lock_mode = (lock_flag & DBA_LOCK_WRITER) ? LOCK_EX : 0;
760            file_mode = "r+b";
761            break;
762        case 'c':
763            modenr = DBA_CREAT;
764            lock_mode = (lock_flag & DBA_LOCK_CREAT) ? LOCK_EX : 0;
765            if (lock_mode) {
766                if (lock_dbf) {
767                    /* the create/append check will be done on the lock
768                     * when the lib opens the file it is already created
769                     */
770                    file_mode = "r+b";       /* read & write, seek 0 */
771                    lock_file_mode = "a+b";  /* append */
772                } else {
773                    file_mode = "a+b";       /* append */
774                    lock_file_mode = "w+b";  /* create/truncate */
775                }
776            } else {
777                file_mode = "a+b";
778            }
779            /* In case of the 'a+b' append mode, the handler is responsible
780             * to handle any rewind problems (see flatfile handler).
781             */
782            break;
783        case 'n':
784            modenr = DBA_TRUNC;
785            lock_mode = (lock_flag & DBA_LOCK_TRUNC) ? LOCK_EX : 0;
786            file_mode = "w+b";
787            break;
788        default:
789            php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Illegal DBA mode");
790            FREENOW;
791            RETURN_FALSE;
792    }
793    if (!lock_file_mode) {
794        lock_file_mode = file_mode;
795    }
796    if (*pmode=='d' || *pmode=='l' || *pmode=='-') {
797        pmode++; /* done already - skip here */
798    }
799    if (*pmode=='t') {
800        pmode++;
801        if (!lock_flag) {
802            php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "You cannot combine modifiers - (no lock) and t (test lock)");
803            FREENOW;
804            RETURN_FALSE;
805        }
806        if (!lock_mode) {
807            if ((hptr->flags & DBA_LOCK_ALL) == 0) {
808                php_error_docref2(NULL, 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);
809                FREENOW;
810                RETURN_FALSE;
811            } else {
812                php_error_docref2(NULL, 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);
813                FREENOW;
814                RETURN_FALSE;
815            }
816        } else {
817            lock_mode |= LOCK_NB; /* test =: non blocking */
818        }
819    }
820    if (*pmode) {
821        php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Illegal DBA mode");
822        FREENOW;
823        RETURN_FALSE;
824    }
825
826    info = pemalloc(sizeof(dba_info), persistent);
827    memset(info, 0, sizeof(dba_info));
828    info->path = pestrdup(Z_STRVAL(args[0]), persistent);
829    info->mode = modenr;
830    info->argc = ac - 3;
831    info->argv = args + 3;
832    info->flags = (hptr->flags & ~DBA_LOCK_ALL) | (lock_flag & DBA_LOCK_ALL) | (persistent ? DBA_PERSISTENT : 0);
833    info->lock.mode = lock_mode;
834
835    /* if any open call is a locking call:
836     * check if we already habe a locking call open that should block this call
837     * the problem is some systems would allow read during write
838     */
839    if (hptr->flags & DBA_LOCK_ALL) {
840        if ((other = php_dba_find(info->path)) != NULL) {
841            if (   ( (lock_mode&LOCK_EX)        && (other->lock.mode&(LOCK_EX|LOCK_SH)) )
842                || ( (other->lock.mode&LOCK_EX) && (lock_mode&(LOCK_EX|LOCK_SH))        )
843               ) {
844                error = "Unable to establish lock (database file already open)"; /* force failure exit */
845            }
846        }
847    }
848
849    if (!error && lock_mode) {
850        if (lock_dbf) {
851            lock_name = Z_STRVAL(args[0]);
852        } else {
853            spprintf(&lock_name, 0, "%s.lck", info->path);
854            if (!strcmp(file_mode, "r")) {
855                /* when in read only mode try to use existing .lck file first */
856                /* do not log errors for .lck file while in read ony mode on .lck file */
857                lock_file_mode = "rb";
858                info->lock.fp = php_stream_open_wrapper(lock_name, lock_file_mode, STREAM_MUST_SEEK|IGNORE_PATH|persistent_flag, &opened_path);
859            }
860            if (!info->lock.fp) {
861                /* when not in read mode or failed to open .lck file read only. now try again in create(write) mode and log errors */
862                lock_file_mode = "a+b";
863            } else {
864                if (opened_path) {
865                    info->lock.name = pestrndup(opened_path->val, opened_path->len, persistent);
866                    zend_string_release(opened_path);
867                }
868            }
869        }
870        if (!info->lock.fp) {
871            info->lock.fp = php_stream_open_wrapper(lock_name, lock_file_mode, STREAM_MUST_SEEK|REPORT_ERRORS|IGNORE_PATH|persistent_flag, &opened_path);
872            if (info->lock.fp) {
873                if (lock_dbf) {
874                    /* replace the path info with the real path of the opened file */
875                    pefree(info->path, persistent);
876                    info->path = pestrndup(opened_path->val, opened_path->len, persistent);
877                }
878                /* now store the name of the lock */
879                info->lock.name = pestrndup(opened_path->val, opened_path->len, persistent);
880                zend_string_release(opened_path);
881            }
882        }
883        if (!lock_dbf) {
884            efree(lock_name);
885        }
886        if (!info->lock.fp) {
887            dba_close(info);
888            /* stream operation already wrote an error message */
889            FREENOW;
890            RETURN_FALSE;
891        }
892        if (!php_stream_supports_lock(info->lock.fp)) {
893            error = "Stream does not support locking";
894        }
895        if (php_stream_lock(info->lock.fp, lock_mode)) {
896            error = "Unable to establish lock"; /* force failure exit */
897        }
898    }
899
900    /* centralised open stream for builtin */
901    if (!error && (hptr->flags&DBA_STREAM_OPEN)==DBA_STREAM_OPEN) {
902        if (info->lock.fp && lock_dbf) {
903            info->fp = info->lock.fp; /* use the same stream for locking and database access */
904        } else {
905            info->fp = php_stream_open_wrapper(info->path, file_mode, STREAM_MUST_SEEK|REPORT_ERRORS|IGNORE_PATH|persistent_flag, NULL);
906        }
907        if (!info->fp) {
908            dba_close(info);
909            /* stream operation already wrote an error message */
910            FREENOW;
911            RETURN_FALSE;
912        }
913        if (hptr->flags & (DBA_NO_APPEND|DBA_CAST_AS_FD)) {
914            /* Needed because some systems do not allow to write to the original
915             * file contents with O_APPEND being set.
916             */
917            if (SUCCESS != php_stream_cast(info->fp, PHP_STREAM_AS_FD, (void*)&info->fd, 1)) {
918                php_error_docref(NULL, E_WARNING, "Could not cast stream");
919                dba_close(info);
920                FREENOW;
921                RETURN_FALSE;
922#ifdef F_SETFL
923            } else if (modenr == DBA_CREAT) {
924                int flags = fcntl(info->fd, F_GETFL);
925                fcntl(info->fd, F_SETFL, flags & ~O_APPEND);
926#endif
927            }
928
929        }
930    }
931
932    if (error || hptr->open(info, &error) != SUCCESS) {
933        dba_close(info);
934        php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Driver initialization failed for handler: %s%s%s", hptr->name, error?": ":"", error?error:"");
935        FREENOW;
936        RETURN_FALSE;
937    }
938
939    info->hnd = hptr;
940    info->argc = 0;
941    info->argv = NULL;
942
943    if (persistent) {
944        zval new_le;
945
946        ZVAL_NEW_PERSISTENT_RES(&new_le, -1, info, le_pdb);
947        if (zend_hash_str_update(&EG(persistent_list), key, keylen, &new_le) == NULL) {
948            dba_close(info);
949            php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Could not register persistent resource");
950            FREENOW;
951            RETURN_FALSE;
952        }
953    }
954
955    RETVAL_RES(zend_register_resource(info, (persistent ? le_pdb : le_db)));
956    FREENOW;
957}
958/* }}} */
959#undef FREENOW
960
961/* {{{ proto resource dba_popen(string path, string mode [, string handlername, string ...])
962   Opens path using the specified handler in mode persistently */
963PHP_FUNCTION(dba_popen)
964{
965    php_dba_open(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
966}
967/* }}} */
968
969/* {{{ proto resource dba_open(string path, string mode [, string handlername, string ...])
970   Opens path using the specified handler in mode*/
971PHP_FUNCTION(dba_open)
972{
973    php_dba_open(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
974}
975/* }}} */
976
977/* {{{ proto void dba_close(resource handle)
978   Closes database */
979PHP_FUNCTION(dba_close)
980{
981    zval *id;
982    dba_info *info = NULL;
983
984    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &id) == FAILURE) {
985        return;
986    }
987
988    DBA_FETCH_RESOURCE(info, id);
989
990    zend_list_close(Z_RES_P(id));
991}
992/* }}} */
993
994/* {{{ proto bool dba_exists(string key, resource handle)
995   Checks, if the specified key exists */
996PHP_FUNCTION(dba_exists)
997{
998    DBA_ID_GET2;
999
1000    if(info->hnd->exists(info, key_str, key_len) == SUCCESS) {
1001        DBA_ID_DONE;
1002        RETURN_TRUE;
1003    }
1004    DBA_ID_DONE;
1005    RETURN_FALSE;
1006}
1007/* }}} */
1008
1009/* {{{ proto string dba_fetch(string key, [int skip ,] resource handle)
1010   Fetches the data associated with key */
1011PHP_FUNCTION(dba_fetch)
1012{
1013    char *val;
1014    int len = 0;
1015    DBA_ID_GET2_3;
1016
1017    if (ac==3) {
1018        if (!strcmp(info->hnd->name, "cdb")) {
1019            if (skip < 0) {
1020                php_error_docref(NULL, E_NOTICE, "Handler %s accepts only skip values greater than or equal to zero, using skip=0", info->hnd->name);
1021                skip = 0;
1022            }
1023        } else if (!strcmp(info->hnd->name, "inifile")) {
1024            /* "-1" is compareable to 0 but allows a non restrictive
1025             * access which is fater. For example 'inifile' uses this
1026             * to allow faster access when the key was already found
1027             * using firstkey/nextkey. However explicitly setting the
1028             * value to 0 ensures the first value.
1029             */
1030            if (skip < -1) {
1031                php_error_docref(NULL, E_NOTICE, "Handler %s accepts only skip value -1 and greater, using skip=0", info->hnd->name);
1032                skip = 0;
1033            }
1034        } else {
1035            php_error_docref(NULL, E_NOTICE, "Handler %s does not support optional skip parameter, the value will be ignored", info->hnd->name);
1036            skip = 0;
1037        }
1038    } else {
1039        skip = 0;
1040    }
1041    if((val = info->hnd->fetch(info, key_str, key_len, skip, &len)) != NULL) {
1042        DBA_ID_DONE;
1043        RETVAL_STRINGL(val, len);
1044        efree(val);
1045        return;
1046    }
1047    DBA_ID_DONE;
1048    RETURN_FALSE;
1049}
1050/* }}} */
1051
1052/* {{{ proto array|false dba_key_split(string key)
1053   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 */
1054PHP_FUNCTION(dba_key_split)
1055{
1056    zval *zkey;
1057    char *key, *name;
1058    size_t key_len;
1059
1060    if (ZEND_NUM_ARGS() != 1) {
1061        WRONG_PARAM_COUNT;
1062    }
1063    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "z", &zkey) == SUCCESS) {
1064        if (Z_TYPE_P(zkey) == IS_NULL || (Z_TYPE_P(zkey) == IS_FALSE)) {
1065            RETURN_BOOL(0);
1066        }
1067    }
1068    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &key, &key_len) == FAILURE) {
1069        RETURN_BOOL(0);
1070    }
1071    array_init(return_value);
1072    if (key[0] == '[' && (name = strchr(key, ']')) != NULL) {
1073        add_next_index_stringl(return_value, key+1, name - (key + 1));
1074        add_next_index_stringl(return_value, name+1, key_len - (name - key + 1));
1075    } else {
1076        add_next_index_stringl(return_value, "", 0);
1077        add_next_index_stringl(return_value, key, key_len);
1078    }
1079}
1080/* }}} */
1081
1082/* {{{ proto string dba_firstkey(resource handle)
1083   Resets the internal key pointer and returns the first key */
1084PHP_FUNCTION(dba_firstkey)
1085{
1086    char *fkey;
1087    int len;
1088    zval *id;
1089    dba_info *info = NULL;
1090
1091    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &id) == FAILURE) {
1092        return;
1093    }
1094
1095    DBA_FETCH_RESOURCE(info, id);
1096
1097    fkey = info->hnd->firstkey(info, &len);
1098
1099    if (fkey) {
1100        RETVAL_STRINGL(fkey, len);
1101        efree(fkey);
1102        return;
1103    }
1104
1105    RETURN_FALSE;
1106}
1107/* }}} */
1108
1109/* {{{ proto string dba_nextkey(resource handle)
1110   Returns the next key */
1111PHP_FUNCTION(dba_nextkey)
1112{
1113    char *nkey;
1114    int len;
1115    zval *id;
1116    dba_info *info = NULL;
1117
1118    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &id) == FAILURE) {
1119        return;
1120    }
1121
1122    DBA_FETCH_RESOURCE(info, id);
1123
1124    nkey = info->hnd->nextkey(info, &len);
1125
1126    if (nkey) {
1127        RETVAL_STRINGL(nkey, len);
1128        efree(nkey);
1129        return;
1130    }
1131
1132    RETURN_FALSE;
1133}
1134/* }}} */
1135
1136/* {{{ proto bool dba_delete(string key, resource handle)
1137   Deletes the entry associated with key
1138   If inifile: remove all other key lines */
1139PHP_FUNCTION(dba_delete)
1140{
1141    DBA_ID_GET2;
1142
1143    DBA_WRITE_CHECK_WITH_ID;
1144
1145    if(info->hnd->delete(info, key_str, key_len) == SUCCESS)
1146    {
1147        DBA_ID_DONE;
1148        RETURN_TRUE;
1149    }
1150    DBA_ID_DONE;
1151    RETURN_FALSE;
1152}
1153/* }}} */
1154
1155/* {{{ proto bool dba_insert(string key, string value, resource handle)
1156   If not inifile: Insert value as key, return false, if key exists already
1157   If inifile: Add vakue as key (next instance of key) */
1158PHP_FUNCTION(dba_insert)
1159{
1160    php_dba_update(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1161}
1162/* }}} */
1163
1164/* {{{ proto bool dba_replace(string key, string value, resource handle)
1165   Inserts value as key, replaces key, if key exists already
1166   If inifile: remove all other key lines */
1167PHP_FUNCTION(dba_replace)
1168{
1169    php_dba_update(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1170}
1171/* }}} */
1172
1173/* {{{ proto bool dba_optimize(resource handle)
1174   Optimizes (e.g. clean up, vacuum) database */
1175PHP_FUNCTION(dba_optimize)
1176{
1177    zval *id;
1178    dba_info *info = NULL;
1179
1180    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &id) == FAILURE) {
1181        return;
1182    }
1183
1184    DBA_FETCH_RESOURCE(info, id);
1185
1186    DBA_WRITE_CHECK;
1187
1188    if (info->hnd->optimize(info) == SUCCESS) {
1189        RETURN_TRUE;
1190    }
1191
1192    RETURN_FALSE;
1193}
1194/* }}} */
1195
1196/* {{{ proto bool dba_sync(resource handle)
1197   Synchronizes database */
1198PHP_FUNCTION(dba_sync)
1199{
1200    zval *id;
1201    dba_info *info = NULL;
1202
1203    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &id) == FAILURE) {
1204        return;
1205    }
1206
1207    DBA_FETCH_RESOURCE(info, id);
1208
1209    if (info->hnd->sync(info) == SUCCESS) {
1210        RETURN_TRUE;
1211    }
1212
1213    RETURN_FALSE;
1214}
1215/* }}} */
1216
1217/* {{{ proto array dba_handlers([bool full_info])
1218   List configured database handlers */
1219PHP_FUNCTION(dba_handlers)
1220{
1221    dba_handler *hptr;
1222    zend_bool full_info = 0;
1223
1224    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &full_info) == FAILURE) {
1225        RETURN_FALSE;
1226    }
1227
1228    array_init(return_value);
1229
1230    for(hptr = handler; hptr->name; hptr++) {
1231        if (full_info) {
1232            // TODO: avoid reallocation ???
1233            char *str = hptr->info(hptr, NULL);
1234            add_assoc_string(return_value, hptr->name, str);
1235            efree(str);
1236        } else {
1237            add_next_index_string(return_value, hptr->name);
1238        }
1239    }
1240}
1241/* }}} */
1242
1243/* {{{ proto array dba_list()
1244   List opened databases */
1245PHP_FUNCTION(dba_list)
1246{
1247    zend_ulong numitems, i;
1248    zend_resource *le;
1249    dba_info *info;
1250
1251    if (zend_parse_parameters_none() == FAILURE) {
1252        RETURN_FALSE;
1253    }
1254
1255    array_init(return_value);
1256
1257    numitems = zend_hash_next_free_element(&EG(regular_list));
1258    for (i=1; i<numitems; i++) {
1259        if ((le = zend_hash_index_find_ptr(&EG(regular_list), i)) == NULL) {
1260            continue;
1261        }
1262        if (le->type == le_db || le->type == le_pdb) {
1263            info = (dba_info *)(le->ptr);
1264            add_index_string(return_value, i, info->path);
1265        }
1266    }
1267}
1268/* }}} */
1269
1270#endif /* HAVE_DBA */
1271
1272/*
1273 * Local variables:
1274 * tab-width: 4
1275 * c-basic-offset: 4
1276 * End:
1277 * vim600: sw=4 ts=4 fdm=marker
1278 * vim<600: sw=4 ts=4
1279 */
1280