source: tags/ms_r16q3/ARBDB/arbdb.cxx

Last change on this file was 15279, checked in by westram, 8 years ago
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 85.5 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : arbdb.cxx                                         //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include "gb_key.h"
12#include "gb_comm.h"
13#include "gb_compress.h"
14#include "gb_localdata.h"
15#include "gb_ta.h"
16#include "gb_ts.h"
17#include "gb_index.h"
18
19#include <rpc/types.h>
20#include <rpc/xdr.h>
21#include <arb_misc.h>
22
23gb_local_data *gb_local = 0;
24
25#define INIT_TYPE_NAME(t) GB_TYPES_name[t] = #t
26
27static const char *GB_TYPES_2_name(GB_TYPES type) {
28    static const char *GB_TYPES_name[GB_TYPE_MAX];
29    static bool        initialized = false;
30
31    if (!initialized) {
32        memset(GB_TYPES_name, 0, sizeof(GB_TYPES_name));
33        INIT_TYPE_NAME(GB_NONE);
34        INIT_TYPE_NAME(GB_BIT);
35        INIT_TYPE_NAME(GB_BYTE);
36        INIT_TYPE_NAME(GB_INT);
37        INIT_TYPE_NAME(GB_FLOAT);
38        INIT_TYPE_NAME(GB_POINTER);
39        INIT_TYPE_NAME(GB_BITS);
40        INIT_TYPE_NAME(GB_BYTES);
41        INIT_TYPE_NAME(GB_INTS);
42        INIT_TYPE_NAME(GB_FLOATS);
43        INIT_TYPE_NAME(GB_LINK);
44        INIT_TYPE_NAME(GB_STRING);
45        INIT_TYPE_NAME(GB_STRING_SHRT);
46        INIT_TYPE_NAME(GB_DB);
47        initialized = true;
48    }
49
50    const char *name = NULL;
51    if (type >= 0 && type<GB_TYPE_MAX) name = GB_TYPES_name[type];
52    if (!name) {
53        static char *unknownType = 0;
54        freeset(unknownType, GBS_global_string_copy("<invalid-type=%i>", type));
55        name = unknownType;
56    }
57    return name;
58}
59
60const char *GB_get_type_name(GBDATA *gbd) {
61    return GB_TYPES_2_name(gbd->type());
62}
63
64inline GB_ERROR gb_transactable_type(GB_TYPES type, GBDATA *gbd) {
65    GB_ERROR error = NULL;
66    if (GB_MAIN(gbd)->get_transaction_level() == 0) {
67        error = "No transaction running";
68    }
69    else if (GB_ARRAY_FLAGS(gbd).changed == GB_DELETED) {
70        error = "Entry has been deleted";
71    }
72    else {
73        GB_TYPES gb_type = gbd->type();
74        if (gb_type != type && (type != GB_STRING || gb_type != GB_LINK)) {
75            char *rtype    = ARB_strdup(GB_TYPES_2_name(type));
76            char *rgb_type = ARB_strdup(GB_TYPES_2_name(gb_type));
77           
78            error = GBS_global_string("type mismatch (want='%s', got='%s') in '%s'", rtype, rgb_type, GB_get_db_path(gbd));
79
80            free(rgb_type);
81            free(rtype);
82        }
83    }
84    if (error) {
85        GBK_dump_backtrace(stderr, error); // it's a bug: none of the above errors should ever happen
86        gb_assert(0);
87    }
88    return error;
89}
90
91__ATTR__USERESULT static GB_ERROR gb_security_error(GBDATA *gbd) {
92    GB_MAIN_TYPE *Main  = GB_MAIN(gbd);
93    const char   *error = GBS_global_string("Protection: Attempt to change a level-%i-'%s'-entry,\n"
94                                            "but your current security level is only %i",
95                                            GB_GET_SECURITY_WRITE(gbd),
96                                            GB_read_key_pntr(gbd),
97                                            Main->security_level);
98#if defined(DEBUG)
99    fprintf(stderr, "%s\n", error);
100#endif // DEBUG
101    return error;
102}
103
104inline GB_ERROR gb_type_writeable_to(GB_TYPES type, GBDATA *gbd) {
105    GB_ERROR error = gb_transactable_type(type, gbd);
106    if (!error) {
107        if (GB_GET_SECURITY_WRITE(gbd) > GB_MAIN(gbd)->security_level) {
108            error = gb_security_error(gbd);
109        }
110    }
111    return error;
112}
113inline GB_ERROR gb_type_readable_from(GB_TYPES type, GBDATA *gbd) {
114    return gb_transactable_type(type, gbd);
115}
116
117inline GB_ERROR error_with_dbentry(const char *action, GBDATA *gbd, GB_ERROR error) {
118    if (error) {
119        char       *error_copy = ARB_strdup(error);
120        const char *path       = GB_get_db_path(gbd);
121        error                  = GBS_global_string("Can't %s '%s':\n%s", action, path, error_copy);
122        free(error_copy);
123    }
124    return error;
125}
126
127
128#define RETURN_ERROR_IF_NOT_WRITEABLE_AS_TYPE(gbd, type)        \
129    do {                                                        \
130        GB_ERROR error = gb_type_writeable_to(type, gbd);       \
131        if (error) {                                            \
132            return error_with_dbentry("write", gbd, error);     \
133        }                                                       \
134    } while(0)
135
136#define EXPORT_ERROR_AND_RETURN_0_IF_NOT_READABLE_AS_TYPE(gbd, type)    \
137    do {                                                                \
138        GB_ERROR error = gb_type_readable_from(type, gbd);              \
139        if (error) {                                                    \
140            error = error_with_dbentry("read", gbd, error);             \
141            GB_export_error(error);                                     \
142            return 0;                                                   \
143        }                                                               \
144    } while(0)                                                          \
145
146
147#if defined(WARN_TODO)
148#warning replace GB_TEST_READ / GB_TEST_READ by new names later
149#endif
150
151#define GB_TEST_READ(gbd, type, ignored) EXPORT_ERROR_AND_RETURN_0_IF_NOT_READABLE_AS_TYPE(gbd, type)
152#define GB_TEST_WRITE(gbd, type, ignored) RETURN_ERROR_IF_NOT_WRITEABLE_AS_TYPE(gbd, type)
153
154#define GB_TEST_NON_BUFFER(x, gerror)                                   \
155    do {                                                                \
156        if (GB_is_in_buffer(x)) {                                       \
157            GBK_terminatef("%s: you are not allowed to write any data, which you get by pntr", gerror); \
158        }                                                               \
159    } while (0)
160
161
162static GB_ERROR GB_safe_atof(const char *str, float *res) {
163    GB_ERROR error = NULL;
164
165    char *end;
166    *res = strtof(str, &end);
167
168    if (end == str || end[0] != 0) {
169        if (!str[0]) {
170            *res = 0.0;
171        }
172        else {
173            error = GBS_global_string("cannot convert '%s' to float", str);
174        }
175    }
176    return error;
177}
178
179float GB_atof(const char *str) {
180    // convert ASCII to float
181    float    res = 0;
182    GB_ERROR err = GB_safe_atof(str, &res);
183    if (err) {
184        // expected float in 'str'- better use GB_safe_atof()
185        GBK_terminatef("GB_safe_atof(\"%s\", ..) returns error: %s", str, err);
186    }
187    return res;
188}
189
190// ---------------------------
191//      compression tables
192
193const int gb_convert_type_2_compression_flags[] = {
194    GB_COMPRESSION_NONE,                                                                 // GB_NONE  0
195    GB_COMPRESSION_NONE,                                                                 // GB_BIT   1
196    GB_COMPRESSION_NONE,                                                                 // GB_BYTE  2
197    GB_COMPRESSION_NONE,                                                                 // GB_INT   3
198    GB_COMPRESSION_NONE,                                                                 // GB_FLOAT 4
199    GB_COMPRESSION_NONE,                                                                 // GB_??    5
200    GB_COMPRESSION_BITS,                                                                 // GB_BITS  6
201    GB_COMPRESSION_NONE,                                                                 // GB_??    7
202    GB_COMPRESSION_RUNLENGTH | GB_COMPRESSION_HUFFMANN,                                  // GB_BYTES 8
203    GB_COMPRESSION_RUNLENGTH | GB_COMPRESSION_HUFFMANN | GB_COMPRESSION_SORTBYTES,       // GB_INTS  9
204    GB_COMPRESSION_RUNLENGTH | GB_COMPRESSION_HUFFMANN | GB_COMPRESSION_SORTBYTES,       // GB_FLTS 10
205    GB_COMPRESSION_NONE,                                                                 // GB_LINK 11
206    GB_COMPRESSION_RUNLENGTH | GB_COMPRESSION_HUFFMANN | GB_COMPRESSION_DICTIONARY,      // GB_STR  12
207    GB_COMPRESSION_NONE,                                                                 // GB_STRS 13
208    GB_COMPRESSION_NONE,                                                                 // GB??    14
209    GB_COMPRESSION_NONE                                                                  // GB_DB   15
210};
211
212int gb_convert_type_2_sizeof[] = { /* contains the unit-size of data stored in DB,
213                                    * i.e. realsize = unit_size * size()
214                                    */
215    0,                                              // GB_NONE  0
216    0,                                              // GB_BIT   1
217    sizeof(char),                                   // GB_BYTE  2
218    sizeof(int),                                    // GB_INT   3
219    sizeof(float),                                  // GB_FLOAT 4
220    0,                                              // GB_??    5
221    0,                                              // GB_BITS  6
222    0,                                              // GB_??    7
223    sizeof(char),                                   // GB_BYTES 8
224    sizeof(int),                                    // GB_INTS  9
225    sizeof(float),                                  // GB_FLTS 10
226    sizeof(char),                                   // GB_LINK 11
227    sizeof(char),                                   // GB_STR  12
228    sizeof(char),                                   // GB_STRS 13
229    0,                                              // GB_??   14
230    0,                                              // GB_DB   15
231};
232
233int gb_convert_type_2_appendix_size[] = { /* contains the size of the suffix (aka terminator element)
234                                           * size is in bytes
235                                           */
236
237    0,                                              // GB_NONE  0
238    0,                                              // GB_BIT   1
239    0,                                              // GB_BYTE  2
240    0,                                              // GB_INT   3
241    0,                                              // GB_FLOAT 4
242    0,                                              // GB_??    5
243    0,                                              // GB_BITS  6
244    0,                                              // GB_??    7
245    0,                                              // GB_BYTES 8
246    0,                                              // GB_INTS  9
247    0,                                              // GB_FLTS 10
248    1,                                              // GB_LINK 11 (zero terminated)
249    1,                                              // GB_STR  12 (zero terminated)
250    1,                                              // GB_STRS 13 (zero terminated)
251    0,                                              // GB_??   14
252    0,                                              // GB_DB   15
253};
254
255
256// ---------------------------------
257//      local buffer management
258
259static void init_buffer(gb_buffer *buf, size_t initial_size) {
260    buf->size = initial_size;
261    buf->mem  = buf->size ? ARB_alloc<char>(buf->size) : NULL;
262}
263
264static char *check_out_buffer(gb_buffer *buf) {
265    char *checkOut = buf->mem;
266
267    buf->mem  = 0;
268    buf->size = 0;
269
270    return checkOut;
271}
272
273static void alloc_buffer(gb_buffer *buf, size_t size) {
274    free(buf->mem);
275    buf->size = size;
276#if (MEMORY_TEST==1)
277    ARB_alloc(buf->mem, buf->size);
278#else
279    ARB_calloc(buf->mem, buf->size);
280#endif
281}
282
283static GB_BUFFER give_buffer(gb_buffer *buf, size_t size) {
284#if (MEMORY_TEST==1)
285    alloc_buffer(buf, size); // do NOT reuse buffer if testing memory
286#else
287    if (size >= buf->size) {
288        alloc_buffer(buf, size);
289    }
290#endif
291    return buf->mem;
292}
293
294static int is_in_buffer(gb_buffer *buf, GB_CBUFFER ptr) {
295    return ptr >= buf->mem && ptr < buf->mem+buf->size;
296}
297
298// ------------------------------
299
300GB_BUFFER GB_give_buffer(size_t size) {
301    // return a pointer to a static piece of memory at least size bytes long
302    return give_buffer(&gb_local->buf1, size);
303}
304
305GB_BUFFER GB_increase_buffer(size_t size) {
306    if (size < gb_local->buf1.size) {
307        char   *old_buffer = gb_local->buf1.mem;
308        size_t  old_size   = gb_local->buf1.size;
309
310        gb_local->buf1.mem = NULL;
311        alloc_buffer(&gb_local->buf1, size);
312        memcpy(gb_local->buf1.mem, old_buffer, old_size);
313
314        free(old_buffer);
315    }
316    return gb_local->buf1.mem;
317}
318
319NOT4PERL int GB_give_buffer_size() {
320    return gb_local->buf1.size;
321}
322
323GB_BUFFER GB_give_buffer2(long size) {
324    return give_buffer(&gb_local->buf2, size);
325}
326
327static int GB_is_in_buffer(GB_CBUFFER ptr) {
328    /* returns 1 or 2 if 'ptr' points to gb_local->buf1/buf2
329     * returns 0 otherwise
330     */
331    int buffer = 0;
332
333    if (is_in_buffer(&gb_local->buf1, ptr)) buffer = 1;
334    else if (is_in_buffer(&gb_local->buf2, ptr)) buffer = 2;
335
336    return buffer;
337}
338
339char *GB_check_out_buffer(GB_CBUFFER buffer) {
340    /* Check a piece of memory out of the buffer management
341     * after it is checked out, the user has the full control to use and free it
342     * Returns a pointer to the start of the buffer (even if 'buffer' points inside the buffer!)
343     */
344    char *old = 0;
345
346    if (is_in_buffer(&gb_local->buf1, buffer)) old = check_out_buffer(&gb_local->buf1);
347    else if (is_in_buffer(&gb_local->buf2, buffer)) old = check_out_buffer(&gb_local->buf2);
348
349    return old;
350}
351
352GB_BUFFER GB_give_other_buffer(GB_CBUFFER buffer, long size) {
353    return is_in_buffer(&gb_local->buf1, buffer)
354        ? GB_give_buffer2(size)
355        : GB_give_buffer(size);
356}
357
358static unsigned char GB_BIT_compress_data[] = {
359    0x1d, GB_CS_OK,  0, 0,
360    0x04, GB_CS_OK,  0, 1,
361    0x0a, GB_CS_OK,  0, 2,
362    0x0b, GB_CS_OK,  0, 3,
363    0x0c, GB_CS_OK,  0, 4,
364    0x1a, GB_CS_OK,  0, 5,
365    0x1b, GB_CS_OK,  0, 6,
366    0x1c, GB_CS_OK,  0, 7,
367    0xf0, GB_CS_OK,  0, 8,
368    0xf1, GB_CS_OK,  0, 9,
369    0xf2, GB_CS_OK,  0, 10,
370    0xf3, GB_CS_OK,  0, 11,
371    0xf4, GB_CS_OK,  0, 12,
372    0xf5, GB_CS_OK,  0, 13,
373    0xf6, GB_CS_OK,  0, 14,
374    0xf7, GB_CS_OK,  0, 15,
375    0xf8, GB_CS_SUB, 0, 16,
376    0xf9, GB_CS_SUB, 0, 32,
377    0xfa, GB_CS_SUB, 0, 48,
378    0xfb, GB_CS_SUB, 0, 64,
379    0xfc, GB_CS_SUB, 0, 128,
380    0xfd, GB_CS_SUB, 1, 0,
381    0xfe, GB_CS_SUB, 2, 0,
382    0xff, GB_CS_SUB, 4, 0,
383    0
384};
385
386struct gb_exitfun {
387    void (*exitfun)();
388    gb_exitfun *next;
389};
390
391void GB_atexit(void (*exitfun)()) {
392    // called when GB_shell is destroyed (use similar to atexit())
393    //
394    // Since the program does not neccessarily terminate, your code calling
395    // GB_atexit() may run multiple times. Make sure everything is completely reset by your 'exitfun'
396
397    gb_exitfun *fun = new gb_exitfun;
398    fun->exitfun    = exitfun;
399
400    fun->next          = gb_local->atgbexit;
401    gb_local->atgbexit = fun;
402}
403
404static void run_and_destroy_exit_functions(gb_exitfun *fun) {
405    if (fun) {
406        fun->exitfun();
407        run_and_destroy_exit_functions(fun->next);
408        delete fun;
409    }
410}
411
412static void GB_exit_gb() {
413    GB_shell::ensure_inside();
414
415    if (gb_local) {
416        gb_local->~gb_local_data(); // inplace-dtor
417        gbm_free_mem(gb_local, sizeof(*gb_local), 0);
418        gb_local = NULL;
419        gbm_flush_mem();
420    }
421}
422
423gb_local_data::~gb_local_data() {
424    gb_assert(openedDBs == closedDBs);
425
426    run_and_destroy_exit_functions(atgbexit);
427
428    free(bitcompress);
429    gb_free_compress_tree(bituncompress);
430    free(write_buffer);
431
432    free(check_out_buffer(&buf2));
433    free(check_out_buffer(&buf1));
434    free(open_gb_mains);
435}
436
437// -----------------
438//      GB_shell
439
440
441static GB_shell *inside_shell = NULL;
442
443GB_shell::GB_shell() {
444    if (inside_shell) GBK_terminate("only one GB_shell allowed");
445    inside_shell = this;
446}
447GB_shell::~GB_shell() {
448    gb_assert(inside_shell == this);
449    GB_exit_gb();
450    inside_shell = NULL;
451}
452void GB_shell::ensure_inside()  { if (!inside_shell) GBK_terminate("Not inside GB_shell"); }
453
454bool GB_shell::in_shell() { // used by code based on ARBDB (Kai IIRC)
455    return inside_shell;
456}
457
458struct GB_test_shell_closed {
459    ~GB_test_shell_closed() {
460        if (GB_shell::in_shell()) { // leave that call
461            inside_shell->~GB_shell(); // call dtor
462        }
463    }
464};
465static GB_test_shell_closed test;
466
467#if defined(UNIT_TESTS)
468static bool closed_open_shell_for_unit_tests() {
469    bool was_open = inside_shell;
470    if (was_open) {
471        if (gb_local) gb_local->fake_closed_DBs();
472        inside_shell->~GB_shell(); // just call dtor (not delete)
473    }
474    return was_open;
475}
476#endif
477
478void GB_init_gb() {
479    GB_shell::ensure_inside();
480    if (!gb_local) {
481        GBK_install_SIGSEGV_handler(true);          // never uninstalled
482        gbm_init_mem();
483        gb_local = (gb_local_data *)gbm_get_mem(sizeof(gb_local_data), 0);
484        ::new(gb_local) gb_local_data(); // inplace-ctor
485    }
486}
487
488int GB_open_DBs() { return gb_local ? gb_local->open_dbs() : 0; }
489
490gb_local_data::gb_local_data()
491{
492    init_buffer(&buf1, 4000);
493    init_buffer(&buf2, 4000);
494
495    write_bufsize = GBCM_BUFFER;
496    ARB_alloc(write_buffer, write_bufsize);
497
498    write_ptr  = write_buffer;
499    write_free = write_bufsize;
500
501    bituncompress = gb_build_uncompress_tree(GB_BIT_compress_data, 1, 0);
502    bitcompress   = gb_build_compress_list(GB_BIT_compress_data, 1, &(bc_size));
503
504    openedDBs = 0;
505    closedDBs = 0;
506
507    open_gb_mains = NULL;
508    open_gb_alloc = 0;
509
510    atgbexit = NULL;
511
512    iamclient                  = false;
513    search_system_folder       = false;
514    running_client_transaction = ARB_NO_TRANS;
515}
516
517void gb_local_data::announce_db_open(GB_MAIN_TYPE *Main) {
518    gb_assert(Main);
519    int idx = open_dbs();
520    if (idx >= open_gb_alloc) {
521        int new_alloc = open_gb_alloc + 10;
522        ARB_recalloc(open_gb_mains, open_gb_alloc, new_alloc);
523        open_gb_alloc = new_alloc;
524    }
525    open_gb_mains[idx] = Main;
526    openedDBs++;
527}
528
529void gb_local_data::announce_db_close(GB_MAIN_TYPE *Main) {
530    gb_assert(Main);
531    int open = open_dbs();
532    int idx;
533    for (idx = 0; idx<open; ++idx) if (open_gb_mains[idx] == Main) break;
534
535    gb_assert(idx<open); // passed gb_main is unknown
536    if (idx<open) {
537        if (idx<(open-1)) { // not last
538            open_gb_mains[idx] = open_gb_mains[open-1];
539        }
540        closedDBs++;
541    }
542    if (closedDBs == openedDBs) {
543        GB_exit_gb(); // free most memory allocated by ARBDB library
544        // Caution: calling GB_exit_gb() frees 'this'!
545    }
546}
547
548static GBDATA *gb_remembered_db() {
549    GB_MAIN_TYPE *Main = gb_local ? gb_local->get_any_open_db() : NULL;
550    return Main ? Main->gb_main() : NULL;
551}
552
553GB_ERROR gb_unfold(GBCONTAINER *gbc, long deep, int index_pos) {
554    /*! get data from server.
555     *
556     * @param gbc container to unfold
557     * @param deep if != 0, then get subitems too.
558     * @param index_pos
559     * - >= 0, get indexed item from server
560     * - <0, get all items
561     *
562     * @return error on failure
563     */
564
565    GB_ERROR        error;
566    gb_header_list *header = GB_DATA_LIST_HEADER(gbc->d);
567
568    if (!gbc->flags2.folded_container) return 0;
569    if (index_pos> gbc->d.nheader) gb_create_header_array(gbc, index_pos + 1);
570    if (index_pos >= 0  && GB_HEADER_LIST_GBD(header[index_pos])) return 0;
571
572    if (GBCONTAINER_MAIN(gbc)->is_server()) {
573        GB_internal_error("Cannot unfold in server");
574        return 0;
575    }
576
577    do {
578        if (index_pos<0) break;
579        if (index_pos >= gbc->d.nheader) break;
580        if (header[index_pos].flags.changed >= GB_DELETED) {
581            GB_internal_error("Tried to unfold a deleted item");
582            return 0;
583        }
584        if (GB_HEADER_LIST_GBD(header[index_pos])) return 0;            // already unfolded
585    } while (0);
586
587    error = gbcm_unfold_client(gbc, deep, index_pos);
588    if (error) {
589        GB_print_error();
590        return error;
591    }
592
593    if (index_pos<0) {
594        gb_untouch_children(gbc);
595        gbc->flags2.folded_container = 0;
596    }
597    else {
598        GBDATA *gb2 = GBCONTAINER_ELEM(gbc, index_pos);
599        if (gb2) {
600            if (gb2->is_container()) {
601                gb_untouch_children_and_me(gb2->as_container());
602            }
603            else {
604                gb_untouch_me(gb2->as_entry());
605            }
606        }
607    }
608    return 0;
609}
610
611// -----------------------
612//      close database
613
614typedef void (*gb_close_callback)(GBDATA *gb_main, void *client_data);
615
616struct gb_close_callback_list {
617    gb_close_callback_list *next;
618    gb_close_callback       cb;
619    void                   *client_data;
620};
621
622#if defined(ASSERTION_USED)
623static bool atclose_cb_exists(gb_close_callback_list *gccs, gb_close_callback cb) {
624    return gccs && (gccs->cb == cb || atclose_cb_exists(gccs->next, cb));
625}
626#endif // ASSERTION_USED
627
628void GB_atclose(GBDATA *gbd, void (*fun)(GBDATA *gb_main, void *client_data), void *client_data) {
629    /*! Add a callback, which gets called directly before GB_close destroys all data.
630     * This is the recommended way to remove all callbacks from DB elements.
631     */
632
633    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
634
635    gb_assert(!atclose_cb_exists(Main->close_callbacks, fun)); // each close callback should only exist once
636
637    gb_close_callback_list *gccs = ARB_alloc<gb_close_callback_list>(1);
638
639    gccs->next        = Main->close_callbacks;
640    gccs->cb          = fun;
641    gccs->client_data = client_data;
642
643    Main->close_callbacks = gccs;
644}
645
646static void run_close_callbacks(GBDATA *gb_main, gb_close_callback_list *gccs) {
647    while (gccs) {
648        gccs->cb(gb_main, gccs->client_data);
649        gb_close_callback_list *next = gccs->next;
650        free(gccs);
651        gccs = next;
652    }
653}
654
655void GB_close(GBDATA *gbd) {
656    GB_ERROR      error = NULL;
657    GB_MAIN_TYPE *Main  = GB_MAIN(gbd);
658
659    gb_assert(Main->get_transaction_level() <= 0); // transaction running - you can't close DB yet!
660
661    Main->forget_hierarchy_cbs();
662
663    gb_assert(Main->gb_main() == gbd);
664    run_close_callbacks(gbd, Main->close_callbacks);
665    Main->close_callbacks = 0;
666
667    bool quick_exit = Main->mapped;
668    if (Main->is_client()) {
669        GBCM_ServerResult result = gbcmc_close(Main->c_link);
670        if (result != GBCM_SERVER_OK) error = GBS_global_string("close failed (with %i:%s)", result, GB_await_error());
671
672        gb_assert(!quick_exit); // client cannot be mapped
673    }
674
675    gbcm_logout(Main, NULL); // logout default user
676
677    if (!error) {
678        gb_assert(Main->close_callbacks == 0);
679
680#if defined(LEAKS_SANITIZED)
681        quick_exit = false;
682#endif
683
684        if (quick_exit) {
685            // fake some data to allow quick-exit
686            Main->dummy_father = NULL;
687            Main->cache.entries = NULL;
688        }
689        else {
690            // proper cleanup of DB (causes unwanted behavior described in #649)
691            gb_delete_dummy_father(Main->dummy_father);
692        }
693        Main->root_container = NULL;
694
695        /* ARBDB applications using awars easily crash in call_pending_callbacks(),
696         * if AWARs are still bound to elements in the closed database.
697         *
698         * To unlink awars call AW_root::unlink_awars_from_DB().
699         * If that doesn't help, test Main->data (often aka as GLOBAL_gb_main)
700         */
701        Main->call_pending_callbacks(); // do all callbacks
702        delete Main;
703    }
704
705    if (error) {
706        GB_warningf("Error in GB_close: %s", error);
707    }
708}
709
710void gb_abort_and_close_all_DBs() {
711    GBDATA *gb_main;
712    while ((gb_main = gb_remembered_db())) {
713        // abort any open transactions
714        GB_MAIN_TYPE *Main = GB_MAIN(gb_main);
715        while (Main->get_transaction_level()>0) {
716            GB_ERROR error = Main->abort_transaction();
717            if (error) {
718                fprintf(stderr, "Error in gb_abort_and_close_all_DBs: %s\n", error);
719            }
720        }
721        // and close DB
722        GB_close(gb_main);
723    }
724}
725
726// ------------------
727//      read data
728
729long GB_read_int(GBDATA *gbd)
730{
731    GB_TEST_READ(gbd, GB_INT, "GB_read_int");
732    return gbd->as_entry()->info.i;
733}
734
735int GB_read_byte(GBDATA *gbd)
736{
737    GB_TEST_READ(gbd, GB_BYTE, "GB_read_byte");
738    return gbd->as_entry()->info.i;
739}
740
741GBDATA *GB_read_pointer(GBDATA *gbd) {
742    GB_TEST_READ(gbd, GB_POINTER, "GB_read_pointer");
743    return gbd->as_entry()->info.ptr;
744}
745
746float GB_read_float(GBDATA *gbd) {
747    XDR   xdrs;
748    float f;
749
750    GB_TEST_READ(gbd, GB_FLOAT, "GB_read_float");
751    xdrmem_create(&xdrs, &gbd->as_entry()->info.in.data[0], SIZOFINTERN, XDR_DECODE);
752    xdr_float(&xdrs, &f);
753    xdr_destroy(&xdrs);
754
755    gb_assert(f == f); // !nan
756
757    return f;
758}
759
760long GB_read_count(GBDATA *gbd) {
761    return gbd->as_entry()->size();
762}
763
764long GB_read_memuse(GBDATA *gbd) {
765    return gbd->as_entry()->memsize();
766}
767
768#if defined(DEBUG)
769
770#define MIN_CBLISTNODE_SIZE 48 // minimum (found) callbacklist-elementsize
771
772#if defined(DARWIN)
773
774#define CBLISTNODE_SIZE MIN_CBLISTNODE_SIZE // assume known minimum (doesnt really matter; only used in db-browser)
775
776#else // linux:
777
778typedef std::_List_node<gb_callback_list::cbtype> CBLISTNODE_TYPE;
779const size_t CBLISTNODE_SIZE = sizeof(CBLISTNODE_TYPE);
780
781#if defined(ARB_64)
782// ignore smaller 32-bit implementations
783STATIC_ASSERT_ANNOTATED(MIN_CBLISTNODE_SIZE<=CBLISTNODE_SIZE, "MIN_CBLISTNODE_SIZE too big (smaller implementation detected)");
784#endif
785
786#endif
787
788inline long calc_size(gb_callback_list *gbcbl) {
789    return gbcbl
790        ? sizeof(*gbcbl) + gbcbl->callbacks.size()* CBLISTNODE_SIZE
791        : 0;
792}
793inline long calc_size(gb_transaction_save *gbts) {
794    return gbts
795        ? sizeof(*gbts)
796        : 0;
797}
798inline long calc_size(gb_if_entries *gbie) {
799    return gbie
800        ? sizeof(*gbie) + calc_size(GB_IF_ENTRIES_NEXT(gbie))
801        : 0;
802}
803inline long calc_size(GB_REL_IFES *gbri, int table_size) {
804    long size = 0;
805
806    gb_if_entries *ifes;
807    for (int idx = 0; idx<table_size; ++idx) {
808        for (ifes = GB_ENTRIES_ENTRY(gbri, idx);
809             ifes;
810             ifes = GB_IF_ENTRIES_NEXT(ifes))
811        {
812            size += calc_size(ifes);
813        }
814    }
815    return size;
816}
817inline long calc_size(gb_index_files *gbif) {
818    return gbif
819        ? sizeof(*gbif) + calc_size(GB_INDEX_FILES_NEXT(gbif)) + calc_size(GB_INDEX_FILES_ENTRIES(gbif), gbif->hash_table_size)
820        : 0;
821}
822inline long calc_size(gb_db_extended *gbe) {
823    return gbe
824        ? sizeof(*gbe) + calc_size(gbe->callback) + calc_size(gbe->old)
825        : 0;
826}
827inline long calc_size(GBENTRY *gbe) {
828    return gbe
829        ? sizeof(*gbe) + calc_size(gbe->ext)
830        : 0;
831}
832inline long calc_size(GBCONTAINER *gbc) {
833    return gbc
834        ? sizeof(*gbc) + calc_size(gbc->ext) + calc_size(GBCONTAINER_IFS(gbc))
835        : 0;
836}
837
838long GB_calc_structure_size(GBDATA *gbd) {
839    long size = 0;
840    if (gbd->is_container()) {
841        size = calc_size(gbd->as_container());
842    }
843    else {
844        size = calc_size(gbd->as_entry());
845    }
846    return size;
847}
848
849void GB_SizeInfo::collect(GBDATA *gbd) {
850    if (gbd->is_container()) {
851        ++containers;
852        for (GBDATA *gb_child = GB_child(gbd); gb_child; gb_child = GB_nextChild(gb_child)) {
853            collect(gb_child);
854        }
855    }
856    else {
857        ++terminals;
858        mem += GB_read_memuse(gbd);
859
860        long size;
861        switch (gbd->type()) {
862            case GB_INT:     size = sizeof(int); break;
863            case GB_FLOAT:   size = sizeof(float); break;
864            case GB_BYTE:    size = sizeof(char); break;
865            case GB_POINTER: size = sizeof(GBDATA*); break;
866            case GB_STRING:  size = GB_read_count(gbd); break; // accept 0 sized data for strings
867
868            default:
869                size = GB_read_count(gbd);
870                gb_assert(size>0);                            // terminal w/o data - really?
871                break;
872        }
873        data += size;
874    }
875    structure += GB_calc_structure_size(gbd);
876}
877#endif
878
879GB_CSTR GB_read_pntr(GBDATA *gbd) {
880    GBENTRY    *gbe  = gbd->as_entry();
881    const char *data = gbe->data();
882
883    if (data) {
884        if (gbe->flags.compressed_data) {   // uncompressed data return pntr to database entry
885            char *ca = gb_read_cache(gbe);
886
887            if (!ca) {
888                size_t      size = gbe->uncompressed_size();
889                const char *da   = gb_uncompress_data(gbe, data, size);
890
891                if (da) {
892                    ca = gb_alloc_cache_index(gbe, size);
893                    memcpy(ca, da, size);
894                }
895            }
896            data = ca;
897        }
898    }
899    return data;
900}
901
902int gb_read_nr(GBDATA *gbd) {
903    return gbd->index;
904}
905
906GB_CSTR GB_read_char_pntr(GBDATA *gbd) {
907    GB_TEST_READ(gbd, GB_STRING, "GB_read_char_pntr");
908    return GB_read_pntr(gbd);
909}
910
911char *GB_read_string(GBDATA *gbd) {
912    GB_TEST_READ(gbd, GB_STRING, "GB_read_string");
913    const char *d = GB_read_pntr(gbd);
914    if (!d) return NULL;
915    return GB_memdup(d, gbd->as_entry()->size()+1);
916}
917
918size_t GB_read_string_count(GBDATA *gbd) {
919    GB_TEST_READ(gbd, GB_STRING, "GB_read_string_count");
920    return gbd->as_entry()->size();
921}
922
923GB_CSTR GB_read_link_pntr(GBDATA *gbd) {
924    GB_TEST_READ(gbd, GB_LINK, "GB_read_link_pntr");
925    return GB_read_pntr(gbd);
926}
927
928static char *GB_read_link(GBDATA *gbd) {
929    const char *d;
930    GB_TEST_READ(gbd, GB_LINK, "GB_read_link_pntr");
931    d = GB_read_pntr(gbd);
932    if (!d) return NULL;
933    return GB_memdup(d, gbd->as_entry()->size()+1);
934}
935
936long GB_read_bits_count(GBDATA *gbd) {
937    GB_TEST_READ(gbd, GB_BITS, "GB_read_bits_count");
938    return gbd->as_entry()->size();
939}
940
941GB_CSTR GB_read_bits_pntr(GBDATA *gbd, char c_0, char c_1) {
942    GB_TEST_READ(gbd, GB_BITS, "GB_read_bits_pntr");
943    GBENTRY *gbe  = gbd->as_entry();
944    long     size = gbe->size();
945    if (size) {
946        char *ca = gb_read_cache(gbe);
947        if (ca) return ca;
948
949        ca               = gb_alloc_cache_index(gbe, size+1);
950        const char *data = gbe->data();
951        char       *da   = gb_uncompress_bits(data, size, c_0, c_1);
952        if (ca) {
953            memcpy(ca, da, size+1);
954            return ca;
955        }
956        return da;
957    }
958    return 0;
959}
960
961char *GB_read_bits(GBDATA *gbd, char c_0, char c_1) {
962    GB_CSTR d = GB_read_bits_pntr(gbd, c_0, c_1);
963    return d ? GB_memdup(d, gbd->as_entry()->size()+1) : 0;
964}
965
966
967GB_CSTR GB_read_bytes_pntr(GBDATA *gbd)
968{
969    GB_TEST_READ(gbd, GB_BYTES, "GB_read_bytes_pntr");
970    return GB_read_pntr(gbd);
971}
972
973long GB_read_bytes_count(GBDATA *gbd)
974{
975    GB_TEST_READ(gbd, GB_BYTES, "GB_read_bytes_count");
976    return gbd->as_entry()->size();
977}
978
979char *GB_read_bytes(GBDATA *gbd) {
980    GB_CSTR d = GB_read_bytes_pntr(gbd);
981    return d ? GB_memdup(d, gbd->as_entry()->size()) : 0;
982}
983
984GB_CUINT4 *GB_read_ints_pntr(GBDATA *gbd)
985{
986    GB_TEST_READ(gbd, GB_INTS, "GB_read_ints_pntr");
987    GBENTRY *gbe = gbd->as_entry();
988
989    GB_UINT4 *res;
990    if (gbe->flags.compressed_data) {
991        res = (GB_UINT4 *)GB_read_pntr(gbe);
992    }
993    else {
994        res = (GB_UINT4 *)gbe->data();
995    }
996    if (!res) return NULL;
997
998    if (0x01020304U == htonl(0x01020304U)) {
999        return res;
1000    }
1001    else {
1002        int       size = gbe->size();
1003        char     *buf2 = GB_give_other_buffer((char *)res, size<<2);
1004        GB_UINT4 *s    = (GB_UINT4 *)res;
1005        GB_UINT4 *d    = (GB_UINT4 *)buf2;
1006
1007        for (long i=size; i; i--) {
1008            *(d++) = htonl(*(s++));
1009        }
1010        return (GB_UINT4 *)buf2;
1011    }
1012}
1013
1014long GB_read_ints_count(GBDATA *gbd) { // used by ../PERL_SCRIPTS/SAI/SAI.pm@read_ints_count
1015    GB_TEST_READ(gbd, GB_INTS, "GB_read_ints_count");
1016    return gbd->as_entry()->size();
1017}
1018
1019GB_UINT4 *GB_read_ints(GBDATA *gbd)
1020{
1021    GB_CUINT4 *i = GB_read_ints_pntr(gbd);
1022    if (!i) return NULL;
1023    return  (GB_UINT4 *)GB_memdup((char *)i, gbd->as_entry()->size()*sizeof(GB_UINT4));
1024}
1025
1026GB_CFLOAT *GB_read_floats_pntr(GBDATA *gbd)
1027{
1028    GB_TEST_READ(gbd, GB_FLOATS, "GB_read_floats_pntr");
1029    GBENTRY *gbe = gbd->as_entry();
1030    char    *res;
1031    if (gbe->flags.compressed_data) {
1032        res = (char *)GB_read_pntr(gbe);
1033    }
1034    else {
1035        res = (char *)gbe->data();
1036    }
1037    if (res) {
1038        long size      = gbe->size();
1039        long full_size = size*sizeof(float);
1040
1041        XDR xdrs;
1042        xdrmem_create(&xdrs, res, (int)(full_size), XDR_DECODE);
1043
1044        char  *buf2 = GB_give_other_buffer(res, full_size);
1045        float *d    = (float *)(void*)buf2;
1046        for (long i=size; i; i--) {
1047            xdr_float(&xdrs, d);
1048            d++;
1049        }
1050        xdr_destroy(&xdrs);
1051        return (float *)(void*)buf2;
1052    }
1053    return NULL;
1054}
1055
1056static long GB_read_floats_count(GBDATA *gbd)
1057{
1058    GB_TEST_READ(gbd, GB_FLOATS, "GB_read_floats_count");
1059    return gbd->as_entry()->size();
1060}
1061
1062float *GB_read_floats(GBDATA *gbd) { // @@@ only used in unittest - check usage of floats
1063    GB_CFLOAT *f;
1064    f = GB_read_floats_pntr(gbd);
1065    if (!f) return NULL;
1066    return  (float *)GB_memdup((char *)f, gbd->as_entry()->size()*sizeof(float));
1067}
1068
1069char *GB_read_as_string(GBDATA *gbd) {
1070    /*! reads basic db-field types and returns content as text.
1071     * @see GB_write_autoconv_string
1072     */
1073    switch (gbd->type()) {
1074        case GB_STRING: return GB_read_string(gbd);
1075        case GB_LINK:   return GB_read_link(gbd);
1076        case GB_BYTE:   return GBS_global_string_copy("%i", GB_read_byte(gbd));
1077        case GB_INT:    return GBS_global_string_copy("%li", GB_read_int(gbd));
1078        case GB_FLOAT:  return ARB_strdup(ARB_float_2_ascii(GB_read_float(gbd)));
1079        case GB_BITS:   return GB_read_bits(gbd, '0', '1');
1080            /* Be careful : When adding new types here, you have to make sure that
1081             * GB_write_autoconv_string is able to write them back and that this makes sense.
1082             */
1083        default:    return NULL;
1084    }
1085}
1086
1087inline GB_ERROR cannot_use_fun4entry(const char *fun, GBDATA *gb_entry) {
1088    return GBS_global_string("Error: Cannot use %s() with a field of type %i (field=%s)",
1089                             fun,
1090                             GB_read_type(gb_entry),
1091                             GB_read_key_pntr(gb_entry));
1092}
1093
1094NOT4PERL uint8_t GB_read_lossless_byte(GBDATA *gbd, GB_ERROR& error) {
1095    /*! Reads an uint8_t previously written with GB_write_lossless_byte()
1096     * @param gbd    the DB field
1097     * @param error  result parameter (has to be NULL)
1098     * @result is undefined if error != NULL; contains read value otherwise
1099     */
1100    gb_assert(!error);
1101    gb_assert(!GB_have_error());
1102    uint8_t result;
1103    switch (gbd->type()) {
1104        case GB_BYTE:
1105            result = GB_read_byte(gbd);
1106            break;
1107
1108        case GB_INT:
1109            result = GB_read_int(gbd);
1110            break;
1111
1112        case GB_FLOAT:
1113            result = GB_read_float(gbd)+.5;
1114            break;
1115
1116        case GB_STRING:
1117            result = atoi(GB_read_char_pntr(gbd));
1118            break;
1119
1120        default:
1121            error  = cannot_use_fun4entry("GB_read_lossless_byte", gbd);
1122            result = 0;
1123            break;
1124    }
1125
1126    if (!error) error = GB_incur_error();
1127    return result;
1128}
1129NOT4PERL int32_t GB_read_lossless_int(GBDATA *gbd, GB_ERROR& error) {
1130    /*! Reads an int32_t previously written with GB_write_lossless_int()
1131     * @param gbd    the DB field
1132     * @param error  result parameter (has to be NULL)
1133     * @result is undefined if error != NULL; contains read value otherwise
1134     */
1135    gb_assert(!error);
1136    gb_assert(!GB_have_error());
1137    int32_t result;
1138    switch (gbd->type()) {
1139        case GB_INT:
1140            result = GB_read_int(gbd);
1141            break;
1142
1143        case GB_STRING:
1144            result = atoi(GB_read_char_pntr(gbd));
1145            break;
1146
1147        default:
1148            error  = cannot_use_fun4entry("GB_read_lossless_int", gbd);
1149            result = 0;
1150            break;
1151    }
1152
1153    if (!error) error = GB_incur_error();
1154    return result;
1155}
1156NOT4PERL float GB_read_lossless_float(GBDATA *gbd, GB_ERROR& error) {
1157    /*! Reads a float previously written with GB_write_lossless_float()
1158     * @param gbd    the DB field
1159     * @param error  result parameter (has to be NULL)
1160     * @result is undefined if error != NULL; contains read value otherwise
1161     */
1162    gb_assert(!error);
1163    gb_assert(!GB_have_error());
1164    float result;
1165    switch (gbd->type()) {
1166        case GB_FLOAT:
1167            result = GB_read_float(gbd);
1168            break;
1169
1170        case GB_STRING:
1171            result = GB_atof(GB_read_char_pntr(gbd));
1172            break;
1173
1174        default:
1175            error  = cannot_use_fun4entry("GB_read_lossless_float", gbd);
1176            result = 0;
1177            break;
1178    }
1179
1180    if (!error) error = GB_incur_error();
1181    return result;
1182}
1183
1184// ------------------------------------------------------------
1185//      array type access functions (intended for perl use)
1186
1187long GB_read_from_ints(GBDATA *gbd, long index) { // used by ../PERL_SCRIPTS/SAI/SAI.pm@read_from_ints
1188    static GBDATA    *last_gbd = 0;
1189    static long       count    = 0;
1190    static GB_CUINT4 *i        = 0;
1191
1192    if (gbd != last_gbd) {
1193        count    = GB_read_ints_count(gbd);
1194        i        = GB_read_ints_pntr(gbd);
1195        last_gbd = gbd;
1196    }
1197
1198    if (index >= 0 && index < count) {
1199        return i[index];
1200    }
1201    return -1;
1202}
1203
1204double GB_read_from_floats(GBDATA *gbd, long index) { // @@@ unused
1205    static GBDATA    *last_gbd = 0;
1206    static long       count    = 0;
1207    static GB_CFLOAT *f        = 0;
1208
1209    if (gbd != last_gbd) {
1210        count    = GB_read_floats_count(gbd);
1211        f        = GB_read_floats_pntr(gbd);
1212        last_gbd = gbd;
1213    }
1214
1215    if (index >= 0 && index < count) {
1216        return f[index];
1217    }
1218    return -1;
1219}
1220
1221// -------------------
1222//      write data
1223
1224static void gb_do_callbacks(GBDATA *gbd) {
1225    gb_assert(GB_MAIN(gbd)->get_transaction_level() < 0); // only use in NO_TRANSACTION_MODE!
1226
1227    while (gbd) {
1228        GBDATA *gbdn = GB_get_father(gbd);
1229        gb_callback_list *cbl = gbd->get_callbacks();
1230        if (cbl && cbl->call(gbd, GB_CB_CHANGED)) {
1231            gb_remove_callbacks_marked_for_deletion(gbd);
1232        }
1233        gbd = gbdn;
1234    }
1235}
1236
1237#define GB_DO_CALLBACKS(gbd) do { if (GB_MAIN(gbd)->get_transaction_level() < 0) gb_do_callbacks(gbd); } while (0)
1238
1239GB_ERROR GB_write_byte(GBDATA *gbd, int i)
1240{
1241    GB_TEST_WRITE(gbd, GB_BYTE, "GB_write_byte");
1242    GBENTRY *gbe = gbd->as_entry();
1243    if (gbe->info.i != i) {
1244        gb_save_extern_data_in_ts(gbe);
1245        gbe->info.i = i & 0xff;
1246        gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1247        GB_DO_CALLBACKS(gbe);
1248    }
1249    return 0;
1250}
1251
1252GB_ERROR GB_write_int(GBDATA *gbd, long i) {
1253#if defined(ARB_64)
1254#if defined(WARN_TODO)
1255#warning GB_write_int should be GB_ERROR GB_write_int(GBDATA *gbd,int32_t i)
1256#endif
1257#endif
1258
1259    GB_TEST_WRITE(gbd, GB_INT, "GB_write_int");
1260    if ((long)((int32_t)i) != i) {
1261        gb_assert(0);
1262        GB_warningf("Warning: 64bit incompatibility detected\nNo data written to '%s'\n", GB_get_db_path(gbd));
1263        return "GB_INT out of range (signed, 32bit)";
1264    }
1265    GBENTRY *gbe = gbd->as_entry();
1266    if (gbe->info.i != (int32_t)i) {
1267        gb_save_extern_data_in_ts(gbe);
1268        gbe->info.i = i;
1269        gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1270        GB_DO_CALLBACKS(gbe);
1271    }
1272    return 0;
1273}
1274
1275GB_ERROR GB_write_pointer(GBDATA *gbd, GBDATA *pointer) {
1276    GB_TEST_WRITE(gbd, GB_POINTER, "GB_write_pointer");
1277    GBENTRY *gbe = gbd->as_entry();
1278    if (gbe->info.ptr != pointer) {
1279        gb_save_extern_data_in_ts(gbe);
1280        gbe->info.ptr = pointer;
1281        gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1282        GB_DO_CALLBACKS(gbe);
1283    }
1284    return 0;
1285}
1286
1287GB_ERROR GB_write_float(GBDATA *gbd, float f) {
1288    gb_assert(f == f); // !nan
1289    GB_TEST_WRITE(gbd, GB_FLOAT, "GB_write_float");
1290
1291    if (GB_read_float(gbd) != f) {
1292        GBENTRY *gbe = gbd->as_entry();
1293        gb_save_extern_data_in_ts(gbe);
1294
1295        XDR xdrs;
1296        xdrmem_create(&xdrs, &gbe->info.in.data[0], SIZOFINTERN, XDR_ENCODE);
1297        xdr_float(&xdrs, &f);
1298        xdr_destroy(&xdrs);
1299
1300        gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1301        GB_DO_CALLBACKS(gbe);
1302    }
1303    return 0;
1304}
1305
1306GB_ERROR gb_write_compressed_pntr(GBENTRY *gbe, const char *s, long memsize, long stored_size) {
1307    gb_uncache(gbe);
1308    gb_save_extern_data_in_ts(gbe);
1309    gbe->flags.compressed_data = 1;
1310    gbe->insert_data((char *)s, stored_size, (size_t)memsize);
1311    gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1312
1313    return 0;
1314}
1315
1316int gb_get_compression_mask(GB_MAIN_TYPE *Main, GBQUARK key, int gb_type) {
1317    gb_Key *ks = &Main->keys[key];
1318    int     compression_mask;
1319
1320    if (ks->gb_key_disabled) {
1321        compression_mask = 0;
1322    }
1323    else {
1324        if (!ks->gb_key) gb_load_single_key_data(Main->gb_main(), key);
1325        compression_mask = gb_convert_type_2_compression_flags[gb_type] & ks->compression_mask;
1326    }
1327
1328    return compression_mask;
1329}
1330
1331GB_ERROR GB_write_pntr(GBDATA *gbd, const char *s, size_t bytes_size, size_t stored_size)
1332{
1333    // 'bytes_size' is the size of what 's' points to.
1334    // 'stored_size' is the size-information written into the DB
1335    //
1336    // e.g. for strings : stored_size = bytes_size-1, cause stored_size is string len,
1337    //                    but bytes_size includes zero byte.
1338
1339    GBENTRY      *gbe  = gbd->as_entry();
1340    GB_MAIN_TYPE *Main = GB_MAIN(gbe);
1341    GBQUARK       key  = GB_KEY_QUARK(gbe);
1342    GB_TYPES      type = gbe->type();
1343
1344    gb_assert(implicated(type == GB_STRING, stored_size == bytes_size-1)); // size constraint for strings not fulfilled!
1345
1346    gb_uncache(gbe);
1347    gb_save_extern_data_in_ts(gbe);
1348
1349    int compression_mask = gb_get_compression_mask(Main, key, type);
1350
1351    const char *d;
1352    size_t      memsize;
1353    if (compression_mask) {
1354        d = gb_compress_data(gbe, key, s, bytes_size, &memsize, compression_mask, false);
1355    }
1356    else {
1357        d = NULL;
1358    }
1359    if (d) {
1360        gbe->flags.compressed_data = 1;
1361    }
1362    else {
1363        d = s;
1364        gbe->flags.compressed_data = 0;
1365        memsize = bytes_size;
1366    }
1367
1368    gbe->insert_data(d, stored_size, memsize);
1369    gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1370    GB_DO_CALLBACKS(gbe);
1371
1372    return 0;
1373}
1374
1375GB_ERROR GB_write_string(GBDATA *gbd, const char *s) {
1376    GBENTRY *gbe = gbd->as_entry();
1377    GB_TEST_WRITE(gbe, GB_STRING, "GB_write_string");
1378    GB_TEST_NON_BUFFER(s, "GB_write_string");        // compress would destroy the other buffer
1379
1380    if (!s) s = "";
1381    size_t size = strlen(s);
1382
1383    // no zero len strings allowed
1384    if (gbe->memsize() && (size == gbe->size()))
1385    {
1386        if (!strcmp(s, GB_read_pntr(gbe)))
1387            return 0;
1388    }
1389#if defined(DEBUG) && 0
1390    // check for error (in compression)
1391    {
1392        GB_ERROR error = GB_write_pntr(gbe, s, size+1, size);
1393        if (!error) {
1394            char *check = GB_read_string(gbe);
1395
1396            gb_assert(check);
1397            gb_assert(strcmp(check, s) == 0);
1398
1399            free(check);
1400        }
1401        return error;
1402    }
1403#else
1404    return GB_write_pntr(gbe, s, size+1, size);
1405#endif // DEBUG
1406}
1407
1408GB_ERROR GB_write_link(GBDATA *gbd, const char *s)
1409{
1410    GBENTRY *gbe = gbd->as_entry();
1411    GB_TEST_WRITE(gbe, GB_STRING, "GB_write_link");
1412    GB_TEST_NON_BUFFER(s, "GB_write_link");          // compress would destroy the other buffer
1413
1414    if (!s) s = "";
1415    size_t size = strlen(s);
1416
1417    // no zero len strings allowed
1418    if (gbe->memsize()  && (size == gbe->size()))
1419    {
1420        if (!strcmp(s, GB_read_pntr(gbe)))
1421            return 0;
1422    }
1423    return GB_write_pntr(gbe, s, size+1, size);
1424}
1425
1426
1427GB_ERROR GB_write_bits(GBDATA *gbd, const char *bits, long size, const char *c_0)
1428{
1429    GBENTRY *gbe = gbd->as_entry();
1430    GB_TEST_WRITE(gbe, GB_BITS, "GB_write_bits");
1431    GB_TEST_NON_BUFFER(bits, "GB_write_bits");       // compress would destroy the other buffer
1432    gb_save_extern_data_in_ts(gbe);
1433
1434    long  memsize;
1435    char *d = gb_compress_bits(bits, size, (const unsigned char *)c_0, &memsize);
1436
1437    gbe->flags.compressed_data = 1;
1438    gbe->insert_data(d, size, memsize);
1439    gb_touch_entry(gbe, GB_NORMAL_CHANGE);
1440    GB_DO_CALLBACKS(gbe);
1441    return 0;
1442}
1443
1444GB_ERROR GB_write_bytes(GBDATA *gbd, const char *s, long size)
1445{
1446    GB_TEST_WRITE(gbd, GB_BYTES, "GB_write_bytes");
1447    return GB_write_pntr(gbd, s, size, size);
1448}
1449
1450GB_ERROR GB_write_ints(GBDATA *gbd, const GB_UINT4 *i, long size)
1451{
1452
1453    GB_TEST_WRITE(gbd, GB_INTS, "GB_write_ints");
1454    GB_TEST_NON_BUFFER((char *)i, "GB_write_ints");  // compress would destroy the other buffer
1455
1456    if (0x01020304 != htonl((GB_UINT4)0x01020304)) {
1457        long      j;
1458        char     *buf2 = GB_give_other_buffer((char *)i, size<<2);
1459        GB_UINT4 *s    = (GB_UINT4 *)i;
1460        GB_UINT4 *d    = (GB_UINT4 *)buf2;
1461
1462        for (j=size; j; j--) {
1463            *(d++) = htonl(*(s++));
1464        }
1465        i = (GB_UINT4 *)buf2;
1466    }
1467    return GB_write_pntr(gbd, (char *)i, size* 4 /* sizeof(long4) */, size);
1468}
1469
1470GB_ERROR GB_write_floats(GBDATA *gbd, const float *f, long size)
1471{
1472    long fullsize = size * sizeof(float);
1473    GB_TEST_WRITE(gbd, GB_FLOATS, "GB_write_floats");
1474    GB_TEST_NON_BUFFER((char *)f, "GB_write_floats"); // compress would destroy the other buffer
1475
1476    {
1477        XDR    xdrs;
1478        long   i;
1479        char  *buf2 = GB_give_other_buffer((char *)f, fullsize);
1480        float *s    = (float *)f;
1481
1482        xdrmem_create(&xdrs, buf2, (int)fullsize, XDR_ENCODE);
1483        for (i=size; i; i--) {
1484            xdr_float(&xdrs, s);
1485            s++;
1486        }
1487        xdr_destroy (&xdrs);
1488        f = (float*)(void*)buf2;
1489    }
1490    return GB_write_pntr(gbd, (char *)f, size*sizeof(float), size);
1491}
1492
1493GB_ERROR GB_write_autoconv_string(GBDATA *gbd, const char *val) {
1494    /*! writes data to database field using automatic conversion.
1495     *  Warning: Conversion may cause silent data-loss!
1496     *           (e.g. writing "hello" to a numeric db-field results in zero content)
1497     *
1498     *  Writing back the unmodified(!) result of GB_read_as_string will not cause data loss.
1499     *
1500     *  Consider using the GB_write_lossless_...() functions below (and their counterparts GB_read_lossless_...()).
1501     */
1502    switch (gbd->type()) {
1503        case GB_STRING: return GB_write_string(gbd, val);
1504        case GB_LINK:   return GB_write_link(gbd, val);
1505        case GB_BYTE:   return GB_write_byte(gbd, atoi(val));
1506        case GB_INT:    return GB_write_int(gbd, atoi(val));
1507        case GB_FLOAT:  {
1508            float f;
1509            GB_ERROR error = GB_safe_atof(val, &f);
1510            return error ? error : GB_write_float(gbd, f);
1511        }
1512        case GB_BITS:   return GB_write_bits(gbd, val, strlen(val), "0");
1513        default: return GBS_global_string("Error: You cannot use GB_write_autoconv_string on this type of entry (%s)", GB_read_key_pntr(gbd));
1514    }
1515}
1516
1517GB_ERROR GB_write_lossless_byte(GBDATA *gbd, uint8_t byte) {
1518    /*! Writes an uint8_t to a database field capable to store any value w/o loss.
1519     *  @return error otherwise
1520     *  The corresponding field filter is FIELD_FILTER_BYTE_WRITEABLE.
1521     */
1522    switch (gbd->type()) {
1523        case GB_BYTE:   return GB_write_byte(gbd, byte);
1524        case GB_INT:    return GB_write_int(gbd, byte);
1525        case GB_FLOAT:  return GB_write_float(gbd, byte);
1526        case GB_STRING: {
1527            char buffer[4];
1528            sprintf(buffer, "%u", unsigned(byte));
1529            return GB_write_string(gbd, buffer);
1530        }
1531
1532        default: return cannot_use_fun4entry("GB_write_lossless_byte", gbd);
1533    }
1534}
1535
1536GB_ERROR GB_write_lossless_int(GBDATA *gbd, int32_t i) {
1537    /*! Writes an int32_t to a database field capable to store any value w/o loss.
1538     *  @return error otherwise
1539     *  The corresponding field filter is FIELD_FILTER_INT_WRITEABLE.
1540     */
1541
1542    switch (gbd->type()) {
1543        case GB_INT:    return GB_write_int(gbd, i);
1544        case GB_STRING: {
1545            const int BUFSIZE = 30;
1546            char      buffer[BUFSIZE];
1547#if defined(ASSERTION_USED)
1548            int printed =
1549#endif
1550                sprintf(buffer, "%i", i);
1551            gb_assert(printed<BUFSIZE);
1552            return GB_write_string(gbd, buffer);
1553        }
1554
1555        default: return cannot_use_fun4entry("GB_write_lossless_int", gbd);
1556    }
1557}
1558
1559GB_ERROR GB_write_lossless_float(GBDATA *gbd, float f) {
1560    /*! Writes a float to a database field capable to store any value w/o loss.
1561     *  @return error otherwise
1562     *  The corresponding field filter is FIELD_FILTER_FLOAT_WRITEABLE.
1563     */
1564
1565    switch (gbd->type()) {
1566        case GB_FLOAT:  return GB_write_float(gbd, f);
1567        case GB_STRING: {
1568            const int BUFSIZE = 30;
1569            char      buffer[BUFSIZE];
1570#if defined(ASSERTION_USED)
1571            int printed =
1572#endif
1573                sprintf(buffer, "%e", f);
1574            gb_assert(printed<BUFSIZE);
1575            return GB_write_string(gbd, buffer);
1576        }
1577
1578        default: return cannot_use_fun4entry("GB_write_lossless_float", gbd);
1579    }
1580}
1581
1582// ---------------------------
1583//      security functions
1584
1585int GB_read_security_write(GBDATA *gbd) {
1586    GB_test_transaction(gbd);
1587    return GB_GET_SECURITY_WRITE(gbd);
1588}
1589int GB_read_security_read(GBDATA *gbd) {
1590    GB_test_transaction(gbd);
1591    return GB_GET_SECURITY_READ(gbd);
1592}
1593int GB_read_security_delete(GBDATA *gbd) {
1594    GB_test_transaction(gbd);
1595    return GB_GET_SECURITY_DELETE(gbd);
1596}
1597GB_ERROR GB_write_security_write(GBDATA *gbd, unsigned long level)
1598{
1599    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1600    GB_test_transaction(Main);
1601
1602    if (GB_GET_SECURITY_WRITE(gbd)>Main->security_level)
1603        return gb_security_error(gbd);
1604    if (GB_GET_SECURITY_WRITE(gbd) == level) return 0;
1605    GB_PUT_SECURITY_WRITE(gbd, level);
1606    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
1607    GB_DO_CALLBACKS(gbd);
1608    return 0;
1609}
1610GB_ERROR GB_write_security_read(GBDATA *gbd, unsigned long level) // @@@ unused
1611{
1612    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1613    GB_test_transaction(Main);
1614    if (GB_GET_SECURITY_WRITE(gbd)>Main->security_level)
1615        return gb_security_error(gbd);
1616    if (GB_GET_SECURITY_READ(gbd) == level) return 0;
1617    GB_PUT_SECURITY_READ(gbd, level);
1618    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
1619    GB_DO_CALLBACKS(gbd);
1620    return 0;
1621}
1622GB_ERROR GB_write_security_delete(GBDATA *gbd, unsigned long level)
1623{
1624    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1625    GB_test_transaction(Main);
1626    if (GB_GET_SECURITY_WRITE(gbd)>Main->security_level)
1627        return gb_security_error(gbd);
1628    if (GB_GET_SECURITY_DELETE(gbd) == level) return 0;
1629    GB_PUT_SECURITY_DELETE(gbd, level);
1630    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
1631    GB_DO_CALLBACKS(gbd);
1632    return 0;
1633}
1634GB_ERROR GB_write_security_levels(GBDATA *gbd, unsigned long readlevel, unsigned long writelevel, unsigned long deletelevel)
1635{
1636    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1637    GB_test_transaction(Main);
1638    if (GB_GET_SECURITY_WRITE(gbd)>Main->security_level)
1639        return gb_security_error(gbd);
1640    GB_PUT_SECURITY_WRITE(gbd, writelevel);
1641    GB_PUT_SECURITY_READ(gbd, readlevel);
1642    GB_PUT_SECURITY_DELETE(gbd, deletelevel);
1643    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
1644    GB_DO_CALLBACKS(gbd);
1645    return 0;
1646}
1647
1648void GB_change_my_security(GBDATA *gbd, int level) {
1649    GB_MAIN(gbd)->security_level = level<0 ? 0 : (level>7 ? 7 : level);
1650}
1651
1652// For internal use only
1653void GB_push_my_security(GBDATA *gbd)
1654{
1655    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1656    Main->pushed_security_level++;
1657    if (Main->pushed_security_level <= 1) {
1658        Main->old_security_level = Main->security_level;
1659        Main->security_level = 7;
1660    }
1661}
1662
1663void GB_pop_my_security(GBDATA *gbd) {
1664    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
1665    Main->pushed_security_level--;
1666    if (Main->pushed_security_level <= 0) {
1667        Main->security_level = Main->old_security_level;
1668    }
1669}
1670
1671
1672// ------------------------
1673//      Key information
1674
1675GB_TYPES GB_read_type(GBDATA *gbd) {
1676    GB_test_transaction(gbd);
1677    return gbd->type();
1678}
1679
1680bool GB_is_container(GBDATA *gbd) {
1681    return gbd && gbd->is_container();
1682}
1683
1684char *GB_read_key(GBDATA *gbd) {
1685    return ARB_strdup(GB_read_key_pntr(gbd));
1686}
1687
1688GB_CSTR GB_read_key_pntr(GBDATA *gbd) {
1689    GB_CSTR k;
1690    GB_test_transaction(gbd);
1691    k         = GB_KEY(gbd);
1692    if (!k) k = GBS_global_string("<invalid key (quark=%i)>", GB_KEY_QUARK(gbd));
1693    return k;
1694}
1695
1696GB_CSTR gb_read_key_pntr(GBDATA *gbd) {
1697    return GB_KEY(gbd);
1698}
1699
1700GBQUARK gb_find_or_create_quark(GB_MAIN_TYPE *Main, const char *key) {
1701    //! @return existing or newly created quark for 'key'
1702    GBQUARK quark = key2quark(Main, key);
1703    if (!quark) {
1704        if (!key[0]) GBK_terminate("Attempt to create quark from empty key");
1705        quark = gb_create_key(Main, key, true);
1706    }
1707    return quark;
1708}
1709
1710GBQUARK gb_find_or_create_NULL_quark(GB_MAIN_TYPE *Main, const char *key) {
1711    // similar to gb_find_or_create_quark,
1712    // but if 'key' is NULL, quark 0 will be returned.
1713    //
1714    // Use this function with care.
1715    //
1716    // Known good use:
1717    // - create main entry and its dummy father via gb_make_container()
1718
1719    return key ? gb_find_or_create_quark(Main, key) : 0;
1720}
1721
1722GBQUARK GB_find_existing_quark(GBDATA *gbd, const char *key) {
1723    //! @return existing quark for 'key' (-1 if key == NULL, 0 if key is unknown)
1724    return key2quark(GB_MAIN(gbd), key);
1725}
1726
1727GBQUARK GB_find_or_create_quark(GBDATA *gbd, const char *key) {
1728    //! @return existing or newly created quark for 'key'
1729    return gb_find_or_create_quark(GB_MAIN(gbd), key);
1730}
1731
1732
1733// ---------------------------------------------
1734
1735GBQUARK GB_get_quark(GBDATA *gbd) {
1736    return GB_KEY_QUARK(gbd);
1737}
1738
1739bool GB_has_key(GBDATA *gbd, const char *key) {
1740    GBQUARK quark = GB_find_existing_quark(gbd, key); 
1741    return quark && (quark == GB_get_quark(gbd));
1742}
1743
1744// ---------------------------------------------
1745
1746long GB_read_clock(GBDATA *gbd) {
1747    if (GB_ARRAY_FLAGS(gbd).changed) return GB_MAIN(gbd)->clock;
1748    return gbd->update_date();
1749}
1750
1751// ---------------------------------------------
1752//      Get and check the database hierarchy
1753
1754GBDATA *GB_get_father(GBDATA *gbd) {
1755    // Get the father of an entry
1756    GB_test_transaction(gbd);
1757    return gbd->get_father();
1758}
1759
1760GBDATA *GB_get_grandfather(GBDATA *gbd) {
1761    GB_test_transaction(gbd);
1762
1763    GBDATA *gb_grandpa = GB_FATHER(gbd);
1764    if (gb_grandpa) {
1765        gb_grandpa = GB_FATHER(gb_grandpa);
1766        if (gb_grandpa && !GB_FATHER(gb_grandpa)) gb_grandpa = NULL; // never return dummy_father of root container
1767    }
1768    return gb_grandpa;
1769}
1770
1771// Get the root entry (gb_main)
1772GBDATA *GB_get_root(GBDATA *gbd) { return GB_MAIN(gbd)->gb_main(); }
1773GBCONTAINER *gb_get_root(GBENTRY *gbe) { return GB_MAIN(gbe)->root_container; }
1774GBCONTAINER *gb_get_root(GBCONTAINER *gbc) { return GB_MAIN(gbc)->root_container; }
1775
1776bool GB_check_father(GBDATA *gbd, GBDATA *gb_maybefather) {
1777    // Test whether an entry is a subentry of another
1778    GBDATA *gbfather;
1779    for (gbfather = GB_get_father(gbd);
1780         gbfather;
1781         gbfather = GB_get_father(gbfather))
1782    {
1783        if (gbfather == gb_maybefather) return true;
1784    }
1785    return false;
1786}
1787
1788// --------------------------
1789//      create and rename
1790
1791GBENTRY *gb_create(GBCONTAINER *father, const char *key, GB_TYPES type) {
1792    GBENTRY *gbe = gb_make_entry(father, key, -1, 0, type);
1793    gb_touch_header(GB_FATHER(gbe));
1794    gb_touch_entry(gbe, GB_CREATED);
1795
1796    gb_assert(GB_ARRAY_FLAGS(gbe).changed < GB_DELETED); // happens sometimes -> needs debugging
1797
1798    return gbe;
1799}
1800
1801GBCONTAINER *gb_create_container(GBCONTAINER *father, const char *key) {
1802    // Create a container, do not check anything
1803    GBCONTAINER *gbc = gb_make_container(father, key, -1, 0);
1804    gb_touch_header(GB_FATHER(gbc));
1805    gb_touch_entry(gbc, GB_CREATED);
1806    return gbc;
1807}
1808
1809GBDATA *GB_create(GBDATA *father, const char *key, GB_TYPES type) {
1810    /*! Create a DB entry
1811     *
1812     * @param father container to create DB field in
1813     * @param key name of field
1814     * @param type field type
1815     *
1816     * @return
1817     * - created DB entry
1818     * - NULL on failure (error is exported then)
1819     *
1820     * @see GB_create_container()
1821     */
1822
1823    if (GB_check_key(key)) {
1824        GB_print_error();
1825        return NULL;
1826    }
1827
1828    if (type == GB_DB) {
1829        gb_assert(type != GB_DB); // you like to use GB_create_container!
1830        GB_export_error("GB_create error: can't create containers");
1831        return NULL;
1832    }
1833
1834    if (!father) {
1835        GB_internal_errorf("GB_create error in GB_create:\nno father (key = '%s')", key);
1836        return NULL;
1837    }
1838    GB_test_transaction(father);
1839    if (father->is_entry()) {
1840        GB_export_errorf("GB_create: father (%s) is not of GB_DB type (%i) (creating '%s')",
1841                         GB_read_key_pntr(father), father->type(), key);
1842        return NULL;
1843    }
1844
1845    if (type == GB_POINTER) {
1846        if (!GB_in_temporary_branch(father)) {
1847            GB_export_error("GB_create: pointers only allowed in temporary branches");
1848            return NULL;
1849        }
1850    }
1851
1852    return gb_create(father->expect_container(), key, type);
1853}
1854
1855GBDATA *GB_create_container(GBDATA *father, const char *key) {
1856    /*! Create a new DB container
1857     *
1858     * @param father parent container
1859     * @param key name of created container
1860     *
1861     * @return
1862     * - created container
1863     * - NULL on failure (error is exported then)
1864     *
1865     * @see GB_create()
1866     */
1867
1868    if (GB_check_key(key)) {
1869        GB_print_error();
1870        return NULL;
1871    }
1872
1873    if ((*key == '\0')) {
1874        GB_export_error("GB_create error: empty key");
1875        return NULL;
1876    }
1877    if (!father) {
1878        GB_internal_errorf("GB_create error in GB_create:\nno father (key = '%s')", key);
1879        return NULL;
1880    }
1881
1882    GB_test_transaction(father);
1883    return gb_create_container(father->expect_container(), key);
1884}
1885
1886// ----------------------
1887//      recompression
1888
1889#if defined(WARN_TODO)
1890#warning rename gb_set_compression into gb_recompress (misleading name)
1891#endif
1892
1893static GB_ERROR gb_set_compression(GBDATA *source) {
1894    GB_ERROR error = 0;
1895    GB_test_transaction(source);
1896
1897    switch (source->type()) {
1898        case GB_STRING: {
1899            char *str = GB_read_string(source);
1900            GB_write_string(source, "");
1901            GB_write_string(source, str);
1902            free(str);
1903            break;
1904        }
1905        case GB_BITS:
1906        case GB_BYTES:
1907        case GB_INTS:
1908        case GB_FLOATS:
1909            break;
1910        case GB_DB:
1911            for (GBDATA *gb_p = GB_child(source); gb_p && !error; gb_p = GB_nextChild(gb_p)) {
1912                error = gb_set_compression(gb_p);
1913            }
1914            break;
1915        default:
1916            break;
1917    }
1918    return error;
1919}
1920
1921bool GB_allow_compression(GBDATA *gb_main, bool allow_compression) {
1922    GB_MAIN_TYPE *Main      = GB_MAIN(gb_main);
1923    int           prev_mask = Main->compression_mask;
1924    Main->compression_mask  = allow_compression ? -1 : 0;
1925
1926    return prev_mask == 0 ? false : true;
1927}
1928
1929
1930GB_ERROR GB_delete(GBDATA*& source) {
1931    GBDATA *gb_main;
1932
1933    GB_test_transaction(source);
1934    if (GB_GET_SECURITY_DELETE(source)>GB_MAIN(source)->security_level) {
1935        return GBS_global_string("Security error: deleting entry '%s' not permitted", GB_read_key_pntr(source));
1936    }
1937
1938    gb_main = GB_get_root(source);
1939
1940    if (source->flags.compressed_data) {
1941        bool was_allowed = GB_allow_compression(gb_main, false);
1942        gb_set_compression(source); // write data w/o compression (otherwise GB_read_old_value... won't work)
1943        GB_allow_compression(gb_main, was_allowed);
1944    }
1945
1946    {
1947        GB_MAIN_TYPE *Main = GB_MAIN(source);
1948        if (Main->get_transaction_level() < 0) { // no transaction mode
1949            gb_delete_entry(source);
1950            Main->call_pending_callbacks();
1951        }
1952        else {
1953            gb_touch_entry(source, GB_DELETED);
1954        }
1955    }
1956    return 0;
1957}
1958
1959GB_ERROR gb_delete_force(GBDATA *source)    // delete always
1960{
1961    gb_touch_entry(source, GB_DELETED);
1962    return 0;
1963}
1964
1965
1966// ------------------
1967//      Copy data
1968
1969#if defined(WARN_TODO)
1970#warning replace GB_copy with GB_copy_with_protection after release
1971#endif
1972
1973GB_ERROR GB_copy(GBDATA *dest, GBDATA *source) {
1974    return GB_copy_with_protection(dest, source, false);
1975}
1976
1977GB_ERROR GB_copy_with_protection(GBDATA *dest, GBDATA *source, bool copy_all_protections) {
1978    GB_ERROR error = 0;
1979    GB_test_transaction(source);
1980
1981    GB_TYPES type = source->type();
1982    if (dest->type() != type) {
1983        return GB_export_errorf("incompatible types in GB_copy (source %s:%u != %s:%u",
1984                                GB_read_key_pntr(source), type, GB_read_key_pntr(dest), dest->type());
1985    }
1986
1987    switch (type) {
1988        case GB_INT:
1989            error = GB_write_int(dest, GB_read_int(source));
1990            break;
1991        case GB_FLOAT:
1992            error = GB_write_float(dest, GB_read_float(source));
1993            break;
1994        case GB_BYTE:
1995            error = GB_write_byte(dest, GB_read_byte(source));
1996            break;
1997        case GB_STRING:     // No local compression
1998            error = GB_write_string(dest, GB_read_char_pntr(source));
1999            break;
2000        case GB_LINK:       // No local compression
2001            error = GB_write_link(dest, GB_read_link_pntr(source));
2002            break;
2003        case GB_BITS:       // only local compressions for the following types
2004        case GB_BYTES:
2005        case GB_INTS:
2006        case GB_FLOATS: {
2007            GBENTRY *source_entry = source->as_entry();
2008            GBENTRY *dest_entry   = dest->as_entry();
2009
2010            gb_save_extern_data_in_ts(dest_entry);
2011            dest_entry->insert_data(source_entry->data(), source_entry->size(), source_entry->memsize());
2012
2013            dest->flags.compressed_data = source->flags.compressed_data;
2014            break;
2015        }
2016        case GB_DB: {
2017            if (!dest->is_container()) {
2018                GB_ERROR err = GB_export_errorf("GB_COPY Type conflict %s:%i != %s:%i",
2019                                                GB_read_key_pntr(dest), dest->type(), GB_read_key_pntr(source), GB_DB);
2020                GB_internal_error(err);
2021                return err;
2022            }
2023
2024            GBCONTAINER *destc   = dest->as_container();
2025            GBCONTAINER *sourcec = source->as_container();
2026
2027            if (sourcec->flags2.folded_container) gb_unfold(sourcec, -1, -1);
2028            if (destc->flags2.folded_container)   gb_unfold(destc, 0, -1);
2029
2030            for (GBDATA *gb_p = GB_child(sourcec); gb_p; gb_p = GB_nextChild(gb_p)) {
2031                const char *key = GB_read_key_pntr(gb_p);
2032                GBDATA     *gb_d;
2033
2034                if (gb_p->is_container()) {
2035                    gb_d = GB_create_container(destc, key);
2036                    gb_create_header_array(gb_d->as_container(), gb_p->as_container()->d.size);
2037                }
2038                else {
2039                    gb_d = GB_create(destc, key, gb_p->type());
2040                }
2041
2042                if (!gb_d) error = GB_await_error();
2043                else error       = GB_copy_with_protection(gb_d, gb_p, copy_all_protections);
2044
2045                if (error) break;
2046            }
2047
2048            destc->flags3 = sourcec->flags3;
2049            break;
2050        }
2051        default:
2052            error = GB_export_error("GB_copy-error: unhandled type");
2053    }
2054    if (error) return error;
2055
2056    gb_touch_entry(dest, GB_NORMAL_CHANGE);
2057
2058    dest->flags.security_read = source->flags.security_read;
2059    if (copy_all_protections) {
2060        dest->flags.security_write  = source->flags.security_write;
2061        dest->flags.security_delete = source->flags.security_delete;
2062    }
2063
2064    return 0;
2065}
2066
2067
2068static char *gb_stpcpy(char *dest, const char *source)
2069{
2070    while ((*dest++=*source++)) ;
2071    return dest-1; // return pointer to last copied character (which is \0)
2072}
2073
2074char* GB_get_subfields(GBDATA *gbd) {
2075    /*! Get all subfield names
2076     *
2077     * @return all subfields of 'gbd' as ';'-separated heap-copy
2078     * (first and last char of result is a ';')
2079     */
2080    GB_test_transaction(gbd);
2081
2082    char *result = 0;
2083    if (gbd->is_container()) {
2084        GBCONTAINER *gbc           = gbd->as_container();
2085        int          result_length = 0;
2086
2087        if (gbc->flags2.folded_container) {
2088            gb_unfold(gbc, -1, -1);
2089        }
2090
2091        for (GBDATA *gbp = GB_child(gbd); gbp; gbp = GB_nextChild(gbp)) {
2092            const char *key = GB_read_key_pntr(gbp);
2093            int keylen = strlen(key);
2094
2095            if (result) {
2096                char *neu_result = ARB_alloc<char>(result_length+keylen+1+1);
2097
2098                if (neu_result) {
2099                    char *p = gb_stpcpy(neu_result, result);
2100                    p = gb_stpcpy(p, key);
2101                    *p++ = ';';
2102                    p[0] = 0;
2103
2104                    freeset(result, neu_result);
2105                    result_length += keylen+1;
2106                }
2107                else {
2108                    gb_assert(0);
2109                }
2110            }
2111            else {
2112                ARB_alloc(result, 1+keylen+1+1);
2113                result[0] = ';';
2114                strcpy(result+1, key);
2115                result[keylen+1] = ';';
2116                result[keylen+2] = 0;
2117                result_length = keylen+2;
2118            }
2119        }
2120    }
2121    else {
2122        result = ARB_strdup(";");
2123    }
2124
2125    return result;
2126}
2127
2128// --------------------------
2129//      temporary entries
2130
2131GB_ERROR GB_set_temporary(GBDATA *gbd) { // goes to header: __ATTR__USERESULT
2132    /*! if the temporary flag is set, then that entry (including all subentries) will not be saved
2133     * @see GB_clear_temporary() and GB_is_temporary()
2134     */
2135
2136    GB_ERROR error = NULL;
2137    GB_test_transaction(gbd);
2138
2139    if (GB_GET_SECURITY_DELETE(gbd)>GB_MAIN(gbd)->security_level) {
2140        error = GBS_global_string("Security error in GB_set_temporary: %s", GB_read_key_pntr(gbd));
2141    }
2142    else {
2143        gbd->flags.temporary = 1;
2144        gb_touch_entry(gbd, GB_NORMAL_CHANGE);
2145    }
2146    RETURN_ERROR(error);
2147}
2148
2149GB_ERROR GB_clear_temporary(GBDATA *gbd) { // @@@ used in ptpan branch - do not remove
2150    //! undo effect of GB_set_temporary()
2151
2152    GB_test_transaction(gbd);
2153    gbd->flags.temporary = 0;
2154    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
2155    return 0;
2156}
2157
2158bool GB_is_temporary(GBDATA *gbd) {
2159    //! @see GB_set_temporary() and GB_in_temporary_branch()
2160    GB_test_transaction(gbd);
2161    return (long)gbd->flags.temporary;
2162}
2163
2164bool GB_in_temporary_branch(GBDATA *gbd) {
2165    /*! @return true, if 'gbd' is member of a temporary subtree,
2166     * i.e. if GB_is_temporary(itself or any parent)
2167     */
2168
2169    if (GB_is_temporary(gbd)) return true;
2170
2171    GBDATA *gb_parent = GB_get_father(gbd);
2172    if (!gb_parent) return false;
2173
2174    return GB_in_temporary_branch(gb_parent);
2175}
2176
2177// ---------------------
2178//      transactions
2179
2180GB_ERROR GB_MAIN_TYPE::initial_client_transaction() {
2181    // the first client transaction ever
2182    transaction_level = 1;
2183    GB_ERROR error    = gbcmc_init_transaction(root_container);
2184    if (!error) ++clock;
2185    return error;
2186}
2187
2188inline GB_ERROR GB_MAIN_TYPE::start_transaction() {
2189    gb_assert(transaction_level == 0);
2190
2191    transaction_level   = 1;
2192    aborted_transaction = 0;
2193
2194    GB_ERROR error = NULL;
2195    if (is_client()) {
2196        error = gbcmc_begin_transaction(gb_main());
2197        if (!error) {
2198            error = gb_commit_transaction_local_rek(gb_main_ref(), 0, 0); // init structures
2199            gb_untouch_children_and_me(root_container);
2200        }
2201    }
2202
2203    if (!error) {
2204        /* do all callbacks
2205         * cb that change the db are no problem, because it's the beginning of a ta
2206         */
2207        call_pending_callbacks();
2208        ++clock;
2209    }
2210    return error;
2211}
2212
2213inline GB_ERROR GB_MAIN_TYPE::begin_transaction() {
2214    if (transaction_level>0) return GBS_global_string("attempt to start a NEW transaction (at transaction level %i)", transaction_level);
2215    if (transaction_level == 0) return start_transaction();
2216    return NULL; // NO_TRANSACTION_MODE
2217}
2218
2219inline GB_ERROR GB_MAIN_TYPE::abort_transaction() {
2220    if (transaction_level<=0) {
2221        if (transaction_level<0) return "GB_abort_transaction: Attempt to abort transaction in no-transaction-mode";
2222        return "GB_abort_transaction: No transaction running";
2223    }
2224    if (transaction_level>1) {
2225        aborted_transaction = 1;
2226        return pop_transaction();
2227    }
2228
2229    gb_abort_transaction_local_rek(gb_main_ref());
2230    if (is_client()) {
2231        GB_ERROR error = gbcmc_abort_transaction(gb_main());
2232        if (error) return error;
2233    }
2234    clock--;
2235    call_pending_callbacks();
2236    transaction_level = 0;
2237    gb_untouch_children_and_me(root_container);
2238    return 0;
2239}
2240
2241inline GB_ERROR GB_MAIN_TYPE::commit_transaction() {
2242    GB_ERROR      error = 0;
2243    GB_CHANGE     flag;
2244
2245    if (!transaction_level) {
2246        return "commit_transaction: No transaction running";
2247    }
2248    if (transaction_level>1) {
2249        return GBS_global_string("attempt to commit at transaction level %i", transaction_level);
2250    }
2251    if (aborted_transaction) {
2252        aborted_transaction = 0;
2253        return abort_transaction();
2254    }
2255    if (is_server()) {
2256        char *error1 = gb_set_undo_sync(gb_main());
2257        while (1) {
2258            flag = (GB_CHANGE)GB_ARRAY_FLAGS(gb_main()).changed;
2259            if (!flag) break;           // nothing to do
2260            error = gb_commit_transaction_local_rek(gb_main_ref(), 0, 0);
2261            gb_untouch_children_and_me(root_container);
2262            if (error) break;
2263            call_pending_callbacks();
2264        }
2265        gb_disable_undo(gb_main());
2266        if (error1) {
2267            transaction_level = 0;
2268            gb_assert(error); // maybe return error1?
2269            return error; // @@@ huh? why not return error1
2270        }
2271    }
2272    else {
2273        gb_disable_undo(gb_main());
2274        while (1) {
2275            flag = (GB_CHANGE)GB_ARRAY_FLAGS(gb_main()).changed;
2276            if (!flag) break;           // nothing to do
2277
2278            error = gbcmc_begin_sendupdate(gb_main());                    if (error) break;
2279            error = gb_commit_transaction_local_rek(gb_main_ref(), 1, 0); if (error) break;
2280            error = gbcmc_end_sendupdate(gb_main());                      if (error) break;
2281
2282            gb_untouch_children_and_me(root_container);
2283            call_pending_callbacks();
2284        }
2285        if (!error) error = gbcmc_commit_transaction(gb_main());
2286
2287    }
2288    transaction_level = 0;
2289    return error;
2290}
2291
2292inline GB_ERROR GB_MAIN_TYPE::push_transaction() {
2293    if (transaction_level == 0) return start_transaction();
2294    if (transaction_level>0) ++transaction_level;
2295    // transaction<0 is NO_TRANSACTION_MODE
2296    return NULL;
2297}
2298
2299inline GB_ERROR GB_MAIN_TYPE::pop_transaction() {
2300    if (transaction_level==0) return "attempt to pop nested transaction while none running";
2301    if (transaction_level<0)  return NULL;  // NO_TRANSACTION_MODE
2302    if (transaction_level==1) return commit_transaction();
2303    transaction_level--;
2304    return NULL;
2305}
2306
2307inline GB_ERROR GB_MAIN_TYPE::no_transaction() {
2308    if (is_client()) return "Tried to disable transactions in a client";
2309    transaction_level = -1;
2310    return NULL;
2311}
2312
2313GB_ERROR GB_MAIN_TYPE::send_update_to_server(GBDATA *gbd) {
2314    GB_ERROR error = NULL;
2315
2316    if (!transaction_level) error = "send_update_to_server: no transaction running";
2317    else if (is_server()) error   = "send_update_to_server: only possible from clients (not from server itself)";
2318    else {
2319        const gb_triggered_callback *chg_cbl_old = changeCBs.pending.get_tail();
2320        const gb_triggered_callback *del_cbl_old = deleteCBs.pending.get_tail();
2321
2322        error             = gbcmc_begin_sendupdate(gb_main());
2323        if (!error) error = gb_commit_transaction_local_rek(gbd, 2, 0);
2324        if (!error) error = gbcmc_end_sendupdate(gb_main());
2325
2326        if (!error &&
2327            (chg_cbl_old != changeCBs.pending.get_tail() ||
2328             del_cbl_old != deleteCBs.pending.get_tail()))
2329        {
2330            error = "send_update_to_server triggered a callback (this is not allowed)";
2331        }
2332    }
2333    return error;
2334}
2335
2336// --------------------------------------
2337//      client transaction interface
2338
2339GB_ERROR GB_push_transaction(GBDATA *gbd) {
2340    /*! start a transaction if no transaction is running.
2341     * (otherwise only trace nested transactions)
2342     *
2343     * recommended transaction usage:
2344     *
2345     * \code
2346     * GB_ERROR myFunc() {
2347     *     GB_ERROR error = GB_push_transaction(gbd);
2348     *     if (!error) {
2349     *         error = ...;
2350     *     }
2351     *     return GB_end_transaction(gbd, error);
2352     * }
2353     *
2354     * void myFunc() {
2355     *     GB_ERROR error = GB_push_transaction(gbd);
2356     *     if (!error) {
2357     *         error = ...;
2358     *     }
2359     *     GB_end_transaction_show_error(gbd, error, aw_message);
2360     * }
2361     * \endcode
2362     *
2363     * @see GB_pop_transaction(), GB_end_transaction(), GB_begin_transaction()
2364     */
2365
2366    return GB_MAIN(gbd)->push_transaction();
2367}
2368
2369GB_ERROR GB_pop_transaction(GBDATA *gbd) {
2370    //! commit a transaction started with GB_push_transaction()
2371    return GB_MAIN(gbd)->pop_transaction();
2372}
2373GB_ERROR GB_begin_transaction(GBDATA *gbd) {
2374    /*! like GB_push_transaction(),
2375     * but fails if there is already an transaction running.
2376     * @see GB_commit_transaction() and GB_abort_transaction()
2377     */
2378    return GB_MAIN(gbd)->begin_transaction();
2379}
2380GB_ERROR GB_no_transaction(GBDATA *gbd) { // goes to header: __ATTR__USERESULT
2381    return GB_MAIN(gbd)->no_transaction();
2382}
2383
2384GB_ERROR GB_abort_transaction(GBDATA *gbd) {
2385    /*! abort a running transaction,
2386     * i.e. forget all changes made to DB inside the current transaction.
2387     *
2388     * May be called instead of GB_pop_transaction() or GB_commit_transaction()
2389     *
2390     * If a nested transactions got aborted,
2391     * committing a surrounding transaction will silently abort it as well.
2392     */
2393    return GB_MAIN(gbd)->abort_transaction();
2394}
2395
2396GB_ERROR GB_commit_transaction(GBDATA *gbd) {
2397    /*! commit a transaction started with GB_begin_transaction()
2398     *
2399     * commit changes made to DB.
2400     *
2401     * in case of nested transactions, this is equal to GB_pop_transaction()
2402     */
2403    return GB_MAIN(gbd)->commit_transaction();
2404}
2405
2406GB_ERROR GB_end_transaction(GBDATA *gbd, GB_ERROR error) {
2407    /*! abort or commit transaction
2408     *
2409     * @ param error
2410     * - if NULL commit transaction
2411     * - else abort transaction
2412     *
2413     * always commits in no-transaction-mode
2414     *
2415     * @return error or transaction error
2416     * @see GB_push_transaction() for example
2417     */
2418
2419    if (GB_get_transaction_level(gbd)<0) {
2420        ASSERT_RESULT(GB_ERROR, NULL, GB_pop_transaction(gbd));
2421    }
2422    else {
2423        if (error) GB_abort_transaction(gbd);
2424        else error = GB_pop_transaction(gbd);
2425    }
2426    return error;
2427}
2428
2429void GB_end_transaction_show_error(GBDATA *gbd, GB_ERROR error, void (*error_handler)(GB_ERROR)) {
2430    //! like GB_end_transaction(), but show error using 'error_handler'
2431    error = GB_end_transaction(gbd, error);
2432    if (error) error_handler(error);
2433}
2434
2435int GB_get_transaction_level(GBDATA *gbd) {
2436    /*! @return transaction level
2437     * <0 -> in no-transaction-mode (abort is impossible)
2438     *  0 -> not in transaction
2439     *  1 -> one single transaction
2440     *  2, ... -> nested transactions
2441     */
2442    return GB_MAIN(gbd)->get_transaction_level();
2443}
2444
2445GB_ERROR GB_release(GBDATA *gbd) {
2446    /*! free cached data in client.
2447     *
2448     * Warning: pointers into the freed region(s) will get invalid!
2449     */
2450    GBCONTAINER  *gbc;
2451    GBDATA       *gb;
2452    int           index;
2453    GB_MAIN_TYPE *Main = GB_MAIN(gbd);
2454
2455    GB_test_transaction(gbd);
2456    if (Main->is_server()) return 0;
2457    if (GB_ARRAY_FLAGS(gbd).changed && !gbd->flags2.update_in_server) {
2458        GB_ERROR error = Main->send_update_to_server(gbd);
2459        if (error) return error;
2460    }
2461    if (gbd->type() != GB_DB) {
2462        GB_ERROR error = GB_export_errorf("You cannot release non container (%s)",
2463                                          GB_read_key_pntr(gbd));
2464        GB_internal_error(error);
2465        return error;
2466    }
2467    if (gbd->flags2.folded_container) return 0;
2468    gbc = (GBCONTAINER *)gbd;
2469
2470    for (index = 0; index < gbc->d.nheader; index++) {
2471        if ((gb = GBCONTAINER_ELEM(gbc, index))) {
2472            gb_delete_entry(gb);
2473        }
2474    }
2475
2476    gbc->flags2.folded_container = 1;
2477    Main->call_pending_callbacks();
2478    return 0;
2479}
2480
2481int GB_nsons(GBDATA *gbd) {
2482    /*! return number of child entries
2483     *
2484     * @@@ does this work in clients ?
2485     */
2486
2487    return gbd->is_container()
2488        ? gbd->as_container()->d.size
2489        : 0;
2490}
2491
2492void GB_disable_quicksave(GBDATA *gbd, const char *reason) {
2493    /*! Disable quicksaving database
2494     * @param gbd any DB node
2495     * @param reason why quicksaving is not allowed
2496     */
2497    freedup(GB_MAIN(gbd)->qs.quick_save_disabled, reason);
2498}
2499
2500GB_ERROR GB_resort_data_base(GBDATA *gb_main, GBDATA **new_order_list, long listsize) {
2501    {
2502        long client_count = GB_read_clients(gb_main);
2503        if (client_count<0) {
2504            return "Sorry: this program is not the arbdb server, you cannot resort your data";
2505        }
2506        if (client_count>0) {
2507            // resort will do a big amount of client update callbacks => disallow clients here
2508            bool called_from_macro = GB_inside_remote_action(gb_main);
2509            if (!called_from_macro) { // accept macro clients
2510                return GBS_global_string("There are %li clients (editors, tree programs) connected to this server.\n"
2511                                         "You need to close these clients before you can run this operation.",
2512                                         client_count);
2513            }
2514        }
2515    }
2516
2517    if (listsize <= 0) return 0;
2518
2519    GBCONTAINER *father = GB_FATHER(new_order_list[0]);
2520    GB_disable_quicksave(gb_main, "some entries in the database got a new order");
2521
2522    gb_header_list *hl = GB_DATA_LIST_HEADER(father->d);
2523    for (long new_index = 0; new_index< listsize; new_index++) {
2524        long old_index = new_order_list[new_index]->index;
2525
2526        if (old_index < new_index) {
2527            GB_warningf("Warning at resort database: entry exists twice: %li and %li",
2528                        old_index, new_index);
2529        }
2530        else {
2531            GBDATA *ogb = GB_HEADER_LIST_GBD(hl[old_index]);
2532            GBDATA *ngb = GB_HEADER_LIST_GBD(hl[new_index]);
2533
2534            gb_header_list h = hl[new_index];
2535            hl[new_index] = hl[old_index];
2536            hl[old_index] = h;              // Warning: Relative Pointers are incorrect !!!
2537
2538            SET_GB_HEADER_LIST_GBD(hl[old_index], ngb);
2539            SET_GB_HEADER_LIST_GBD(hl[new_index], ogb);
2540
2541            if (ngb) ngb->index = old_index;
2542            if (ogb) ogb->index = new_index;
2543        }
2544    }
2545
2546    gb_touch_entry(father, GB_NORMAL_CHANGE);
2547    return 0;
2548}
2549
2550GB_ERROR gb_resort_system_folder_to_top(GBCONTAINER *gb_main) {
2551    if (GB_read_clients(gb_main)<0) {
2552        return 0; // we are not server
2553    }
2554
2555    GBDATA *gb_system = GB_entry(gb_main, GB_SYSTEM_FOLDER);
2556    if (!gb_system) {
2557        return GB_export_error("System databaseentry does not exist");
2558    }
2559
2560    GBDATA *gb_first = GB_child(gb_main);
2561    if (gb_first == gb_system) {
2562        return 0;
2563    }
2564
2565    int      len            = GB_number_of_subentries(gb_main);
2566    GBDATA **new_order_list = ARB_calloc<GBDATA*>(len);
2567
2568    new_order_list[0] = gb_system;
2569    for (int i=1; i<len; i++) {
2570        new_order_list[i] = gb_first;
2571        do gb_first = GB_nextChild(gb_first); while (gb_first == gb_system);
2572    }
2573
2574    GB_ERROR error = GB_resort_data_base(gb_main, new_order_list, len);
2575    free(new_order_list);
2576
2577    return error;
2578}
2579
2580// ------------------------------
2581//      private(?) user flags
2582
2583STATIC_ASSERT_ANNOTATED(((GB_USERFLAG_ANY+1)&GB_USERFLAG_ANY) == 0, "not all bits set in GB_USERFLAG_ANY");
2584
2585#if defined(ASSERTION_USED)
2586inline bool legal_user_bitmask(unsigned char bitmask) {
2587    return bitmask>0 && bitmask<=GB_USERFLAG_ANY;
2588}
2589#endif
2590
2591inline gb_flag_types2& get_user_flags(GBDATA *gbd) {
2592    return gbd->expect_container()->flags2;
2593}
2594
2595bool GB_user_flag(GBDATA *gbd, unsigned char user_bit) {
2596    gb_assert(legal_user_bitmask(user_bit));
2597    return get_user_flags(gbd).user_bits & user_bit;
2598}
2599
2600void GB_raise_user_flag(GBDATA *gbd, unsigned char user_bit) {
2601    gb_assert(legal_user_bitmask(user_bit));
2602    gb_flag_types2& flags  = get_user_flags(gbd);
2603    flags.user_bits       |= user_bit;
2604}
2605void GB_clear_user_flag(GBDATA *gbd, unsigned char user_bit) {
2606    gb_assert(legal_user_bitmask(user_bit));
2607    gb_flag_types2& flags  = get_user_flags(gbd);
2608    flags.user_bits       &= (user_bit^GB_USERFLAG_ANY);
2609}
2610void GB_write_user_flag(GBDATA *gbd, unsigned char user_bit, bool state) {
2611    (state ? GB_raise_user_flag : GB_clear_user_flag)(gbd, user_bit);
2612}
2613
2614
2615// ------------------------
2616//      mark DB entries
2617
2618void GB_write_flag(GBDATA *gbd, long flag) {
2619    GBCONTAINER  *gbc  = gbd->expect_container();
2620    GB_MAIN_TYPE *Main = GB_MAIN(gbc);
2621
2622    GB_test_transaction(Main);
2623
2624    int ubit = Main->users[0]->userbit;
2625    int prev = GB_ARRAY_FLAGS(gbc).flags;
2626    gbc->flags.saved_flags = prev;
2627
2628    if (flag) {
2629        GB_ARRAY_FLAGS(gbc).flags |= ubit;
2630    }
2631    else {
2632        GB_ARRAY_FLAGS(gbc).flags &= ~ubit;
2633    }
2634    if (prev != (int)GB_ARRAY_FLAGS(gbc).flags) {
2635        gb_touch_entry(gbc, GB_NORMAL_CHANGE);
2636        gb_touch_header(GB_FATHER(gbc));
2637        GB_DO_CALLBACKS(gbc);
2638    }
2639}
2640
2641int GB_read_flag(GBDATA *gbd) {
2642    GB_test_transaction(gbd);
2643    if (GB_ARRAY_FLAGS(gbd).flags & GB_MAIN(gbd)->users[0]->userbit) return 1;
2644    else return 0;
2645}
2646
2647void GB_touch(GBDATA *gbd) {
2648    GB_test_transaction(gbd);
2649    gb_touch_entry(gbd, GB_NORMAL_CHANGE);
2650    GB_DO_CALLBACKS(gbd);
2651}
2652
2653
2654char GB_type_2_char(GB_TYPES type) {
2655    const char *type2char = "-bcif-B-CIFlSS-%";
2656    return type2char[type];
2657}
2658
2659void GB_print_debug_information(struct Unfixed_cb_parameter *, GBDATA *gb_main) {
2660    GB_MAIN_TYPE *Main = GB_MAIN(gb_main);
2661    GB_push_transaction(gb_main);
2662    for (int i=0; i<Main->keycnt; i++) {
2663        gb_Key& KEY = Main->keys[i];
2664        if (KEY.key) {
2665            printf("%3i %20s    nref %li\n", i, KEY.key, KEY.nref);
2666        }
2667        else {
2668            printf("    %3i unused key, next free key = %li\n", i, KEY.next_free_key);
2669        }
2670    }
2671    gbm_debug_mem();
2672    GB_pop_transaction(gb_main);
2673}
2674
2675static int GB_info_deep = 15;
2676
2677
2678static int gb_info(GBDATA *gbd, int deep) {
2679    if (gbd==NULL) { printf("NULL\n"); return -1; }
2680    GB_push_transaction(gbd);
2681
2682    GB_TYPES type = gbd->type();
2683
2684    if (deep) {
2685        printf("    ");
2686    }
2687
2688    printf("(GBDATA*)0x%lx (GBCONTAINER*)0x%lx ", (long)gbd, (long)gbd);
2689
2690    if (gbd->rel_father==0) { printf("father=NULL\n"); return -1; }
2691
2692    GBCONTAINER  *gbc;
2693    GB_MAIN_TYPE *Main;
2694    if (type==GB_DB) { gbc = gbd->as_container(); Main = GBCONTAINER_MAIN(gbc); }
2695    else             { gbc = NULL;                Main = GB_MAIN(gbd); }
2696
2697    if (!Main) { printf("Oops - I have no main entry!!!\n"); return -1; }
2698    if (gbd==Main->dummy_father) { printf("dummy_father!\n"); return -1; }
2699
2700    printf("%10s Type '%c'  ", GB_read_key_pntr(gbd), GB_type_2_char(type));
2701
2702    switch (type) {
2703        case GB_DB: {
2704            int size = gbc->d.size;
2705            printf("Size %i nheader %i hmemsize %i", gbc->d.size, gbc->d.nheader, gbc->d.headermemsize);
2706            printf(" father=(GBDATA*)0x%lx\n", (long)GB_FATHER(gbd));
2707            if (size < GB_info_deep) {
2708                int             index;
2709                gb_header_list *header;
2710
2711                header = GB_DATA_LIST_HEADER(gbc->d);
2712                for (index = 0; index < gbc->d.nheader; index++) {
2713                    GBDATA  *gb_sub = GB_HEADER_LIST_GBD(header[index]);
2714                    GBQUARK  quark  = header[index].flags.key_quark;
2715                    printf("\t\t%10s (GBDATA*)0x%lx (GBCONTAINER*)0x%lx\n", quark2key(Main, quark), (long)gb_sub, (long)gb_sub);
2716                }
2717            }
2718            break;
2719        }
2720        default: {
2721            char *data = GB_read_as_string(gbd);
2722            if (data) { printf("%s", data); free(data); }
2723            printf(" father=(GBDATA*)0x%lx\n", (long)GB_FATHER(gbd));
2724        }
2725    }
2726
2727
2728    GB_pop_transaction(gbd);
2729
2730    return 0;
2731}
2732
2733int GB_info(GBDATA *gbd) { // unused - intended to be used in debugger
2734    return gb_info(gbd, 0);
2735}
2736
2737long GB_number_of_subentries(GBDATA *gbd) {
2738    GBCONTAINER    *gbc        = gbd->expect_container();
2739    gb_header_list *header     = GB_DATA_LIST_HEADER(gbc->d);
2740
2741    long subentries = 0;
2742    int  end        = gbc->d.nheader;
2743
2744    for (int index = 0; index<end; index++) {
2745        if (header[index].flags.changed < GB_DELETED) subentries++;
2746    }
2747    return subentries;
2748}
2749
2750// --------------------------------------------------------------------------------
2751
2752#ifdef UNIT_TESTS
2753
2754#include <test_unit.h>
2755#include <locale.h>
2756
2757void TEST_GB_atof() {
2758    // startup of ARB (gtk_only@11651) is failing on ubuntu 13.10 (in GBT_read_tree)
2759    // (failed with "Error: 'GB_safe_atof("0.0810811", ..) returns error: cannot convert '0.0810811' to double'")
2760    // Reason: LANG[UAGE] or LC_NUMERIC set to "de_DE..."
2761    //
2762    // Notes:
2763    // * gtk apparently calls 'setlocale(LC_ALL, "");', motif doesnt
2764
2765    TEST_EXPECT_SIMILAR(GB_atof("0.031"), 0.031, 0.0001); // @@@ make this fail, then fix it
2766}
2767
2768void TEST_999_strtod_replacement() {
2769    // caution: if it fails -> locale is not reset (therefore call with low priority 999)
2770    const char *old = setlocale(LC_NUMERIC, "de_DE.UTF-8");
2771    {
2772        // TEST_EXPECT_SIMILAR__BROKEN(strtod("0.031", NULL), 0.031, 0.0001);
2773        TEST_EXPECT_SIMILAR(g_ascii_strtod("0.031", NULL), 0.031, 0.0001);
2774    }
2775    setlocale(LC_NUMERIC, old);
2776}
2777
2778static void test_another_shell() { delete new GB_shell; }
2779static void test_opendb() { GB_close(GB_open("no.arb", "c")); }
2780
2781void TEST_GB_shell() {
2782    {
2783        GB_shell *shell = new GB_shell;
2784        TEST_EXPECT_SEGFAULT(test_another_shell);
2785        test_opendb(); // no SEGV here
2786        delete shell;
2787    }
2788
2789    TEST_EXPECT_SEGFAULT(test_opendb); // should be impossible to open db w/o shell
2790}
2791
2792void TEST_GB_number_of_subentries() {
2793    GB_shell  shell;
2794    GBDATA   *gb_main = GB_open("no.arb", "c");
2795
2796    {
2797        GB_transaction ta(gb_main);
2798
2799        GBDATA   *gb_cont = GB_create_container(gb_main, "container");
2800        TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 0);
2801
2802        TEST_EXPECT_RESULT__NOERROREXPORTED(GB_create(gb_cont, "entry", GB_STRING));
2803        TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 1);
2804
2805        {
2806            GBDATA *gb_entry;
2807            TEST_EXPECT_RESULT__NOERROREXPORTED(gb_entry = GB_create(gb_cont, "entry", GB_STRING));
2808            TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 2);
2809
2810            TEST_EXPECT_NO_ERROR(GB_delete(gb_entry));
2811            TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 1);
2812        }
2813
2814        TEST_EXPECT_RESULT__NOERROREXPORTED(GB_create(gb_cont, "entry", GB_STRING));
2815        TEST_EXPECT_EQUAL(GB_number_of_subentries(gb_cont), 2);
2816    }
2817
2818    GB_close(gb_main);
2819}
2820
2821
2822void TEST_POSTCOND_arbdb() {
2823    GB_ERROR error             = GB_incur_error(); // clears the error (to make further tests succeed)
2824    bool     unclosed_GB_shell = closed_open_shell_for_unit_tests();
2825
2826    TEST_REJECT(error);             // your test finished with an exported error
2827    TEST_REJECT(unclosed_GB_shell); // your test finished w/o destroying GB_shell
2828}
2829
2830#endif // UNIT_TESTS
2831
2832
Note: See TracBrowser for help on using the repository browser.