source: tags/ms_r17q2/ARBDB/ad_load.cxx

Last change on this file was 16119, checked in by westram, 7 years ago
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 56.1 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : ad_load.cxx                                       //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include <cctype>
12#include <ctime>
13#include <netinet/in.h>
14#include <sys/stat.h>
15
16#include <arbdbt.h>
17#include <arb_str.h>
18#include <arb_file.h>
19#include <arb_defs.h>
20#include <arb_progress.h>
21#include <arb_zfile.h>
22#include <BufferedFileReader.h>
23
24#include "gb_key.h"
25#include "gb_localdata.h"
26#include "gb_map.h"
27#include "gb_load.h"
28#include "ad_io_inline.h"
29
30static int gb_verbose_mode = 0;
31void GB_set_verbose() {
32    gb_verbose_mode = 1;
33}
34
35#define FILESIZE_GRANULARITY 1024 // progress will work with DB files up to 2Tb
36
37/* ----------------------------------------
38 * ASCII format
39 *
40 * Versions:
41 *
42 * V0  - 20.6.95
43 * V1  Full save
44 * V2  Differential save
45 * V3  May read from stdin. Skipped support for old ASCII format.
46 */
47
48static const char *getToken(char **line) {
49    char *token  = *line;
50    (*line)     += strcspn(*line, " \t");
51
52    if ((*line)[0]) {                               // sth follows behind token
53        (*line)[0]  = 0;                            // terminate token
54        (*line)++;
55        (*line)    += strspn(*line, " \t");         // goto next token
56    }
57
58    return token;
59}
60
61static GB_ERROR set_protection_level(GB_MAIN_TYPE *Main, GBDATA *gbd, const char *p) {
62    int      secr, secw, secd, lu;
63    GB_ERROR error = 0;
64
65    secr = secw = secd = 0;
66    lu   = 0;
67
68    if (p && p[0] == ':') {
69        long i;
70
71        secd = p[1]; A_TO_I(secd);
72        secw = p[2]; A_TO_I(secw);
73        secr = p[3]; A_TO_I(secr);
74
75        if (secd<0 || secd>7) error = GBS_global_string("Illegal protection level %i", secd);
76        else if (secw<0 || secw>7) error = GBS_global_string("Illegal protection level %i", secw);
77        else if (secr<0 || secr>7) error = GBS_global_string("Illegal protection level %i", secr);
78
79        lu = atoi(p+4);
80
81        for (i=Main->last_updated; i<=lu; ++i) {
82            gb_assert(i<ALLOWED_DATES);
83            Main->dates[i]     = ARB_strdup("unknown date");
84            Main->last_updated = lu+1;
85        }
86    }
87
88    if (!error) {
89        gbd->flags.security_delete = secd;
90        gbd->flags.security_write  = secw;
91        gbd->flags.security_read   = secr;
92        gbd->flags2.last_updated   = lu;
93    }
94
95    return error;
96}
97
98static GB_ERROR gb_parse_ascii_rek(LineReader& r, GBCONTAINER *gb_parent, const char *parent_name) {
99    // if parent_name == 0 -> we are parsing at root-level
100    GB_ERROR      error = 0;
101    int           done  = 0;
102    GB_MAIN_TYPE *Main  = GBCONTAINER_MAIN(gb_parent);
103
104    while (!error && !done) {
105        string LINE;
106        if (!r.getLine(LINE)) break;
107
108        char *line = (char*)(LINE.c_str()); // HACK: code below will modify the content of the string
109
110      rest :
111        line += strspn(line, " \t"); // goto first non-whitespace
112
113        if (line[0]) {          // not empty
114            if (line[0] == '/' && line[1] == '*') { // comment
115                char *eoc = strstr(line+2, "*/");
116                if (eoc) {
117                    line = eoc+2;
118                    goto rest;
119                }
120                error = "expected '*/'";
121            }
122            else { // real content
123                const char *name = getToken(&line);
124
125                if (name[0] == '%' && name[1] == ')' && !name[2]) { // close container
126                    if (!parent_name) {
127                        error = "Unexpected '%)' (not allowed outside container)";
128                    }
129                    else {
130                        if (line[0] == '/' && line[1] == '*') { // comment at container-end
131                            char *eoc  = strstr(line+2, "*/");
132                            if (!eoc) {
133                                error = "expected '*/'"; 
134                            }
135                            else {
136                                line += 2;
137                                *eoc  = 0;
138                                if (strcmp(line, parent_name) != 0) {
139                                    fprintf(stderr,
140                                            "Warning: comment at end of container ('%s') does not match name of container ('%s').\n"
141                                            "         (might be harmless if you've edited the file and did not care about these comments)\n",
142                                            line, parent_name); 
143                                }
144                                line = eoc+2;
145                            }
146                        }
147                        done = 1;
148                    }
149                }
150                else {
151                    const char *protection = NULL;
152                    if (line[0] == ':') {           // protection level
153                        protection = getToken(&line);
154                    }
155
156                    bool readAsString = true;
157                    if (line[0] == '%') {
158                        readAsString = false;
159
160                        const char *type = getToken(&line);
161
162                        if (type[1] == 0 || type[2] != 0) {
163                            error = GBS_global_string("Syntax error in type '%s' (expected %% and 1 more character)", type);
164                        }
165                        else {
166                            if (type[1] == '%' || type[1] == '$') {   // container
167                                if (line[0] == '(' && line[1] == '%') {
168                                    char        *cont_name = ARB_strdup(name);
169                                    GBCONTAINER *gbc       = gb_make_container(gb_parent, cont_name, -1, 0);
170
171                                    char *protection_copy = nulldup(protection);
172                                    bool  marked          = type[1] == '$';
173                                    error                 = gb_parse_ascii_rek(r, gbc, cont_name);
174                                    // CAUTION: most buffer variables are invalidated NOW!!!
175
176                                    if (!error) error = set_protection_level(Main, gbc, protection_copy);
177                                    if (marked) GB_write_flag(gbc, 1);
178
179                                    free(protection_copy);
180                                    free(cont_name);
181                                }
182                                else {
183                                    error = "Expected '(%' after '%%'";
184                                }
185                            }
186                            else {
187                                GB_TYPES gb_type = GB_NONE;
188
189                                switch (type[1]) {
190                                    case 'i': gb_type = GB_INT; break;
191                                    case 'l': gb_type = GB_OBSOLETE; break;
192                                    case 'y': gb_type = GB_BYTE; break;
193                                    case 'f': gb_type = GB_FLOAT; break;
194                                    case 'I': gb_type = GB_BITS; break;
195
196                                    case 'Y': gb_type = GB_BYTES; break;
197                                    case 'N': gb_type = GB_INTS; break;
198                                    case 'F': gb_type = GB_FLOATS; break;
199                                    case 's': gb_type = GB_STRING; readAsString = true; break; // special case (string starts with '%')
200
201                                    default:
202                                        error = GBS_global_string("Unknown type '%s'", type);
203                                        break;
204                                }
205
206                                if (!error && !readAsString) {
207                                    gb_assert(gb_type != GB_NONE);
208
209                                    if (gb_type == GB_OBSOLETE) {
210                                        fputs("Skipped entry (obsolete type GB_LINK)\n", stderr);
211                                    }
212                                    else {
213                                        GBENTRY *gb_new    = gb_make_entry(gb_parent, name, -1, 0, gb_type);
214                                        if (!gb_new) error = GB_await_error();
215                                        else {
216                                            switch (type[1]) {
217                                                case 'i': error = GB_write_int(gb_new, atoi(line)); break;
218                                                case 'y': error = GB_write_byte(gb_new, atoi(line)); break;
219                                                case 'f': error = GB_write_float(gb_new, GB_atof(line)); break;
220                                                case 'I': {
221                                                    int len = strlen(line);
222                                                    gb_assert(line[0] == '\"');
223                                                    gb_assert(line[len-1] == '\"');
224                                                    error   = GB_write_bits(gb_new, line+1, len-2, "-"); break;
225                                                }
226
227                                                case 'Y': if (gb_ascii_2_bin(line, gb_new)) error = "syntax error in byte-array"; break;
228                                                case 'N': if (gb_ascii_2_bin(line, gb_new)) error = "syntax error in int-array"; break;
229                                                case 'F': if (gb_ascii_2_bin(line, gb_new)) error = "syntax error in float-array"; break;
230
231                                                default: gb_assert(0);  // forgot a case ?
232                                            }
233
234                                            if (!error) error = set_protection_level(Main, gb_new, protection);
235                                        }
236                                    }
237                                }
238                            }
239                        }
240                    }
241                   
242                    if (readAsString) {
243                        if (line[0] != '\"') {
244                            error = GBS_global_string("Unexpected content '%s'", line);
245                        }
246                        else {                      // string entry
247                            char *string_start = line+1;
248                            char *end          = GBS_fconvert_string(string_start);
249
250                            if (!end) error = "Cannot convert string (contains zero char)";
251                            else {
252                                GBDATA *gb_string     = gb_make_entry(gb_parent, name, -1, 0, GB_STRING);
253                                if (!gb_string) error = GB_await_error();
254                                else {
255                                    error             = GB_write_string(gb_string, string_start);
256                                    if (!error) error = set_protection_level(Main, gb_string, protection);
257                                }
258                            }
259                        }
260                    }
261                }
262            }
263        }
264    }
265
266    return error;
267}
268
269static GB_ERROR gb_parse_ascii(LineReader& r, GBCONTAINER *gb_parent) {
270    GB_ERROR error = gb_parse_ascii_rek(r, gb_parent, 0);
271    if (error) {
272        error = GBS_global_string("%s in line %zu", error, r.getLineNumber()); // @@@ consider using r.lineError
273    }
274    return error;
275}
276
277struct BufferedPipeReader : public BufferedFileReader {
278    BufferedPipeReader(const string& pipename, FILE *in)
279        : BufferedFileReader(pipename, in)
280    {}
281    ~BufferedPipeReader() {
282        gb_assert(get_fp() == NULL); // you HAVETO call close() or dont_close() manually
283                                     // (to check the error and to close the pipe)
284    }
285
286    GB_ERROR close() {
287        FILE*&   pipe  = get_fp();
288        GB_ERROR error = ARB_zfclose(pipe);
289        pipe           = NULL;
290        return error;
291    }
292
293    void dont_close() {
294        FILE*& f = get_fp();
295        f        = NULL;
296    }
297};
298
299static GB_ERROR gb_read_ascii_beyond_header(FILE *in, const char *path, GBCONTAINER *gbc) {
300    // This loads an ASCII database (header line has already been read!)
301    GB_ERROR           error = 0;
302    BufferedPipeReader r(path, in);
303
304    GB_search(gbc, GB_SYSTEM_FOLDER, GB_CREATE_CONTAINER); // Switch to Version 3
305    error = gb_parse_ascii(r, gbc);
306    r.dont_close();                                        // done by caller
307
308    return error;
309}
310
311// --------------------------
312//      Read binary files
313
314static long gb_recover_corrupt_file(GBCONTAINER *gbc, FILE *in, GB_ERROR recovery_reason, bool loading_quick_save) {
315    // search pattern dx xx xx xx string 0
316    // returns 0 if recovery was able to resync
317    static FILE *old_in = 0;
318    static unsigned char *file = 0;
319    static long size = 0;
320    if (!GBCONTAINER_MAIN(gbc)->allow_corrupt_file_recovery) {
321        if (!recovery_reason) { recovery_reason = GB_await_error(); }
322        char       *reason         = ARB_strdup(recovery_reason);
323        const char *located_reason = GBS_global_string("%s (inside '%s')", reason, GB_get_db_path(gbc));
324
325        if (loading_quick_save) {
326            GB_export_error(located_reason);
327        }
328        else {
329            GB_export_errorf("%s\n"
330                             "(parts of your database might be recoverable using 'arb_repair yourDB.arb newName.arb')\n",
331                             located_reason);
332        }
333        free(reason);
334        return -1;
335    }
336
337    if (GB_is_fifo(in)) {
338        GB_export_error("Unable to recover from corrupt file (Reason: cannot recover from stream)\n"
339                        "Note: if the file is a compressed arb-file, uncompress it manually and retry.");
340        return -1;
341    }
342
343    long pos = ftell(in);
344    if (old_in != in) {
345        file   = (unsigned char *)GB_map_FILE(in, 0);
346        old_in = in;
347        size   = GB_size_of_FILE(in);
348    }
349    for (; pos<size-10; pos ++) {
350        if ((file[pos] & 0xf0) == (GB_STRING_SHRT<<4)) {
351            long s;
352            int c;
353            for (s = pos + 4; s<size && file[s]; s++) {
354                c = file[s];
355                if (! (isalnum(c) || isspace(c) || strchr("._;:,", c))) break;
356            }
357            if (s< size && s > pos+11 && !file[s]) {    // we found something
358                gb_local->search_system_folder = true;
359                return fseek(in, pos, 0);
360            }
361        }
362    }
363    return -1;          // no short string found
364}
365
366// ----------------------------------------
367// #define DEBUG_READ
368#if defined(DEBUG_READ)
369
370static void DEBUG_DUMP_INDENTED(long deep, const char *s) {
371    printf("%*s%s\n", (int)deep, "", s);
372}
373
374#else
375#define DEBUG_DUMP_INDENTED(d, s)
376#endif // DEBUG_READ
377// ----------------------------------------
378
379static long gb_read_bin_rek_V2(FILE *in, GBCONTAINER *gbc_dest, long nitems, long version, 
380                               long reversed, long deep, arb_progress& progress) {
381    GB_MAIN_TYPE *Main = GB_MAIN(gbc_dest);
382
383    DEBUG_DUMP_INDENTED(deep, GBS_global_string("Reading container with %li items", nitems));
384
385    progress.inc_to(ftell(in)/FILESIZE_GRANULARITY);
386    if (progress.aborted()) {
387        GB_export_error(progress.error_if_aborted());
388        return -1;
389    }
390
391    gb_create_header_array(gbc_dest, (int)nitems);
392    gb_header_list *header = GB_DATA_LIST_HEADER(gbc_dest->d);
393    if (deep == 0 && GBCONTAINER_MAIN(gbc_dest)->allow_corrupt_file_recovery) {
394        GB_warning("Now reading to end of file (trying to recover data from broken database)");
395        nitems = 10000000; // read forever at highest level
396    }
397
398    bool is_quicksave = version != 1;
399
400    for (long item = 0; item<nitems; item++) {
401        long type = getc(in);
402        DEBUG_DUMP_INDENTED(deep, GBS_global_string("Item #%li/%li type=%02lx (filepos=%08lx)", item+1, nitems, type, ftell(in)-1));
403        if (type == EOF) {
404            if (GBCONTAINER_MAIN(gbc_dest)->allow_corrupt_file_recovery) {
405                GB_export_error("End of file reached (no error)");
406            }
407            else {
408                GB_export_error("Unexpected end of file seen");
409            }
410            return -1;
411        }
412        if (!type) {
413            int func;
414            if (version == 1) { // master file
415                if (gb_recover_corrupt_file(gbc_dest, in, "Unknown DB type 0 (DB version=1)", is_quicksave)) return -1;
416                continue;
417            }
418            func = getc(in);
419            switch (func) {
420                case 1: {    //  delete entry
421                    int index = (int)gb_get_number(in);
422                    if (index >= gbc_dest->d.nheader) {
423                        gb_create_header_array(gbc_dest, index+1);
424                        header = GB_DATA_LIST_HEADER(gbc_dest->d);
425                    }
426
427                    GBDATA *gb2 = GB_HEADER_LIST_GBD(header[index]);
428                    if (gb2) {
429                        gb_delete_entry(gb2);
430                    }
431                    else {
432                        header[index].flags.set_change(GB_DELETED);
433                    }
434
435                    break;
436                }
437                default:
438                    if (gb_recover_corrupt_file(gbc_dest, in, GBS_global_string("Unknown func=%i", func), is_quicksave)) return -1;
439                    continue;
440            }
441            continue;
442        }
443
444        long    security = getc(in);
445        long    type2    = (type>>4)&0xf;
446        GBQUARK key      = (GBQUARK)gb_get_number(in);
447
448        if (key >= Main->keycnt || !quark2key(Main, key)) {
449            const char *reason = GBS_global_string("database entry with unknown field quark %i", key);
450            if (gb_recover_corrupt_file(gbc_dest, in, reason, is_quicksave)) return -1;
451            continue;
452        }
453
454        DEBUG_DUMP_INDENTED(deep, GBS_global_string("key='%s' type2=%li", quark2key(Main, key), type2));
455
456        GBENTRY     *gbe = NULL;
457        GBCONTAINER *gbc = NULL;
458        GBDATA      *gbd = NULL;
459
460        {
461            int index;
462            if (version == 2) {
463                index = (int)gb_get_number(in);
464                if (index >= gbc_dest->d.nheader) {
465                    gb_create_header_array(gbc_dest, index+1);
466                    header = GB_DATA_LIST_HEADER(gbc_dest->d);
467                }
468
469                if (index >= 0 && (gbd = GB_HEADER_LIST_GBD(header[index]))!=NULL) {
470                    if ((gbd->type() == GB_DB) != (type2 == GB_DB)) {
471                        GB_internal_error("Type changed, you may loose data");
472                        gb_delete_entry(gbd);
473                        SET_GB_HEADER_LIST_GBD(header[index], NULL);
474                    }
475                    else {
476                        if (type2 == GB_DB) {
477                            gbc = gbd->as_container();
478                        }
479                        else {
480                            gbe = gbd->as_entry();
481                            gbe->free_data();
482                        }
483                    }
484                }
485            }
486            else index = -1;
487
488            if (!gbd) {
489                if (type2 == (long)GB_DB) {
490                    gbd = gbc = gb_make_container(gbc_dest, NULL, index, key);
491                }
492                else {
493                    gbd = gbe = gb_make_entry(gbc_dest, NULL, index, key, (GB_TYPES)type2);
494                    gbe->index_check_out();
495                }
496            }
497        }
498
499        gb_assert(implicated(gbe, gbe == gbd));
500        gb_assert(implicated(gbc, gbc == gbd));
501        gb_assert(implicated(gbd, contradicted(gbe, gbc)));
502
503        if (version == 2) {
504            gbd->create_extended();
505            gbd->touch_creation_and_update(Main->clock);
506            header[gbd->index].flags.ever_changed = 1;
507        }
508        else {
509            Main->keys[key].nref_last_saved++;
510        }
511
512        gbd->flags.security_delete     = type >> 1;
513        gbd->flags.security_write      = ((type&1) << 2) + (security >> 6);
514        gbd->flags.security_read       = security >> 3;
515        gbd->flags.compressed_data     = security >> 2;
516        header[gbd->index].flags.flags = (int)((security >> 1) & 1);
517        gbd->flags.unused              = security >> 0;
518        gbd->flags2.last_updated       = getc(in);
519
520        switch (type2) {
521            case GB_INT:
522                {
523                    GB_UINT4 buffer;
524                    if (!fread((char*)&buffer, sizeof(GB_UINT4), 1, in)) {
525                        GB_export_error("File too short, seems truncated");
526                        return -1;
527                    }
528                    gbe->info.i = ntohl(buffer);
529                    break;
530                }
531
532            case GB_FLOAT:
533                if (!fread((char*)&gbe->info.i, sizeof(float), 1, in)) {
534                    GB_export_error("File too short, seems truncated");
535                    return -1;
536                }
537                break;
538            case GB_STRING_SHRT: {
539                long  i    = GB_give_buffer_size();
540                char *buff = GB_give_buffer(GBTUM_SHORT_STRING_SIZE+2);
541                char *p    = buff;
542
543                long size = 0;
544                while (1) {
545                    for (; size<i; size++) {
546                        if (!(*(p++) = getc(in))) goto shrtstring_fully_loaded;
547                    }
548                    i = i*3/2;
549                    buff = GB_increase_buffer(i);
550                    p = buff + size;
551                }
552                  shrtstring_fully_loaded :
553                gbe->insert_data(buff, size, size+1);
554                break;
555            }
556            case GB_OBSOLETE:
557            case GB_STRING:
558            case GB_BITS:
559            case GB_BYTES:
560            case GB_INTS:
561            case GB_FLOATS: {
562                long size    = gb_get_number(in);
563                long memsize = gb_get_number(in);
564
565                DEBUG_DUMP_INDENTED(deep, GBS_global_string("size=%li memsize=%li", size, memsize));
566
567                GBENTRY_memory storage(gbe, size, memsize);
568
569                long i = fread(storage, 1, (size_t)memsize, in);
570                if (i!=memsize) {
571                    gb_read_bin_error(in, gbe, "Unexpected EOF found");
572                    return -1;
573                }
574                break;
575            }
576            case GB_DB: {
577                long size = gb_get_number(in);
578                // gbc->d.size  is automatically incremented
579                if (gb_read_bin_rek_V2(in, gbc, size, version, reversed, deep+1, progress)) {
580                    if (!GBCONTAINER_MAIN(gbc_dest)->allow_corrupt_file_recovery) {
581                        return -1;
582                    }
583                }
584                break;
585            }
586            case GB_BYTE:
587                gbe->info.i = getc(in);
588                break;
589            default:
590                gb_read_bin_error(in, gbd, "Unknown type");
591                if (gb_recover_corrupt_file(gbc_dest, in, NULL, is_quicksave)) {
592                    return GBCONTAINER_MAIN(gbc_dest)->allow_corrupt_file_recovery
593                        ? 0                         // loading stopped
594                        : -1;
595                }
596
597                continue;
598        }
599    }
600    return 0;
601}
602
603static GBDATA *gb_search_system_folder_rek(GBDATA *gbd) {
604    GBDATA *gb2;
605    GBDATA *gb_result = 0;
606    for (gb2 = GB_child(gbd); gb2; gb2 = GB_nextChild(gb2)) {
607        int type = GB_read_type(gb2);
608        if (type != GB_DB) continue;
609        if (!strcmp(GB_SYSTEM_FOLDER, GB_read_key_pntr(gb2))) {
610            gb_result = gb2;
611            break;
612        }
613    }
614    return gb_result;
615}
616
617
618static void gb_search_system_folder(GBDATA *gb_main) {
619    /* Search a system folder within the database tree
620     * and copy it to main level
621     */
622    GBDATA   *gb_oldsystem;
623    GB_ERROR  error;
624    GBDATA   *gb_system = GB_entry(gb_main, GB_SYSTEM_FOLDER);
625    if (gb_system) return;
626
627    GB_warning("Searching system information");
628    gb_oldsystem = gb_search_system_folder_rek(gb_main);
629    if (!gb_oldsystem) {
630        GB_warning("!!!!! not found (bad)");
631        return;
632    }
633    gb_system = GB_search(gb_main, GB_SYSTEM_FOLDER, GB_CREATE_CONTAINER);
634    error = GB_copy(gb_system, gb_oldsystem);
635    if (!error) error = GB_delete(gb_oldsystem);
636    if (error) GB_warning(error);
637    GB_warning("***** found (good)");
638}
639
640inline bool read_keyword(const char *expected_keyword, FILE *in, GBCONTAINER *gbc) {
641    gb_assert(strlen(expected_keyword) == 4); // mandatory
642
643    long val         = gb_read_in_uint32(in, 0);
644    bool as_expected = strncmp((char*)&val, expected_keyword, 4) == 0;
645   
646    if (!as_expected) {
647        gb_read_bin_error(in, gbc, GBS_global_string("keyword '%s' not found", expected_keyword));
648    }
649    return as_expected;
650}
651
652static long gb_read_bin(FILE *in, GBCONTAINER *gbc, bool allowed_to_load_diff, arb_progress& progress) {
653    int   c = 1;
654    long  i;
655    long  error;
656    long  j, k;
657    long  version;
658    long  nodecnt;
659    long  first_free_key;
660    char *buffer, *p;
661
662    GB_MAIN_TYPE *Main = GBCONTAINER_MAIN(gbc);
663
664    while (c && c != EOF) {
665        c = getc(in);
666    }
667    if (c==EOF) {
668        gb_read_bin_error(in, gbc, "First zero not found");
669        return 1;
670    }
671
672    if (!read_keyword("vers", in, gbc)) return 1;
673
674    // detect byte order in ARB file
675    i = gb_read_in_uint32(in, 0);
676    bool reversed;
677    switch (i) {
678        case 0x01020304: reversed = false; break;
679        case 0x04030201: reversed = true; break;
680        default:
681            gb_read_bin_error(in, gbc, "keyword '^A^B^C^D' not found");
682            return 1;
683    }
684
685    version = gb_read_in_uint32(in, reversed);
686    if (version == 0) {
687        gb_read_bin_error(in, gbc, "ARB Database version 0 no longer supported (rev [9647])");
688        return 1;
689    }
690    if (version>2) {
691        gb_read_bin_error(in, gbc, "ARB Database version > '2'");
692        return 1;
693    }
694
695    if (version == 2 && !allowed_to_load_diff) {
696        GB_export_error("This is not a primary arb file, please select the master"
697                        " file xxx.arb");
698        return 1;
699    }
700
701    if (!read_keyword("keys", in, gbc)) return 1;
702
703    if (!Main->key_2_index_hash) Main->key_2_index_hash = GBS_create_hash(ALLOWED_KEYS, GB_MIND_CASE);
704
705    first_free_key = 0;
706    Main->free_all_keys();
707
708    buffer = GB_give_buffer(256);
709    while (1) {         // read keys
710        long nrefs = 0;
711        if (version) {
712            nrefs = gb_get_number(in);
713        }
714        p = buffer;
715        for (k=0; ; k++) {
716            c = getc(in);
717            if (!c) break;
718            if (c==EOF) {
719                gb_read_bin_error(in, gbc, "unexpected EOF while reading keys");
720                return 1;
721            }
722            *(p++) = c;
723        }
724        *p = 0;
725
726        if (k > GB_KEY_LEN_MAX) {
727            printf("Warning: Key '%s' exceeds maximum keylength (%i)\n"
728                   "         Please do NOT create such long keys!\n",
729                   buffer, GB_KEY_LEN_MAX);
730        }
731        if (p == buffer) break;
732
733        if (*buffer == 1) {                                                   // empty key
734            long index = gb_create_key(Main, 0, false);
735
736            Main->keys[index].key           = 0;
737            Main->keys[index].nref          = 0;
738            Main->keys[index].next_free_key = first_free_key;
739
740            first_free_key = index;
741        }
742        else {
743            long index = gb_create_key(Main, buffer, false);
744
745            Main->keys[index].nref = nrefs;
746        }
747    }
748
749    Main->first_free_key = first_free_key;
750
751    if (!read_keyword("time", in, gbc)) return 1;
752   
753    for (j=0; j<(ALLOWED_DATES-1); j++) {         // read times
754        p = buffer;
755        for (k=0; k<256; k++) {
756            c = getc(in);
757            if (!c) break;
758            if (c==EOF) {
759                gb_read_bin_error(in, gbc, "unexpected EOF while reading times");
760                return 1;
761            }
762            *(p++) = c;
763        }
764        *p = 0;
765        if (p == buffer) break;
766        freedup(Main->dates[j], buffer);
767    }
768    if (j>=(ALLOWED_DATES-1)) {
769        gb_read_bin_error(in, gbc, "too many date entries");
770        return 1;
771    }
772    Main->last_updated = (unsigned int)j;
773
774    if (!read_keyword("data", in, gbc)) return 1;
775
776    nodecnt = gb_read_in_uint32(in, reversed);
777    GB_give_buffer(256);
778
779    if (version==1) {                                     // teste auf map file falls version == 1
780        long          mode = GB_mode_of_link(Main->path); // old master
781        GB_CSTR       map_path;
782        unsigned long time_of_db;
783
784        if (S_ISLNK(mode)) {
785            char *path2 = GB_follow_unix_link(Main->path);
786            map_path    = gb_mapfile_name(path2);
787            time_of_db  = GB_time_of_file(path2);
788            free(path2);
789        }
790        else {
791            map_path = gb_mapfile_name(Main->path);
792            time_of_db  = GB_time_of_file(Main->path);
793        }
794
795        bool          mapped          = false;
796        GB_ERROR      map_fail_reason = NULL;
797        gb_map_header mheader;
798
799        switch (gb_is_valid_mapfile(map_path, &mheader, 0)) {
800            case -1: map_fail_reason = GBS_global_string("no FastLoad File '%s' found", map_path); break;
801            case  0: map_fail_reason = GB_await_error(); break;
802            case  1: {
803                unsigned long time_of_map = GB_time_of_file(map_path);
804
805                if (time_of_map != time_of_db) { // timestamp of mapfile differs
806                    unsigned long diff = time_of_map>time_of_db ? time_of_map-time_of_db : time_of_db-time_of_map;
807                    fprintf(stderr, "Warning: modification times of DB and fastload file differ (DB=%lu fastload=%lu diff=%lu)\n",
808                            time_of_db, time_of_map, diff);
809
810                    if (diff>5) {
811                        map_fail_reason = "modification times of DB and fastload file differ (too much)";
812                    }
813                    else {
814                        fprintf(stderr, "(accepting modification time difference of %lu seconds)\n", diff);
815                    }
816                }
817
818                if (!map_fail_reason) {
819                    if (gb_main_array[mheader.main_idx]==NULL) {
820                        GBCONTAINER *new_gbc = (GBCONTAINER*)gb_map_mapfile(map_path);
821
822                        if (new_gbc) {
823                            GBCONTAINER *father  = GB_FATHER(gbc);
824                            GB_MAIN_IDX  new_idx = mheader.main_idx;
825                            GB_MAIN_IDX  old_idx = father->main_idx;
826
827                            long gbc_index = gbc->index;
828
829                            GB_commit_transaction((GBDATA*)gbc);
830
831                            gb_assert(new_gbc->main_idx == new_idx);
832                            gb_assert((new_idx % GB_MAIN_ARRAY_SIZE) == new_idx);
833
834                            gb_main_array[new_idx] = Main;
835
836                            gbm_free_mem(Main->root_container, sizeof(GBCONTAINER), quark2gbmindex(Main, 0));
837
838                            Main->root_container = new_gbc;
839                            father->main_idx     = new_idx;
840
841                            SET_GBCONTAINER_ELEM(father, gbc_index, NULL); // unlink old main-entry
842
843                            gbc = new_gbc;
844                            SET_GB_FATHER(gbc, father);
845                       
846                            SET_GBCONTAINER_ELEM(father, gbc->index, (GBDATA*)gbc); // link new main-entry
847
848                            gb_main_array[old_idx]    = NULL;
849
850                            GB_begin_transaction((GBDATA*)gbc);
851                            mapped = true;
852                        }
853                    }
854                    else {
855                        map_fail_reason = GBS_global_string("FastLoad-File index conflict (%s, %i)", map_path, mheader.main_idx);
856                    }
857                }
858           
859                break;
860            }
861            default: gb_assert(0); break;
862        }
863
864        gb_assert(mapped || map_fail_reason);
865
866        if (mapped) {
867            Main->mapped = true;
868            return 0; // succeded loading mapfile -> no need to load normal DB file
869        }
870        GB_informationf("ARB: %s => loading entire DB", map_fail_reason);
871    }
872
873    // load binary DB file
874
875    switch (version) {
876        case 2: // quick save file
877            for (i=1; i < Main->keycnt; i++) {
878                if (Main->keys[i].key) {
879                    Main->keys[i].nref_last_saved = Main->keys[i].nref;
880                }
881            }
882
883            if (Main->clock<=0) Main->clock++;
884            // fall-through
885        case 1: // master arb file
886            error = gb_read_bin_rek_V2(in, gbc, nodecnt, version, reversed, 0, progress);
887            break;
888        default:
889            GB_internal_errorf("Sorry: This ARB Version does not support database format V%li", version);
890            error = 1;
891    }
892
893    if (gb_local->search_system_folder) {
894        gb_search_system_folder(gbc);
895    }
896
897    switch (version) {
898        case 2:
899        case 1:
900            for (i=1; i < Main->keycnt; i++) {
901                if (Main->keys[i].key) {
902                    Main->keys[i].nref = Main->keys[i].nref_last_saved;
903                }
904            }
905            break;
906        default:
907            break;
908    }
909
910    return error;
911}
912
913// ----------------------
914//      OPEN DATABASE
915
916static long gb_next_main_idx_for_mapfile = 0;
917
918void GB_set_next_main_idx(long idx) {
919    gb_next_main_idx_for_mapfile = idx;
920}
921
922GB_MAIN_IDX gb_make_main_idx(GB_MAIN_TYPE *Main) {
923    static int initialized = 0;
924    GB_MAIN_IDX idx;
925
926    if (!initialized) {
927        for (idx=0; idx<GB_MAIN_ARRAY_SIZE; idx++) gb_main_array[idx] = NULL;
928        initialized = 1;
929    }
930    if (gb_next_main_idx_for_mapfile<=0) {
931        while (1) {                                 // search for unused array index
932            idx = (short)GB_random(GB_MAIN_ARRAY_SIZE);
933            if (gb_main_array[idx]==NULL) break;
934        }
935    }
936    else {
937        idx = (short)gb_next_main_idx_for_mapfile;
938        gb_next_main_idx_for_mapfile = 0;
939    }
940
941    gb_assert((idx%GB_MAIN_ARRAY_SIZE) == idx);
942
943    gb_main_array[idx] = Main;
944    return idx;
945}
946
947void GB_MAIN_TYPE::release_main_idx() { 
948    if (dummy_father) {
949        GB_MAIN_IDX idx = dummy_father->main_idx;
950        gb_assert(gb_main_array[idx] == this);
951        gb_main_array[idx] = NULL;
952    }
953}
954
955GB_ERROR GB_MAIN_TYPE::login_remote(const char *db_path, const char *opent) {
956    GB_ERROR error = NULL;
957
958    i_am_server = false;
959    c_link = gbcmc_open(db_path);
960    if (!c_link) {
961        error = GBS_global_string("There is no ARBDB server '%s', please start one or add a filename", db_path);
962    }
963    else {
964        root_container->server_id = 0;
965
966        remote_hash = GBS_create_numhash(GB_REMOTE_HASH_SIZE);
967        error       = initial_client_transaction();
968
969        if (!error) {
970            root_container->flags2.folded_container = 1;
971
972            if (strchr(opent, 't')) error      = gb_unfold(root_container, 0, -2);  // tiny
973            else if (strchr(opent, 'm')) error = gb_unfold(root_container, 1, -2);  // medium (no sequence)
974            else if (strchr(opent, 'b')) error = gb_unfold(root_container, 2, -2);  // big (no tree)
975            else if (strchr(opent, 'h')) error = gb_unfold(root_container, -1, -2); // huge (all)
976            else error                         = gb_unfold(root_container, 0, -2);  // tiny
977        }
978    }
979    return error;
980}
981
982inline bool is_binary_db_id(int id) {
983    return (id == 0x56430176)
984        || (id == GBTUM_MAGIC_NUMBER)
985        || (id == GBTUM_MAGIC_REVERSED);
986}
987inline bool has_ascii_db_id(uint32_t bin_id, FILE *in) {
988    // assumes the first 4 bytes of the input have been read (into 'bin_id').
989    // will read enough bytes to check for valid ascii-header.
990    // returns true if file has an arb-ascii-database-header.
991    const int ASC_HEADER_SIZE = 15;
992    char      buffer[ASC_HEADER_SIZE+1];
993
994    size_t read_bytes = fread(buffer+4, 1, ASC_HEADER_SIZE-4, in); // 4 bytes have already been read as binary ID
995    if (read_bytes == (ASC_HEADER_SIZE-4)) {
996        buffer[ASC_HEADER_SIZE] = 0;
997
998        const char *ascii_header = "/*ARBDB ASCII*/";
999        uint32_t   *ui_buffer    = (uint32_t*)buffer;
1000
1001        *ui_buffer = bin_id; // insert these 4 bytes
1002        if (strcmp(buffer, ascii_header) == 0) return true;
1003
1004        *ui_buffer = reverse_byteorder(bin_id); // insert them reversed
1005        if (strcmp(buffer, ascii_header) == 0) return true;
1006    }
1007    return false;
1008}
1009
1010static GB_ERROR init_tmp_branch(GBDATA *gb_main) {
1011    GB_ERROR  error   = NULL;
1012    GBDATA   *gb_tmp  = GB_search(gb_main, "tmp", GB_CREATE_CONTAINER);
1013    if (gb_tmp) {
1014        error = GB_set_temporary(gb_tmp);
1015    }
1016    else {
1017        error = GB_await_error();
1018    }
1019    return error;
1020}
1021
1022static GBDATA *GB_login(const char *cpath, const char *opent, const char *user) {
1023    /*! open an ARB database
1024     *
1025     * @param cpath arb database. May be
1026     * - full path of database. (loads DB plus newest quicksave, if any quicksaves exist)
1027     * - full path of a quicksave file (loads DB with specific quicksave)
1028     * - ":" connects to a running ARB DB server (e.g. ARB_NT, arb_db_server)
1029     * @param opent contains one or more of the following characters:
1030     * - 'r' read
1031     * - 'w' write (w/o 'r' it overwrites existing database)
1032     * - 'c' create (if not found)
1033     * - 's'     read only ???
1034     * - 'D' looks for default in $ARBHOME/lib/arb_default if file is not found in $ARB_PROP
1035     *       (only works combined with mode 'c')
1036     * - memory usage (only used for client-DB, i.e. if DB-name is ':'):
1037     *   - 't' small memory usage
1038     *   - 'm' medium
1039     *   - 'b' big
1040     *   - 'h' huge
1041     * - 'R' allow corrupt file recovery + opening quicks with no master
1042     * - 'N' assume new database format (does not check whether to convert old->new compression)
1043     * @param user username
1044     *
1045     * @return DB root node (or NULL, in which case an error has been exported)
1046     *
1047     * @see GB_open() and GBT_open()
1048     */
1049    GBCONTAINER   *gbc;
1050    GB_MAIN_TYPE  *Main;
1051    gb_open_types  opentype;
1052    GB_CSTR        quickFile           = NULL;
1053    int            ignoreMissingMaster = 0;
1054    int            loadedQuickIndex    = -1;
1055    GB_ERROR       error               = 0;
1056    char          *path                = ARB_strdup(cpath?cpath:"");
1057    bool           dbCreated           = false;
1058
1059    gb_assert(strchr(opent, 'd') == NULL); // mode 'd' is deprecated. You have to use 'D' and store your defaults inside ARBHOME/lib/arb_default
1060
1061    opentype = (!opent || strchr(opent, 'w')) ? gb_open_all : gb_open_read_only_all;
1062
1063    if (strchr(path, ':')) {
1064        ; // remote access
1065    }
1066    else if (GBS_string_matches(path, "*.quick?", GB_MIND_CASE)) {
1067        char *ext = gb_findExtension(path);
1068        gb_assert(ext!=0);
1069        if (isdigit(ext[6]))
1070        {
1071            loadedQuickIndex = atoi(ext+6);
1072            strcpy(ext, ".arb");
1073            quickFile = gb_oldQuicksaveName(path, loadedQuickIndex);
1074            if (strchr(opent, 'R'))     ignoreMissingMaster = 1;
1075        }
1076    }
1077    else if (GBS_string_matches(path, "*.a??", GB_MIND_CASE)) {
1078
1079        char *extension = gb_findExtension(path);
1080
1081        if (isdigit(extension[2]) && isdigit(extension[3]))
1082        {
1083            loadedQuickIndex = atoi(extension+2);
1084            strcpy(extension, ".arb");
1085            quickFile = gb_quicksaveName(path, loadedQuickIndex);
1086            if (strchr(opent, 'R'))     ignoreMissingMaster = 1;
1087        }
1088        else {
1089            char *base = ARB_strdup(path);
1090            char *ext = gb_findExtension(base);
1091            {
1092                gb_scandir dir;
1093                ext[0] = 0;
1094                gb_scan_directory(base, &dir);
1095
1096                loadedQuickIndex = dir.highest_quick_index;
1097
1098                if (dir.highest_quick_index!=dir.newest_quick_index)
1099                {
1100                    GB_warning("The QuickSave-File with the highest index-number\n"
1101                               "is not the NEWEST of your QuickSave-Files.\n"
1102                               "If you didn't restore old QuickSave-File from a backup\n"
1103                               "please inform your system-administrator - \n"
1104                               "this may be a serious bug and you may loose your data.");
1105                }
1106
1107                switch (dir.type)
1108                {
1109                    case GB_SCAN_NO_QUICK:
1110                        break;
1111                    case GB_SCAN_NEW_QUICK:
1112                        quickFile = gb_quicksaveName(path, dir.highest_quick_index);
1113                        break;
1114                    case GB_SCAN_OLD_QUICK:
1115                        quickFile = gb_oldQuicksaveName(path, dir.newest_quick_index);
1116
1117                        break;
1118                }
1119            }
1120
1121            free(base);
1122        }
1123    }
1124
1125    if (gb_verbose_mode) {
1126        GB_informationf("ARB: Loading '%s'%s%s", path, quickFile ? " + Changes-File " : "", quickFile ? quickFile : "");
1127    }
1128
1129    error = GB_install_pid(1);
1130    if (error) {
1131        GB_export_error(error);
1132        return 0;
1133    }
1134
1135    GB_init_gb();
1136
1137    Main = new GB_MAIN_TYPE(path);
1138    Main->mark_as_server();
1139
1140    if (strchr(opent, 'R')) Main->allow_corrupt_file_recovery = 1;
1141
1142    ASSERT_RESULT(long, 0, gb_create_key(Main, "main", false));
1143
1144    Main->dummy_father            = gb_make_container(NULL, NULL, -1, 0); // create "main"
1145    Main->dummy_father->main_idx  = gb_make_main_idx(Main);
1146    Main->dummy_father->server_id = GBTUM_MAGIC_NUMBER;
1147    gbc                           = gb_make_container(Main->dummy_father, NULL, -1, 0); // create "main"
1148
1149    Main->root_container = gbc;
1150
1151    error = gbcm_login(gbc, user);
1152    if (!error) {
1153        Main->opentype       = opentype;
1154        Main->security_level = 7;
1155
1156        if (path && (strchr(opent, 'r'))) {
1157            if (strchr(path, ':')) {
1158                error = Main->login_remote(path, opent);
1159            }
1160            else {
1161                int read_from_stdin = strcmp(path, "-") == 0;
1162
1163                GB_ULONG time_of_main_file = 0; long i;
1164
1165                Main->mark_as_server();
1166                GB_begin_transaction(gbc);
1167                Main->clock      = 0; // start clock
1168
1169                FILE *input = read_from_stdin ? stdin : ARB_zfopen(path, "rb", ZFILE_AUTODETECT, error, false);
1170                if (!input && ignoreMissingMaster) {
1171                    error = NULL; // @@@ maybe need to inspect error message here
1172                    goto load_quick_save_file_only;
1173                }
1174
1175                if (!input) {
1176                    if (strchr(opent, 'c')) {
1177                        error = NULL; // from ARB_zfopen
1178                        GB_disable_quicksave(gbc, "Database Created");
1179
1180                        if (strchr(opent, 'D')) { // use default settings
1181                            GB_clear_error(); // with default-files gb_scan_directory (used above) has created an error, cause the path was a fake path
1182                       
1183                            gb_assert(!ARB_strBeginsWith(path, ".arb_prop/")); // do no longer pass path-prefix [deprecated!] 
1184                            char *found_path = GB_property_file(false, path);
1185
1186                            if (!found_path) {
1187                                fprintf(stderr, "file %s not found\n", path);
1188                                dbCreated = true;
1189                            }
1190                            else {
1191                                freeset(path, found_path);
1192                                // cppcheck-suppress deallocuse (false positive; path is reassigned to non-NULL above)
1193                                input = fopen(path, "rb");
1194                            }
1195                        }
1196                        else {
1197                            dbCreated = true;
1198                        }
1199
1200                        if (dbCreated) {
1201                            fprintf(stderr, "Created new database \"%s\".\n", path);
1202                        }
1203                    }
1204                    else {
1205                        gb_assert(error); // from ARB_zfopen
1206                        error = GBS_global_string("Database '%s' not found (%s)", path, error);
1207                        gbc   = 0;
1208                    }
1209                }
1210                if (input) {
1211                    if (strchr(opent, 'D')) { // we are loading properties -> be verboose
1212                        fprintf(stderr, "Using properties from '%s'\n", path);
1213                    }
1214                    time_of_main_file = GB_time_of_file(path);
1215
1216                    i = gb_read_in_uint32(input, 0);
1217
1218                    if (is_binary_db_id(i)) {
1219                        {
1220                            arb_progress progress("Loading database", GB_size_of_FILE(input)/FILESIZE_GRANULARITY);
1221                            i = gb_read_bin(input, gbc, false, progress);                  // read or map whole db
1222                            progress.done();
1223                        }
1224                        gbc   = Main->root_container;
1225                        error = ARB_zfclose(input);
1226
1227                        if (i) {
1228                            if (Main->allow_corrupt_file_recovery) {
1229                                GB_print_error();
1230                                GB_clear_error();
1231                            }
1232                            else {
1233                                gbc   = 0;
1234                                error = GBS_global_string("Failed to load database '%s'\n"
1235                                                          "Reason: %s",
1236                                                          path,
1237                                                          GB_await_error());
1238                            }
1239                        }
1240
1241                        if (gbc && quickFile) {
1242                            long     err;
1243                            GB_ERROR err_msg;
1244                          load_quick_save_file_only :
1245                            err     = 0;
1246                            err_msg = 0;
1247
1248                            input = fopen(quickFile, "rb");
1249
1250                            if (input) {
1251                                GB_ULONG time_of_quick_file = GB_time_of_file(quickFile);
1252                                if (time_of_main_file && time_of_quick_file < time_of_main_file) {
1253                                    const char *warning = GBS_global_string("Your main database file '%s' is newer than\n"
1254                                                                            "   the changes file '%s'\n"
1255                                                                            "   That is very strange and happens only if files where\n"
1256                                                                            "   moved/copied by hand\n"
1257                                                                            "   Your file '%s' may be an old relict,\n"
1258                                                                            "   if you ran into problems now,delete it",
1259                                                                            path, quickFile, quickFile);
1260                                    GB_warning(warning);
1261                                }
1262                                i = gb_read_in_uint32(input, 0);
1263                                if (is_binary_db_id(i)) {
1264                                    {
1265                                        arb_progress progress("Loading quicksave", GB_size_of_FILE(input)/FILESIZE_GRANULARITY);
1266                                        err = gb_read_bin(input, gbc, true, progress);
1267                                        progress.done();
1268                                    }
1269                                    fclose (input);
1270
1271                                    if (err) {
1272                                        err_msg = GBS_global_string("Loading failed (file corrupt?)\n"
1273                                                                    "[Fail-Reason: '%s']",
1274                                                                    GB_await_error());
1275                                    }
1276                                }
1277                                else {
1278                                    err_msg = "Wrong file format (not a quicksave file)";
1279                                    err     = 1;
1280                                }
1281                            }
1282                            else {
1283                                err_msg = "Can't open file";
1284                                err     = 1;
1285                            }
1286
1287                            if (err) {
1288                                error = GBS_global_string("I cannot load your quick file '%s'\n"
1289                                                          "Reason: %s\n"
1290                                                          "\n"
1291                                                          "Note: you MAY restore an older version by running arb with:\n"
1292                                                          "      arb <name of quicksave-file>",
1293                                                          quickFile, err_msg);
1294
1295                                if (!Main->allow_corrupt_file_recovery) {
1296                                    gbc = 0;
1297                                }
1298                                else {
1299                                    GB_export_error(error);
1300                                    GB_print_error();
1301                                    GB_clear_error();
1302                                    error = 0;
1303                                    GB_disable_quicksave(gbc, "Couldn't load last quicksave (your latest changes are NOT included)");
1304                                }
1305                            }
1306                        }
1307                        Main->qs.last_index = loadedQuickIndex; // determines which # will be saved next
1308                    }
1309                    else {
1310                        if (has_ascii_db_id(i, input)) {
1311                            error = gb_read_ascii_beyond_header(input, path, gbc);
1312                            if (input != stdin) {
1313                                GB_ERROR close_error = ARB_zfclose(input);
1314                                if (!error) error    = close_error;
1315                            }
1316                            GB_disable_quicksave(gbc,
1317                                                 "Sorry, I cannot save differences to ascii files\n"
1318                                                 "  Save whole database in binary mode first");
1319                        }
1320                        else {
1321                            error = "input file is not an arb database file";
1322                        }
1323
1324                    }
1325                }
1326            }
1327        }
1328        else {
1329            GB_disable_quicksave(gbc, "Database not part of this process");
1330            Main->mark_as_server();
1331            GB_begin_transaction(gbc);
1332        }
1333
1334        if (error) gbcm_logout(Main, user);
1335    }
1336
1337    gb_assert(error || gbc);
1338
1339    if (error) {
1340        gb_delete_dummy_father(Main->dummy_father);
1341        gbc = NULL;
1342        delete Main;
1343
1344        GB_export_error(error);
1345    }
1346    else {
1347        GB_commit_transaction(gbc);
1348        {
1349            GB_begin_transaction(gbc); // New Transaction, should be quicksaveable
1350            if (!strchr(opent, 'N')) {               // new format
1351                gb_convert_V2_to_V3(gbc); // Compression conversion
1352            }
1353            error = gb_load_key_data_and_dictionaries(Main);
1354            if (!error) error = gb_resort_system_folder_to_top(Main->root_container);
1355            if (!error) error = init_tmp_branch(gbc);
1356
1357            GB_commit_transaction(gbc);
1358
1359            // "handle" error
1360            if (error) GBK_terminatef("PANIC in GB_login: %s", error);
1361        }
1362        Main->security_level = 0;
1363        gbl_install_standard_commands(gbc);
1364
1365        if (Main->is_server()) {
1366            GBT_install_message_handler(gbc);
1367        }
1368        if (gb_verbose_mode && !dbCreated) GB_informationf("ARB: Loading '%s' done\n", path);
1369    }
1370    free(path);
1371    return gbc;
1372}
1373
1374GBDATA *GB_open(const char *path, const char *opent)
1375{
1376    const char *user;
1377    user = GB_getenvUSER();
1378    return GB_login(path, opent, user);
1379}
1380
1381GB_ERROR GBT_check_arb_file(const char *name) { // goes to header: __ATTR__USERESULT
1382    /*! Checks whether a file is an arb file (or ':')
1383     *
1384     * @result NULL if it is an arb file
1385     */
1386
1387    GB_ERROR error = NULL;
1388    if (!strchr(name, ':'))  { // don't check remote DB
1389        if (GB_is_regularfile(name)) {
1390            FILE *in = ARB_zfopen(name, "rb", ZFILE_AUTODETECT, error, true); // suppress stderr (to hide "broken pipe" errors from decompressors)
1391            if (!in) {
1392                gb_assert(error);
1393                error = GBS_global_string("Cannot read file '%s' (Reason: %s)", name, error);
1394            }
1395            else {
1396                uint32_t i = gb_read_in_uint32(in, 0);
1397
1398                if (!is_binary_db_id(i)) {
1399                    if (!has_ascii_db_id(i, in)) {
1400                        error = GBS_global_string("'%s' is not an arb file", name);
1401                    }
1402                }
1403                ARB_zfclose(in); // Note: error ignored here (will report broken pipe from decompressor)
1404            }
1405        }
1406        else {
1407            error = GBS_global_string("'%s' is no file", name);
1408        }
1409    }
1410    return error;
1411}
1412
1413
1414// --------------------------------------------------------------------------------
1415
1416#ifdef UNIT_TESTS
1417
1418#include <test_unit.h>
1419
1420void TEST_io_number() {
1421    struct data {
1422        long  val;
1423        short size_expd;
1424    };
1425
1426    data DATA[] = {
1427        { 0x0,      1 },
1428        { 0x1,      1 },
1429        { 0x7f,     1 },
1430                   
1431        { 0x80,     2 },
1432        { 0x81,     2 },
1433        { 0xff,     2 },
1434        { 0x100,    2 },
1435        { 0x1234,   2 },
1436        { 0x3fff,   2 },
1437                   
1438        { 0x4000,   3 },
1439        { 0x4001,   3 },
1440        { 0xffff,   3 },
1441        { 0x1fffff, 3 },
1442
1443        { 0x200000, 4 },
1444        { 0x7fffff, 4 },
1445        { 0x800002, 4 },
1446        { 0xffffff, 4 },
1447        { 0xfffffff, 4 },
1448
1449#if defined(ARB_64)
1450        // the following entries are negative on 32bit systems; see ad_io_inline.h@bit-hell
1451        { 0x10000000, 5 },
1452        { 0x7fffffff, 5 },
1453        { 0x80000000, 5 },
1454        { 0x80808080, 5 },
1455        { 0xffffffff, 5 },
1456#endif
1457    };
1458
1459    const char *numbers   = "numbers.test";
1460    long        writeSize = 0;
1461    long        readSize  = 0;
1462
1463    {
1464        FILE *out = fopen(numbers, "wb");
1465        TEST_REJECT_NULL(out);
1466
1467        long lastPos = 0;
1468        for (size_t i = 0; i<ARRAY_ELEMS(DATA); ++i) {
1469            data& d = DATA[i];
1470            TEST_ANNOTATE(GBS_global_string("val=0x%lx", d.val));
1471            gb_put_number(d.val, out);
1472
1473            long pos           = ftell(out);
1474            long bytes_written = pos-lastPos;
1475            TEST_EXPECT_EQUAL(bytes_written, d.size_expd);
1476
1477            writeSize += bytes_written;
1478
1479            lastPos = pos;
1480        }
1481        TEST_ANNOTATE(NULL);
1482
1483        fclose(out);
1484    }
1485
1486    {
1487        FILE *in = fopen(numbers, "rb");
1488        TEST_REJECT_NULL(in);
1489
1490        long lastPos = 0;
1491
1492        for (size_t i = 0; i<ARRAY_ELEMS(DATA); ++i) {
1493            data& d = DATA[i];
1494            TEST_ANNOTATE(GBS_global_string("val=0x%lx", d.val));
1495
1496            long val = gb_get_number(in);
1497            TEST_EXPECT_EQUAL(val, d.val);
1498
1499            long pos        = ftell(in);
1500            long bytes_read = pos-lastPos;
1501            TEST_EXPECT_EQUAL(bytes_read, d.size_expd);
1502
1503            readSize += bytes_read;
1504
1505            lastPos = pos;
1506        }
1507        TEST_ANNOTATE(NULL);
1508
1509        fclose(in);
1510    }
1511
1512    TEST_EXPECT_EQUAL(GB_size_of_file(numbers), writeSize);
1513    TEST_EXPECT_EQUAL(writeSize, readSize);
1514
1515    TEST_EXPECT_ZERO_OR_SHOW_ERRNO(GB_unlink(numbers));
1516}
1517
1518void TEST_GBDATA_size() {
1519    // protect GBDATA/GBENTRY/GBCONTAINER against unwanted changes
1520    GBENTRY fakeEntry;
1521
1522#if defined(ARB_64)
1523
1524    TEST_EXPECT_EQUAL(sizeof(GBDATA), 40);
1525    TEST_EXPECT_EQUAL(sizeof(fakeEntry.info), 24);  // @@@ SIZOFINTERN may be increased (to use unused space); that change would need new mapfile version
1526    TEST_EXPECT_EQUAL(sizeof(fakeEntry.cache_index), 4);
1527    // 40+24+4 = 68 (where/what are the missing 4 bytes?; they seem to be at the end of the struct; maybe padding-bytes)
1528
1529    TEST_EXPECT_EQUAL(sizeof(GBENTRY), 72);
1530    TEST_EXPECT_EQUAL(sizeof(GBCONTAINER), 104);
1531
1532#else // !defined(ARB_64)
1533
1534    TEST_EXPECT_EQUAL(sizeof(GBDATA), 24);
1535    TEST_EXPECT_EQUAL(sizeof(fakeEntry.info), 12);
1536    TEST_EXPECT_EQUAL(sizeof(fakeEntry.cache_index), 4);
1537    // 24+12+4 = 40 (here nothing is missing)
1538
1539    TEST_EXPECT_EQUAL(sizeof(GBENTRY), 40);
1540    TEST_EXPECT_EQUAL(sizeof(GBCONTAINER), 60);
1541
1542#endif
1543}
1544TEST_PUBLISH(TEST_GBDATA_size);
1545
1546#endif // UNIT_TESTS
Note: See TracBrowser for help on using the repository browser.