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