source: tags/ms_r17q1/ARBDB/arbdb.cxx

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