source: tags/ms_r16q2/ARBDB/arbdb.cxx

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