source: tags/ms_r16q2/ARBDB/adsocket.cxx

Last change on this file was 14809, checked in by westram, 8 years ago
  • [14771] broke GB_xcmd: LD_LIBRARY_PATH was exported empty, causing dynamic link errors in external commands
    • affected arb_rnacma, SINA?, arb_primer, …
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.4 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : adsocket.cxx                                      //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include <unistd.h>
12
13#include <climits>
14#include <cstdarg>
15#include <cctype>
16
17#include <netdb.h>
18#include <netinet/tcp.h>
19#include <signal.h>
20#include <sys/mman.h>
21#include <sys/socket.h>
22#include <sys/stat.h>
23#include <sys/time.h>
24#include <sys/un.h>
25
26#if defined(DARWIN)
27# include <sys/sysctl.h>
28#endif // DARWIN
29
30#include <arb_cs.h>
31#include <arb_str.h>
32#include <arb_strbuf.h>
33#include <arb_file.h>
34#include <arb_sleep.h>
35#include <arb_pathlen.h>
36
37#include "gb_comm.h"
38#include "gb_data.h"
39#include "gb_localdata.h"
40
41#include <SigHandler.h>
42
43#include <algorithm>
44#include <arb_misc.h>
45#include <arb_defs.h>
46
47// ------------------------------------------------
48//      private read and write socket functions
49
50void gbcm_read_flush() {
51    gb_local->write_ptr  = gb_local->write_buffer;
52    gb_local->write_free = gb_local->write_bufsize;
53}
54
55static long gbcm_read_buffered(int socket, char *ptr, long size) {
56    /* write_ptr ptr to not read data
57       write_free   = write_bufsize-size of non read data;
58    */
59    long holding;
60    holding = gb_local->write_bufsize - gb_local->write_free;
61    if (holding <= 0) {
62        holding = read(socket, gb_local->write_buffer, (size_t)gb_local->write_bufsize);
63
64        if (holding < 0)
65        {
66            fprintf(stderr, "Cannot read data from client: len=%li (%s, errno %i)\n",
67                    holding, strerror(errno), errno);
68            return 0;
69        }
70        gbcm_read_flush();
71        gb_local->write_free-=holding;
72    }
73    if (size>holding) size = holding;
74    memcpy(ptr, gb_local->write_ptr, (int)size);
75    gb_local->write_ptr += size;
76    gb_local->write_free += size;
77    return size;
78}
79
80long gbcm_read(int socket, char *ptr, long size) {
81    long leftsize = size;
82    while (leftsize) {
83        long readsize = gbcm_read_buffered(socket, ptr, leftsize);
84        if (readsize<=0) return 0;
85        ptr += readsize;
86        leftsize -= readsize;
87    }
88
89    return size;
90}
91
92GBCM_ServerResult gbcm_write_flush(int socket) {
93    long     leftsize = gb_local->write_ptr - gb_local->write_buffer;
94    ssize_t  writesize;
95    char    *ptr      = gb_local->write_buffer;
96
97    // once we're done, the buffer will be free
98    gb_local->write_free = gb_local->write_bufsize;
99    gb_local->write_ptr = gb_local->write_buffer;
100   
101    while (leftsize) {
102#ifdef MSG_NOSIGNAL
103        // Linux has MSG_NOSIGNAL, but not SO_NOSIGPIPE
104        // prevent SIGPIPE here
105        writesize = send(socket, ptr, leftsize, MSG_NOSIGNAL);
106#else
107        writesize = write(socket, ptr, leftsize);
108#endif
109
110        if (writesize<0) {
111            if (gb_local->iamclient) {
112                fprintf(stderr, 
113                        "Client (pid=%i) terminating after failure to contact database (%s).",
114                        getpid(), strerror(errno));
115                exit(EXIT_SUCCESS);
116            }
117            else {
118                fprintf(stderr, "Error sending data to client (%s).", strerror(errno));
119                return GBCM_SERVER_FAULT;
120            }
121        }
122        ptr      += writesize;
123        leftsize -= writesize;
124    }
125
126    return GBCM_SERVER_OK;
127}
128
129GBCM_ServerResult gbcm_write(int socket, const char *ptr, long size) {
130    while (size >= gb_local->write_free) {
131        memcpy(gb_local->write_ptr, ptr, (int)gb_local->write_free);
132        gb_local->write_ptr += gb_local->write_free;
133        size -= gb_local->write_free;
134        ptr += gb_local->write_free;
135
136        gb_local->write_free = 0;
137        if (gbcm_write_flush(socket)) return GBCM_SERVER_FAULT;
138    }
139    memcpy(gb_local->write_ptr, ptr, (int)size);
140    gb_local->write_ptr += size;
141    gb_local->write_free -= size;
142    return GBCM_SERVER_OK;
143}
144
145GB_ERROR gbcm_open_socket(const char *path, bool do_connect, int *psocket, char **unix_name) {
146    if (path && strcmp(path, ":") == 0) {
147        path = GBS_read_arb_tcp("ARB_DB_SERVER");
148        if (!path) {
149            return GB_await_error();
150        }
151    }
152
153    return arb_open_socket(path, do_connect, psocket, unix_name);
154}
155
156#if defined(WARN_TODO)
157#warning gbcms_close is unused
158#endif
159long gbcms_close(gbcmc_comm *link) {
160    if (link->socket) {
161        close(link->socket);
162        link->socket = 0;
163        if (link->unix_name) {
164            unlink(link->unix_name);
165        }
166    }
167    return 0;
168}
169
170gbcmc_comm *gbcmc_open(const char *path) {
171    gbcmc_comm *link = (gbcmc_comm *)GB_calloc(sizeof(gbcmc_comm), 1);
172    GB_ERROR    err  = gbcm_open_socket(path, true, &link->socket, &link->unix_name);
173
174    if (err) {
175        if (link->unix_name) free(link->unix_name); // @@@
176        free(link);
177        if (*err) {
178            GB_internal_errorf("ARB_DB_CLIENT_OPEN\n(Reason: %s)", err);
179        }
180        return 0;
181    }
182    gb_local->iamclient = true;
183    return link;
184}
185
186long gbcm_write_two(int socket, long a, long c) {
187    long    ia[3];
188    ia[0] = a;
189    ia[1] = 3;
190    ia[2] = c;
191    if (!socket) return 1;
192    return  gbcm_write(socket, (const char *)ia, sizeof(long)*3);
193}
194
195
196GBCM_ServerResult gbcm_read_two(int socket, long a, long *b, long *c) {
197    /*! read two values: length and any user long
198     *
199     *  if data is send by gbcm_write_two() then @param b should be zero
200     *  and is not used!
201     */
202
203    long    ia[3];
204    long    size;
205    size = gbcm_read(socket, (char *)&(ia[0]), sizeof(long)*3);
206    if (size != sizeof(long) * 3) {
207        GB_internal_errorf("receive failed: %zu bytes expected, %li got, keyword %lX",
208                           sizeof(long) * 3, size, a);
209        return GBCM_SERVER_FAULT;
210    }
211    if (ia[0] != a) {
212        GB_internal_errorf("received keyword failed %lx != %lx\n", ia[0], a);
213        return GBCM_SERVER_FAULT;
214    }
215    if (b) {
216        *b = ia[1];
217    }
218    else {
219        if (ia[1]!=3) {
220            GB_internal_error("receive failed: size not 3\n");
221            return GBCM_SERVER_FAULT;
222        }
223    }
224    *c = ia[2];
225    return GBCM_SERVER_OK;
226}
227
228GBCM_ServerResult gbcm_write_string(int socket, const char *key) {
229    if (key) {
230        size_t len = strlen(key);
231        gbcm_write_long(socket, len);
232        if (len) gbcm_write(socket, key, len);
233    }
234    else {
235        gbcm_write_long(socket, -1);
236    }
237    return GBCM_SERVER_OK;
238}
239
240char *gbcm_read_string(int socket)
241{
242    char *key;
243    long  len = gbcm_read_long(socket);
244
245    if (len) {
246        if (len>0) {
247            key = (char *)GB_calloc(sizeof(char), (size_t)len+1);
248            gbcm_read(socket, key, len);
249        }
250        else {
251            key = 0;
252        }
253    }
254    else {
255        key = strdup("");
256    }
257
258    return key;
259}
260
261GBCM_ServerResult gbcm_write_long(int socket, long data) {
262    gbcm_write(socket, (char*)&data, sizeof(data));
263    return GBCM_SERVER_OK;
264}
265
266long gbcm_read_long(int socket) {
267    long data;
268    gbcm_read(socket, (char*)&data, sizeof(data));
269    return data;
270}
271
272char *GB_read_fp(FILE *in) {
273    /*! like GB_read_file(), but works on already open file
274     * (useful together with GB_fopen_tempfile())
275     *
276     * Note: File should be opened in text-mode (e.g. "rt")
277     */
278
279    GBS_strstruct *buf = GBS_stropen(4096);
280    int            c;
281
282    while (EOF != (c = getc(in))) {
283        GBS_chrcat(buf, c);
284    }
285    return GBS_strclose(buf);
286}
287
288char *GB_read_file(const char *path) { // consider using class FileContent instead
289    /*! read content of file 'path' into string (heap-copy)
290     *
291     * if path is '-', read from STDIN
292     *
293     * @return NULL in case of error (use GB_await_error() to get the message)
294     */
295    char *result = 0;
296
297    if (strcmp(path, "-") == 0) {
298        result = GB_read_fp(stdin);
299    }
300    else {
301        char *epath = GBS_eval_env(path);
302
303        if (epath) {
304            FILE *in = fopen(epath, "rt");
305
306            if (!in) GB_export_error(GB_IO_error("reading", epath));
307            else {
308                long data_size = GB_size_of_file(epath);
309
310                if (data_size >= 0) {
311                    result = (char*)malloc(data_size+1);
312
313                    data_size         = fread(result, 1, data_size, in);
314                    result[data_size] = 0;
315                }
316                fclose(in);
317            }
318        }
319        free(epath);
320    }
321    return result;
322}
323
324char *GB_map_FILE(FILE *in, int writeable) {
325    int fi = fileno(in);
326    size_t size = GB_size_of_FILE(in);
327    char *buffer;
328    if (size<=0) {
329        GB_export_error("GB_map_file: sorry file not found");
330        return NULL;
331    }
332    if (writeable) {
333        buffer = (char*)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fi, 0);
334    }
335    else {
336        buffer = (char*)mmap(NULL, size, PROT_READ, MAP_SHARED, fi, 0);
337    }
338    if (buffer == MAP_FAILED) {
339        GB_export_errorf("GB_map_file: Error: Out of Memory: mmap failed (errno: %i)", errno);
340        return NULL;
341    }
342    return buffer;
343}
344
345char *GB_map_file(const char *path, int writeable) {
346    FILE *in;
347    char *buffer;
348    in = fopen(path, "r");
349    if (!in) {
350        GB_export_errorf("GB_map_file: sorry file '%s' not readable", path);
351        return NULL;
352    }
353    buffer = GB_map_FILE(in, writeable);
354    fclose(in);
355    return buffer;
356}
357
358GB_ULONG GB_time_of_day() {
359    timeval tp;
360    if (gettimeofday(&tp, 0)) return 0;
361    return tp.tv_sec;
362}
363
364GB_ERROR GB_textprint(const char *path) {
365    // goes to header: __ATTR__USERESULT
366    char       *fpath        = GBS_eval_env(path);
367    char       *quoted_fpath = GBK_singlequote(fpath);
368    const char *command      = GBS_global_string("arb_textprint %s &", quoted_fpath);
369    GB_ERROR    error        = GBK_system(command);
370    error                    = GB_failedTo_error("print textfile", fpath, error);
371    free(quoted_fpath);
372    free(fpath);
373    return error;
374}
375
376// --------------------------------------------------------------------------------
377
378static GB_CSTR GB_getenvPATH() {
379    static const char *path = 0;
380    if (!path) {
381        path = ARB_getenv_ignore_empty("PATH");
382        if (!path) {
383            path = GBS_eval_env("/bin:/usr/bin:$(ARBHOME)/bin");
384            GB_informationf("Your PATH variable is empty - using '%s' as search path.", path);
385        }
386        else {
387            char *arbbin = GBS_eval_env("$(ARBHOME)/bin");
388            if (strstr(path, arbbin) == 0) {
389                GB_warningf("Your PATH variable does not contain '%s'. Things may not work as expected.", arbbin);
390            }
391            free(arbbin);
392        }
393    }
394    return path;
395}
396
397// --------------------------------------------------------------------------------
398// Functions to find an executable
399
400static char *GB_find_executable(GB_CSTR description_of_executable, ...) {
401    // goes to header: __ATTR__SENTINEL
402    /* search the path for an executable with any of the given names (...)
403     * if any is found, it's full path is returned
404     * if none is found, a warning call is returned (which can be executed without harm)
405    */
406
407    GB_CSTR  name;
408    char    *found = 0;
409    va_list  args;
410
411    va_start(args, description_of_executable);
412    while (!found && (name = va_arg(args, GB_CSTR)) != 0) found = ARB_executable(name, GB_getenvPATH());
413    va_end(args);
414
415    if (!found) { // none of the executables has been found
416        char *looked_for;
417        char *msg;
418        {
419            GBS_strstruct *buf   = GBS_stropen(100);
420            int            first = 1;
421
422            va_start(args, description_of_executable);
423            while ((name = va_arg(args, GB_CSTR)) != 0) {
424                if (!first) GBS_strcat(buf, ", ");
425                first = 0;
426                GBS_strcat(buf, name);
427            }
428            va_end(args);
429            looked_for = GBS_strclose(buf);
430        }
431
432        msg   = GBS_global_string_copy("Could not find a %s (looked for: %s)", description_of_executable, looked_for);
433        GB_warning(msg);
434        found = GBS_global_string_copy("echo \"%s\" ; arb_ign Parameters", msg);
435        free(msg);
436        free(looked_for);
437    }
438    else {
439        GB_informationf("Using %s '%s' ('%s')", description_of_executable, name, found);
440    }
441    return found;
442}
443
444// --------------------------------------------------------------------------------
445// Functions to access the environment variables used by ARB:
446
447static char *getenv_executable(GB_CSTR envvar) {
448    // get full path of executable defined by 'envvar'
449    // returns 0 if
450    //  - envvar not defined or
451    //  - not defining an executable (warns about that)
452
453    char       *result   = 0;
454    const char *exe_name = ARB_getenv_ignore_empty(envvar);
455
456    if (exe_name) {
457        result = ARB_executable(exe_name, GB_getenvPATH());
458        if (!result) {
459            GB_warningf("Environment variable '%s' contains '%s' (which is not an executable)", envvar, exe_name);
460        }
461    }
462
463    return result;
464}
465
466static char *getenv_existing_directory(GB_CSTR envvar) {
467    // get full path of directory defined by 'envvar'
468    // return 0 if
469    // - envvar is not defined or
470    // - does not point to a directory (warns about that)
471
472    char       *result   = 0;
473    const char *dir_name = ARB_getenv_ignore_empty(envvar);
474
475    if (dir_name) {
476        if (GB_is_directory(dir_name)) {
477            result = strdup(dir_name);
478        }
479        else {
480            GB_warningf("Environment variable '%s' should contain the path of an existing directory.\n"
481                        "(current content '%s' has been ignored.)", envvar, dir_name);
482        }
483    }
484    return result;
485}
486
487static void GB_setenv(const char *var, const char *value) {
488    if (setenv(var, value, 1) != 0) {
489        GB_warningf("Could not set environment variable '%s'. This might cause problems in subprocesses.\n"
490                    "(Reason: %s)", var, strerror(errno));
491    }
492}
493
494static GB_CSTR GB_getenvARB_XTERM() {
495    static const char *xterm = 0;
496    if (!xterm) {
497        xterm = ARB_getenv_ignore_empty("ARB_XTERM"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARB_XTERM
498        if (!xterm) xterm = "xterm -sl 1000 -sb -geometry 150x60";
499    }
500    return xterm;
501}
502
503static GB_CSTR GB_getenvARB_XCMD() {
504    static const char *xcmd = 0;
505    if (!xcmd) {
506        xcmd = ARB_getenv_ignore_empty("ARB_XCMD"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARB_XCMD
507        if (!xcmd) {
508            const char *xterm = GB_getenvARB_XTERM();
509            gb_assert(xterm);
510            xcmd = GBS_global_string_copy("%s -e", xterm);
511        }
512    }
513    return xcmd;
514}
515
516GB_CSTR GB_getenvUSER() {
517    static const char *user = 0;
518    if (!user) {
519        user = ARB_getenv_ignore_empty("USER");
520        if (!user) user = ARB_getenv_ignore_empty("LOGNAME");
521        if (!user) {
522            user = ARB_getenv_ignore_empty("HOME");
523            if (user && strrchr(user, '/')) user = strrchr(user, '/')+1;
524        }
525        if (!user) {
526            fprintf(stderr, "WARNING: Cannot identify user: environment variables USER, LOGNAME and HOME not set\n");
527            user = "UnknownUser";
528        }
529    }
530    return user;
531}
532
533
534static GB_CSTR GB_getenvHOME() {
535    static SmartCharPtr Home;
536    if (Home.isNull()) {
537        char *home = getenv_existing_directory("HOME");
538        if (!home) {
539            home = nulldup(GB_getcwd());
540            if (!home) home = strdup(".");
541            fprintf(stderr, "WARNING: Cannot identify user's home directory: environment variable HOME not set\n"
542                    "Using current directory (%s) as home.\n", home);
543        }
544        gb_assert(home);
545        Home = home;
546    }
547    return &*Home;
548}
549
550GB_CSTR GB_getenvARBHOME() {
551    static SmartCharPtr Arbhome;
552    if (Arbhome.isNull()) {
553        char *arbhome = getenv_existing_directory("ARBHOME"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARBHOME
554        if (!arbhome) {
555            fprintf(stderr, "Fatal ERROR: Environment Variable ARBHOME not found !!!\n"
556                    "   Please set 'ARBHOME' to the installation path of ARB\n");
557            exit(EXIT_FAILURE);
558        }
559        Arbhome = arbhome;
560    }
561    return &*Arbhome;
562}
563
564GB_CSTR GB_getenvARBMACRO() {
565    static const char *am = 0;
566    if (!am) {
567        am          = getenv_existing_directory("ARBMACRO"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARBMACRO
568        if (!am) am = strdup(GB_path_in_ARBLIB("macros"));
569    }
570    return am;
571}
572
573static char *getenv_autodirectory(const char *envvar, const char *defaultDirectory) {
574    // if environment variable 'envvar' contains an existing directory -> use that
575    // otherwise fallback to 'defaultDirectory' (create if not existing)
576    // return heap-copy of full directory name
577    char *dir = getenv_existing_directory(envvar);
578    if (!dir) {
579        dir = GBS_eval_env(defaultDirectory);
580        if (!GB_is_directory(dir)) {
581            GB_ERROR error = GB_create_directory(dir);
582            if (error) GB_warning(error);
583        }
584    }
585    return dir;
586}
587
588GB_CSTR GB_getenvARB_PROP() {
589    static SmartCharPtr ArbProps;
590    if (ArbProps.isNull()) ArbProps = getenv_autodirectory("ARB_PROP", GB_path_in_HOME(".arb_prop")); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARB_PROP
591    return &*ArbProps;
592}
593
594GB_CSTR GB_getenvARBMACROHOME() {
595    static SmartCharPtr ArbMacroHome;
596    if (ArbMacroHome.isNull()) ArbMacroHome = getenv_autodirectory("ARBMACROHOME", GB_path_in_arbprop("macros"));  // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARBMACROHOME
597    return &*ArbMacroHome;
598}
599
600GB_CSTR GB_getenvARBCONFIG() {
601    static SmartCharPtr ArbConfig;
602    if (ArbConfig.isNull()) ArbConfig = getenv_autodirectory("ARBCONFIG", GB_path_in_arbprop("cfgSave")); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARBCONFIG
603    return &*ArbConfig;
604}
605
606GB_CSTR GB_getenvARB_GS() {
607    static const char *gs = 0;
608    if (!gs) {
609        gs = getenv_executable("ARB_GS"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARB_GS
610        if (!gs) gs = GB_find_executable("Postscript viewer", "gv", "ghostview", NULL);
611    }
612    return gs;
613}
614
615GB_CSTR GB_getenvARB_PDFVIEW() {
616    static const char *pdfview = 0;
617    if (!pdfview) {
618        pdfview = getenv_executable("ARB_PDFVIEW"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARB_PDFVIEW
619        if (!pdfview) pdfview = GB_find_executable("PDF viewer", "epdfview", "xpdf", "kpdf", "acroread", "gv", NULL);
620    }
621    return pdfview;
622}
623
624GB_CSTR GB_getenvARB_TEXTEDIT() {
625    static const char *editor = 0;
626    if (!editor) {
627        editor = getenv_executable("ARB_TEXTEDIT"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARB_TEXTEDIT
628        if (!editor) editor = "arb_textedit"; // a smart editor shell script
629    }
630    return editor;
631}
632
633GB_CSTR GB_getenvDOCPATH() {
634    static const char *dp = 0;
635    if (!dp) {
636        char *res = getenv_existing_directory("ARB_DOC"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARB_DOC
637        if (res) dp = res;
638        else     dp = strdup(GB_path_in_ARBLIB("help"));
639    }
640    return dp;
641}
642
643GB_CSTR GB_getenvHTMLDOCPATH() {
644    static const char *dp = 0;
645    if (!dp) {
646        char *res = getenv_existing_directory("ARB_HTMLDOC"); // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp@ARB_HTMLDOC
647        if (res) dp = res;
648        else     dp = strdup(GB_path_in_ARBLIB("help_html"));
649    }
650    return dp;
651
652}
653
654static gb_getenv_hook getenv_hook = NULL;
655
656NOT4PERL gb_getenv_hook GB_install_getenv_hook(gb_getenv_hook hook) {
657    // Install 'hook' to be called by GB_getenv().
658    // If the 'hook' returns NULL, normal expansion takes place.
659    // Otherwise GB_getenv() returns result from 'hook'
660
661    gb_getenv_hook oldHook = getenv_hook;
662    getenv_hook            = hook;
663    return oldHook;
664}
665
666GB_CSTR GB_getenv(const char *env) {
667    if (getenv_hook) {
668        const char *result = getenv_hook(env);
669        if (result) return result;
670    }
671    if (strncmp(env, "ARB", 3) == 0) {
672        // doc in ../HELP_SOURCE/oldhelp/arb_envar.hlp
673
674        if (strcmp(env, "ARBHOME")      == 0) return GB_getenvARBHOME();
675        if (strcmp(env, "ARB_PROP")     == 0) return GB_getenvARB_PROP();
676        if (strcmp(env, "ARBCONFIG")    == 0) return GB_getenvARBCONFIG();
677        if (strcmp(env, "ARBMACROHOME") == 0) return GB_getenvARBMACROHOME();
678        if (strcmp(env, "ARBMACRO")     == 0) return GB_getenvARBMACRO();
679
680        if (strcmp(env, "ARB_GS")       == 0) return GB_getenvARB_GS();
681        if (strcmp(env, "ARB_PDFVIEW")  == 0) return GB_getenvARB_PDFVIEW();
682        if (strcmp(env, "ARB_DOC")      == 0) return GB_getenvDOCPATH();
683        if (strcmp(env, "ARB_TEXTEDIT") == 0) return GB_getenvARB_TEXTEDIT();
684        if (strcmp(env, "ARB_XTERM")    == 0) return GB_getenvARB_XTERM();
685        if (strcmp(env, "ARB_XCMD")     == 0) return GB_getenvARB_XCMD();
686    }
687    else {
688        if (strcmp(env, "HOME") == 0) return GB_getenvHOME();
689        if (strcmp(env, "USER") == 0) return GB_getenvUSER();
690    }
691
692    return ARB_getenv_ignore_empty(env);
693}
694
695struct export_environment {
696    export_environment() {
697        // set all variables needed in ARB subprocesses
698        GB_setenv("ARB_XCMD", GB_getenvARB_XCMD());
699    }
700};
701
702static export_environment expenv;
703
704bool GB_host_is_local(const char *hostname) {
705    // returns true if host is local
706
707    arb_assert(hostname);
708    arb_assert(hostname[0]);
709
710    return
711        ARB_stricmp(hostname, "localhost")       == 0 ||
712        ARB_strBeginsWith(hostname, "127.0.0.")       ||
713        ARB_stricmp(hostname, arb_gethostname()) == 0;
714}
715
716static GB_ULONG get_physical_memory() {
717    // Returns the physical available memory size in k available for one process
718    static GB_ULONG physical_memsize = 0;
719    if (!physical_memsize) {
720        GB_ULONG memsize; // real existing memory in k
721#if defined(LINUX)
722        {
723            long pagesize = sysconf(_SC_PAGESIZE);
724            long pages    = sysconf(_SC_PHYS_PAGES);
725
726            memsize = (pagesize/1024) * pages;
727        }
728#elif defined(DARWIN)
729#warning memsize detection needs to be tested for Darwin
730        {
731            int      mib[2];
732            uint64_t bytes;
733            size_t   len;
734
735            mib[0] = CTL_HW;
736            mib[1] = HW_MEMSIZE; // uint64_t: physical ram size
737            len = sizeof(bytes);
738            sysctl(mib, 2, &bytes, &len, NULL, 0);
739
740            memsize = bytes/1024;
741        }
742#else
743        memsize = 1024*1024; // assume 1 Gb
744        printf("\n"
745               "Warning: ARB is not prepared to detect the memory size on your system!\n"
746               "         (it assumes you have %ul Mb,  but does not use more)\n\n", memsize/1024);
747#endif
748
749        GB_ULONG net_memsize = memsize - 10240;         // reduce by 10Mb
750
751        // detect max allocateable memory by ... allocating
752        GB_ULONG max_malloc_try = net_memsize*1024;
753        GB_ULONG max_malloc     = 0;
754        {
755            GB_ULONG step_size  = 4096;
756            void *head = 0;
757
758            do {
759                void **tmp;
760                while ((tmp=(void**)malloc(step_size))) {
761                    *tmp        = head;
762                    head        = tmp;
763                    max_malloc += step_size;
764                    if (max_malloc >= max_malloc_try) break;
765                    step_size *= 2;
766                }
767            } while ((step_size=step_size/2) > sizeof(void*));
768
769            while (head) freeset(head, *(void**)head);
770            max_malloc /= 1024;
771        }
772
773        physical_memsize = std::min(net_memsize, max_malloc);
774
775#if defined(DEBUG) && 0
776        printf("- memsize(real)        = %20lu k\n", memsize);
777        printf("- memsize(net)         = %20lu k\n", net_memsize);
778        printf("- memsize(max_malloc)  = %20lu k\n", max_malloc);
779#endif // DEBUG
780
781        GB_informationf("Visible memory: %s", GBS_readable_size(physical_memsize*1024, "b"));
782    }
783
784    arb_assert(physical_memsize>0);
785    return physical_memsize;
786}
787
788static GB_ULONG parse_env_mem_definition(const char *env_override, GB_ERROR& error) {
789    const char *end;
790    GB_ULONG    num = strtoul(env_override, const_cast<char**>(&end), 10);
791
792    error = NULL;
793
794    bool valid = num>0 || env_override[0] == '0';
795    if (valid) {
796        const char *formatSpec = end;
797        double      factor     = 1;
798
799        switch (tolower(formatSpec[0])) {
800            case 0:
801                num = GB_ULONG(num/1024.0+0.5); // byte->kb
802                break; // no format given
803
804            case 'g': factor *= 1024;
805            case 'm': factor *= 1024;
806            case 'k': break;
807
808            case '%':
809                factor = num/100.0;
810                num    = get_physical_memory();
811                break;
812
813            default: valid = false; break;
814        }
815
816        if (valid) return GB_ULONG(num*factor+0.5);
817    }
818
819    error = "expected digits (optionally followed by k, M, G or %)";
820    return 0;
821}
822
823GB_ULONG GB_get_usable_memory() {
824    // memory allowed to be used by a single ARB process (in kbyte)
825
826    static GB_ULONG useable_memory = 0;
827    if (!useable_memory) {
828        bool        allow_fallback = true;
829        const char *env_override   = GB_getenv("ARB_MEMORY");
830        const char *via_whom;
831        if (env_override) {
832            via_whom = "via envar ARB_MEMORY";
833        }
834        else {
835          FALLBACK:
836            env_override   = "90%"; // ARB processes do not use more than 90% of physical memory
837            via_whom       = "by internal default";
838            allow_fallback = false;
839        }
840
841        gb_assert(env_override);
842
843        GB_ERROR env_error;
844        GB_ULONG env_memory = parse_env_mem_definition(env_override, env_error);
845        if (env_error) {
846            GB_warningf("Ignoring invalid setting '%s' %s (%s)", env_override, via_whom, env_error);
847            if (allow_fallback) goto FALLBACK;
848            GBK_terminate("failed to detect usable memory");
849        }
850
851        GB_informationf("Restricting used memory (%s '%s') to %s", via_whom, env_override, GBS_readable_size(env_memory*1024, "b"));
852        if (!allow_fallback) {
853            GB_informationf("Note: Setting envar ARB_MEMORY will override that restriction (percentage or absolute memsize)");
854        }
855        useable_memory = env_memory;
856        gb_assert(useable_memory>0 && useable_memory<get_physical_memory());
857    }
858    return useable_memory;
859}
860
861// ---------------------------
862//      external commands
863
864GB_ERROR GB_xterm() {
865    // goes to header: __ATTR__USERESULT
866    const char *xt      = GB_getenvARB_XTERM();
867    const char *command = GBS_global_string("%s &", xt);
868    return GBK_system(command);
869}
870
871GB_ERROR GB_xcmd(const char *cmd, bool background, bool wait_only_if_error) {
872    // goes to header: __ATTR__USERESULT_TODO
873
874    // runs a command in an xterm
875    // if 'background' is true -> run asynchronous
876    // if 'wait_only_if_error' is true -> asynchronous does wait for keypress only if cmd fails
877
878    const int     BUFSIZE = 1024;
879    GBS_strstruct system_call(BUFSIZE);
880
881    const char *xcmd = GB_getenvARB_XCMD();
882
883    system_call.put('(');
884    system_call.cat(xcmd);
885
886    {
887        GBS_strstruct bash_command(BUFSIZE);
888
889        bash_command.cat("LD_LIBRARY_PATH=");
890        {
891            char *dquoted_library_path = GBK_doublequote(GB_getenv("LD_LIBRARY_PATH"));
892            bash_command.cat(dquoted_library_path);
893            free(dquoted_library_path);
894        }
895        bash_command.cat(";export LD_LIBRARY_PATH; (");
896        bash_command.cat(cmd);
897
898        const char *wait_commands = "echo; echo Press ENTER to close this window; read a";
899        if (wait_only_if_error) {
900            bash_command.cat(") || (");
901            bash_command.cat(wait_commands);
902        }
903        else if (background) {
904            bash_command.cat("; ");
905            bash_command.cat(wait_commands);
906        }
907        bash_command.put(')');
908
909        system_call.cat(" bash -c ");
910        char *squoted_bash_command = GBK_singlequote(bash_command.get_data());
911        system_call.cat(squoted_bash_command);
912        free(squoted_bash_command);
913    }
914    system_call.cat(" )");
915    if (background) system_call.cat(" &");
916
917    return GBK_system(system_call.get_data());
918}
919
920// ---------------------------------------------
921// path completion (parts former located in AWT)
922// @@@ whole section (+ corresponding tests) should move to adfile.cxx
923
924static int  path_toggle = 0;
925static char path_buf[2][ARB_PATH_MAX];
926
927static char *use_other_path_buf() {
928    path_toggle = 1-path_toggle;
929    return path_buf[path_toggle];
930}
931
932GB_CSTR GB_append_suffix(const char *name, const char *suffix) {
933    // if suffix != NULL -> append .suffix
934    // (automatically removes duplicated '.'s)
935
936    GB_CSTR result = name;
937    if (suffix) {
938        while (suffix[0] == '.') suffix++;
939        if (suffix[0]) {
940            result = GBS_global_string_to_buffer(use_other_path_buf(), ARB_PATH_MAX, "%s.%s", name, suffix);
941        }
942    }
943    return result;
944}
945
946GB_CSTR GB_canonical_path(const char *anypath) {
947    // expands '~' '..' symbolic links etc in 'anypath'.
948    //
949    // Never returns NULL (if called correctly)
950    // Instead might return non-canonical path (when a directory
951    // in 'anypath' does not exist)
952
953    GB_CSTR result = NULL;
954    if (!anypath) {
955        GB_export_error("NULL path (internal error)");
956    }
957    else if (!anypath[0]) {
958        result = "/";
959    }
960    else if (strlen(anypath) >= ARB_PATH_MAX) {
961        GB_export_errorf("Path too long (> %i chars)", ARB_PATH_MAX-1);
962    }
963    else {
964        if (anypath[0] == '~' && (!anypath[1] || anypath[1] == '/')) {
965            GB_CSTR home    = GB_getenvHOME();
966            GB_CSTR homeexp = GBS_global_string("%s%s", home, anypath+1);
967            result          = GB_canonical_path(homeexp);
968            GBS_reuse_buffer(homeexp);
969        }
970        else {
971            result = realpath(anypath, path_buf[1-path_toggle]);
972            if (result) {
973                path_toggle = 1-path_toggle;
974            }
975            else { // realpath failed (happens e.g. when using a non-existing path, e.g. if user entered the name of a new file)
976                   // => content of path_buf[path_toggle] is UNDEFINED!
977                char *dir, *fullname;
978                GB_split_full_path(anypath, &dir, &fullname, NULL, NULL);
979
980                const char *canonical_dir = NULL;
981                if (!dir) {
982                    gb_assert(!strchr(anypath, '/'));
983                    canonical_dir = GB_canonical_path("."); // use working directory
984                }
985                else {
986                    gb_assert(strcmp(dir, anypath) != 0); // avoid deadlock
987                    canonical_dir = GB_canonical_path(dir);
988                }
989                gb_assert(canonical_dir);
990
991                // manually resolve '.' and '..' in non-existing parent directories
992                if (strcmp(fullname, "..") == 0) {
993                    char *parent;
994                    GB_split_full_path(canonical_dir, &parent, NULL, NULL, NULL);
995                    if (parent) {
996                        result = strcpy(use_other_path_buf(), parent);
997                        free(parent);
998                    }
999                }
1000                else if (strcmp(fullname, ".") == 0) {
1001                    result = canonical_dir;
1002                }
1003
1004                if (!result) result = GB_concat_path(canonical_dir, fullname);
1005
1006                free(dir);
1007                free(fullname);
1008            }
1009        }
1010        gb_assert(result);
1011    }
1012    return result;
1013}
1014
1015GB_CSTR GB_concat_path(GB_CSTR anypath_left, GB_CSTR anypath_right) {
1016    // concats left and right part of a path.
1017    // '/' is inserted in-between
1018    //
1019    // if one of the arguments is NULL => returns the other argument
1020    // if both arguments are NULL      => return NULL (@@@ maybe forbid?)
1021
1022    GB_CSTR result = NULL;
1023
1024    if (anypath_right) {
1025        if (anypath_right[0] == '/') {
1026            result = GB_concat_path(anypath_left, anypath_right+1);
1027        }
1028        else if (anypath_left && anypath_left[0]) {
1029            if (anypath_left[strlen(anypath_left)-1] == '/') {
1030                result = GBS_global_string_to_buffer(use_other_path_buf(), sizeof(path_buf[0]), "%s%s", anypath_left, anypath_right);
1031            }
1032            else {
1033                result = GBS_global_string_to_buffer(use_other_path_buf(), sizeof(path_buf[0]), "%s/%s", anypath_left, anypath_right);
1034            }
1035        }
1036        else {
1037            result = anypath_right;
1038        }
1039    }
1040    else {
1041        result = anypath_left;
1042    }
1043
1044    return result;
1045}
1046
1047GB_CSTR GB_concat_full_path(const char *anypath_left, const char *anypath_right) {
1048    // like GB_concat_path(), but returns the canonical path
1049    GB_CSTR result = GB_concat_path(anypath_left, anypath_right);
1050
1051    gb_assert(result != anypath_left); // consider using GB_canonical_path() directly
1052    gb_assert(result != anypath_right);
1053
1054    if (result) result = GB_canonical_path(result);
1055    return result;
1056}
1057
1058inline bool is_absolute_path(const char *path) { return path[0] == '/' || path[0] == '~'; }
1059inline bool is_name_of_envvar(const char *name) {
1060    for (int i = 0; name[i]; ++i) {
1061        if (isalnum(name[i]) || name[i] == '_') continue;
1062        return false;
1063    }
1064    return true;
1065}
1066
1067GB_CSTR GB_unfold_in_directory(const char *relative_directory, const char *path) {
1068    // If 'path' is an absolute path, return canonical path.
1069    //
1070    // Otherwise unfolds relative 'path' using 'relative_directory' as start directory.
1071
1072    if (is_absolute_path(path)) return GB_canonical_path(path);
1073    return GB_concat_full_path(relative_directory, path);
1074}
1075
1076GB_CSTR GB_unfold_path(const char *pwd_envar, const char *path) {
1077    // If 'path' is an absolute path, return canonical path.
1078    //
1079    // Otherwise unfolds relative 'path' using content of environment
1080    // variable 'pwd_envar' as start directory.
1081    // If environment variable is not defined, fall-back to current directory
1082
1083    gb_assert(is_name_of_envvar(pwd_envar));
1084    if (is_absolute_path(path)) {
1085        return GB_canonical_path(path);
1086    }
1087
1088    const char *pwd = GB_getenv(pwd_envar);
1089    if (!pwd) pwd = GB_getcwd(); // @@@ really wanted ?
1090    return GB_concat_full_path(pwd, path);
1091}
1092
1093static GB_CSTR GB_path_in_ARBHOME(const char *relative_path_left, const char *anypath_right) {
1094    return GB_path_in_ARBHOME(GB_concat_path(relative_path_left, anypath_right));
1095}
1096
1097GB_CSTR GB_path_in_ARBHOME(const char *relative_path) {
1098    return GB_unfold_path("ARBHOME", relative_path);
1099}
1100GB_CSTR GB_path_in_ARBLIB(const char *relative_path) {
1101    return GB_path_in_ARBHOME("lib", relative_path);
1102}
1103GB_CSTR GB_path_in_HOME(const char *relative_path) {
1104    return GB_unfold_path("HOME", relative_path);
1105}
1106GB_CSTR GB_path_in_arbprop(const char *relative_path) {
1107    return GB_unfold_path("ARB_PROP", relative_path);
1108}
1109GB_CSTR GB_path_in_ARBLIB(const char *relative_path_left, const char *anypath_right) {
1110    return GB_path_in_ARBLIB(GB_concat_path(relative_path_left, anypath_right));
1111}
1112GB_CSTR GB_path_in_arb_temp(const char *relative_path) {
1113    return GB_path_in_HOME(GB_concat_path(".arb_tmp", relative_path));
1114}
1115
1116#define GB_PATH_TMP GB_path_in_arb_temp("tmp") // = "~/.arb_tmp/tmp" (used wherever '/tmp' was used in the past)
1117
1118FILE *GB_fopen_tempfile(const char *filename, const char *fmode, char **res_fullname) {
1119    // fopens a tempfile
1120    //
1121    // Returns
1122    // - NULL in case of error (which is exported then)
1123    // - otherwise returns open filehandle
1124    //
1125    // Always sets
1126    // - heap-copy of used filename in 'res_fullname' (if res_fullname != NULL)
1127    // (even if fopen failed)
1128
1129    char     *file  = strdup(GB_concat_path(GB_PATH_TMP, filename));
1130    GB_ERROR  error = GB_create_parent_directory(file);
1131    FILE     *fp    = NULL;
1132
1133    if (!error) {
1134        bool write = strpbrk(fmode, "wa") != 0;
1135
1136        fp = fopen(file, fmode);
1137        if (fp) {
1138            // make file private
1139            if (fchmod(fileno(fp), S_IRUSR|S_IWUSR) != 0) {
1140                error = GB_IO_error("changing permissions of", file);
1141            }
1142        }
1143        else {
1144            error = GB_IO_error(GBS_global_string("opening(%s) tempfile", write ? "write" : "read"), file);
1145        }
1146
1147        if (res_fullname) {
1148            *res_fullname = file ? strdup(file) : 0;
1149        }
1150    }
1151
1152    if (error) {
1153        // don't care if anything fails here..
1154        if (fp) { fclose(fp); fp = 0; }
1155        if (file) unlink(file);
1156        GB_export_error(error);
1157    }
1158
1159    free(file);
1160
1161    return fp;
1162}
1163
1164char *GB_create_tempfile(const char *name) {
1165    // creates a tempfile and returns full name of created file
1166    // returns NULL in case of error (which is exported then)
1167
1168    char *fullname;
1169    FILE *out = GB_fopen_tempfile(name, "wt", &fullname);
1170
1171    if (out) fclose(out);
1172    return fullname;
1173}
1174
1175char *GB_unique_filename(const char *name_prefix, const char *suffix) {
1176    // generates a unique (enough) filename
1177    //
1178    // scheme: name_prefix_USER_PID_COUNT.suffix
1179
1180    static int counter = 0;
1181    return GBS_global_string_copy("%s_%s_%i_%i.%s",
1182                                  name_prefix,
1183                                  GB_getenvUSER(), getpid(), counter++,
1184                                  suffix);
1185}
1186
1187static GB_HASH *files_to_remove_on_exit = 0;
1188static long exit_remove_file(const char *file, long, void *) {
1189    if (unlink(file) != 0) {
1190        fprintf(stderr, "Warning: %s\n", GB_IO_error("removing", file));
1191    }
1192    return 0;
1193}
1194static void exit_removal() {
1195    if (files_to_remove_on_exit) {
1196        GBS_hash_do_loop(files_to_remove_on_exit, exit_remove_file, NULL);
1197        GBS_free_hash(files_to_remove_on_exit);
1198        files_to_remove_on_exit = NULL;
1199    }
1200}
1201void GB_remove_on_exit(const char *filename) {
1202    // mark a file for removal on exit
1203
1204    if (!files_to_remove_on_exit) {
1205        files_to_remove_on_exit = GBS_create_hash(20, GB_MIND_CASE);
1206        GB_atexit(exit_removal);
1207    }
1208    GBS_write_hash(files_to_remove_on_exit, filename, 1);
1209}
1210
1211void GB_split_full_path(const char *fullpath, char **res_dir, char **res_fullname, char **res_name_only, char **res_suffix) {
1212    // Takes a file (or directory) name and splits it into "path/name.suffix".
1213    // If result pointers (res_*) are non-NULL, they are assigned heap-copies of the split parts.
1214    // If parts are not valid (e.g. cause 'fullpath' doesn't have a .suffix) the corresponding result pointer
1215    // is set to NULL.
1216    //
1217    // The '/' and '.' characters at the split-positions will be removed (not included in the results-strings).
1218    // Exceptions:
1219    // - the '.' in 'res_fullname'
1220    // - the '/' if directory part is the rootdir
1221    //
1222    // Note:
1223    // - if the filename starts with '.' (and that is the only '.' in the filename, an empty filename is returned: "")
1224
1225    if (fullpath && fullpath[0]) {
1226        const char *lslash     = strrchr(fullpath, '/');
1227        const char *name_start = lslash ? lslash+1 : fullpath;
1228        const char *ldot       = strrchr(lslash ? lslash : fullpath, '.');
1229        const char *terminal   = strchr(name_start, 0);
1230
1231        gb_assert(terminal);
1232        gb_assert(name_start);
1233        gb_assert(terminal > fullpath); // ensure (terminal-1) is a valid character position in path
1234
1235        if (!lslash && fullpath[0] == '.' && (fullpath[1] == 0 || (fullpath[1] == '.' && fullpath[2] == 0))) { // '.' and '..'
1236            if (res_dir)       *res_dir       = strdup(fullpath);
1237            if (res_fullname)  *res_fullname  = NULL;
1238            if (res_name_only) *res_name_only = NULL;
1239            if (res_suffix)    *res_suffix    = NULL;
1240        }
1241        else {
1242            if (res_dir)       *res_dir       = lslash ? GB_strpartdup(fullpath, lslash == fullpath ? lslash : lslash-1) : NULL;
1243            if (res_fullname)  *res_fullname  = GB_strpartdup(name_start, terminal-1);
1244            if (res_name_only) *res_name_only = GB_strpartdup(name_start, ldot ? ldot-1 : terminal-1);
1245            if (res_suffix)    *res_suffix    = ldot ? GB_strpartdup(ldot+1, terminal-1) : NULL;
1246        }
1247    }
1248    else {
1249        if (res_dir)       *res_dir       = NULL;
1250        if (res_fullname)  *res_fullname  = NULL;
1251        if (res_name_only) *res_name_only = NULL;
1252        if (res_suffix)    *res_suffix    = NULL;
1253    }
1254}
1255
1256
1257// --------------------------------------------------------------------------------
1258
1259#ifdef UNIT_TESTS
1260
1261#include <test_unit.h>
1262
1263#define TEST_EXPECT_IS_CANONICAL(file)                  \
1264    do {                                                \
1265        char *dup = strdup(file);                       \
1266        TEST_EXPECT_EQUAL(GB_canonical_path(dup), dup); \
1267        free(dup);                                      \
1268    } while(0)
1269
1270#define TEST_EXPECT_CANONICAL_TO(not_cano,cano)                         \
1271    do {                                                                \
1272        char *arb_not_cano = strdup(GB_concat_path(arbhome, not_cano)); \
1273        char *arb_cano     = strdup(GB_concat_path(arbhome, cano));     \
1274        TEST_EXPECT_EQUAL(GB_canonical_path(arb_not_cano), arb_cano);   \
1275        free(arb_cano);                                                 \
1276        free(arb_not_cano);                                             \
1277    } while (0)
1278
1279static arb_test::match_expectation path_splits_into(const char *path, const char *Edir, const char *Enameext, const char *Ename, const char *Eext) {
1280    using namespace arb_test;
1281    expectation_group expected;
1282
1283    char *Sdir,*Snameext,*Sname,*Sext;
1284    GB_split_full_path(path, &Sdir, &Snameext, &Sname, &Sext);
1285
1286    expected.add(that(Sdir).is_equal_to(Edir));
1287    expected.add(that(Snameext).is_equal_to(Enameext));
1288    expected.add(that(Sname).is_equal_to(Ename));
1289    expected.add(that(Sext).is_equal_to(Eext));
1290
1291    free(Sdir);
1292    free(Snameext);
1293    free(Sname);
1294    free(Sext);
1295
1296    return all().ofgroup(expected);
1297}
1298
1299#define TEST_EXPECT_PATH_SPLITS_INTO(path,dir,nameext,name,ext)         TEST_EXPECTATION(path_splits_into(path,dir,nameext,name,ext))
1300#define TEST_EXPECT_PATH_SPLITS_INTO__BROKEN(path,dir,nameext,name,ext) TEST_EXPECTATION__BROKEN(path_splits_into(path,dir,nameext,name,ext))
1301
1302static arb_test::match_expectation path_splits_reversible(const char *path) {
1303    using namespace arb_test;
1304    expectation_group expected;
1305
1306    char *Sdir,*Snameext,*Sname,*Sext;
1307    GB_split_full_path(path, &Sdir, &Snameext, &Sname, &Sext);
1308
1309    expected.add(that(GB_append_suffix(Sname, Sext)).is_equal_to(Snameext)); // GB_append_suffix should reverse name.ext-split
1310    expected.add(that(GB_concat_path(Sdir, Snameext)).is_equal_to(path));    // GB_concat_path should reverse dir/file-split
1311
1312    free(Sdir);
1313    free(Snameext);
1314    free(Sname);
1315    free(Sext);
1316
1317    return all().ofgroup(expected);
1318}
1319
1320#define TEST_SPLIT_REVERSIBILITY(path)         TEST_EXPECTATION(path_splits_reversible(path))
1321#define TEST_SPLIT_REVERSIBILITY__BROKEN(path) TEST_EXPECTATION__BROKEN(path_splits_reversible(path))
1322
1323void TEST_paths() {
1324    // test GB_concat_path
1325    TEST_EXPECT_EQUAL(GB_concat_path("a", NULL), "a");
1326    TEST_EXPECT_EQUAL(GB_concat_path(NULL, "b"), "b");
1327    TEST_EXPECT_EQUAL(GB_concat_path("a", "b"), "a/b");
1328
1329    TEST_EXPECT_EQUAL(GB_concat_path("/", "test.fig"), "/test.fig");
1330
1331    // test GB_split_full_path
1332    TEST_EXPECT_PATH_SPLITS_INTO("dir/sub/.ext",              "dir/sub",   ".ext",            "",            "ext");
1333    TEST_EXPECT_PATH_SPLITS_INTO("/root/sub/file.notext.ext", "/root/sub", "file.notext.ext", "file.notext", "ext");
1334
1335    TEST_EXPECT_PATH_SPLITS_INTO("./file.ext", ".", "file.ext", "file", "ext");
1336    TEST_EXPECT_PATH_SPLITS_INTO("/file",      "/", "file",     "file", NULL);
1337    TEST_EXPECT_PATH_SPLITS_INTO(".",          ".", NULL,       NULL,   NULL);
1338
1339    // test reversibility of GB_split_full_path and GB_concat_path/GB_append_suffix
1340    {
1341        const char *prefix[] = {
1342            "",
1343            "dir/",
1344            "dir/sub/",
1345            "/dir/",
1346            "/dir/sub/",
1347            "/",
1348            "./",
1349            "../",
1350        };
1351
1352        for (size_t d = 0; d<ARRAY_ELEMS(prefix); ++d) {
1353            TEST_ANNOTATE(GBS_global_string("prefix='%s'", prefix[d]));
1354
1355            TEST_SPLIT_REVERSIBILITY(GBS_global_string("%sfile.ext", prefix[d]));
1356            TEST_SPLIT_REVERSIBILITY(GBS_global_string("%sfile", prefix[d]));
1357            TEST_SPLIT_REVERSIBILITY(GBS_global_string("%s.ext", prefix[d]));
1358            if (prefix[d][0]) { // empty string "" reverts to NULL
1359                TEST_SPLIT_REVERSIBILITY(prefix[d]);
1360            }
1361        }
1362    }
1363
1364    // GB_canonical_path basics
1365    TEST_EXPECT_CONTAINS(GB_canonical_path("./bla"), "UNIT_TESTER/run/bla");
1366    TEST_EXPECT_CONTAINS(GB_canonical_path("bla"),   "UNIT_TESTER/run/bla");
1367
1368    {
1369        char        *arbhome    = strdup(GB_getenvARBHOME());
1370        const char*  nosuchfile = "nosuchfile";
1371        const char*  somefile   = "arb_README.txt";
1372
1373        char *somefile_in_arbhome   = strdup(GB_concat_path(arbhome, somefile));
1374        char *nosuchfile_in_arbhome = strdup(GB_concat_path(arbhome, nosuchfile));
1375        char *nosuchpath_in_arbhome = strdup(GB_concat_path(arbhome, "nosuchpath"));
1376        char *somepath_in_arbhome   = strdup(GB_concat_path(arbhome, "lib"));
1377        char *file_in_nosuchpath    = strdup(GB_concat_path(nosuchpath_in_arbhome, "whatever"));
1378
1379        TEST_REJECT(GB_is_directory(nosuchpath_in_arbhome));
1380
1381        // test GB_get_full_path
1382        TEST_EXPECT_IS_CANONICAL(somefile_in_arbhome);
1383        TEST_EXPECT_IS_CANONICAL(nosuchpath_in_arbhome);
1384        TEST_EXPECT_IS_CANONICAL(file_in_nosuchpath);
1385
1386        TEST_EXPECT_IS_CANONICAL("/sbin"); // existing (most likely)
1387        TEST_EXPECT_IS_CANONICAL("/tmp/arbtest.fig");
1388        TEST_EXPECT_IS_CANONICAL("/arbtest.fig"); // not existing (most likely)
1389
1390        TEST_EXPECT_CANONICAL_TO("./PARSIMONY/./../ARBDB/./arbdb.h",     "ARBDB/arbdb.h"); // test parent-path
1391        TEST_EXPECT_CANONICAL_TO("INCLUDE/arbdb.h",                   "ARBDB/arbdb.h"); // test symbolic link to file
1392        TEST_EXPECT_CANONICAL_TO("NAMES_COM/AISC/aisc.pa",            "AISC_COM/AISC/aisc.pa"); // test symbolic link to directory
1393        TEST_EXPECT_CANONICAL_TO("./NAMES_COM/AISC/..",               "AISC_COM");              // test parent-path through links
1394
1395        TEST_EXPECT_CANONICAL_TO("./PARSIMONY/./../ARBDB/../nosuchpath", "nosuchpath"); // nosuchpath does not exist, but involved parent dirs do
1396        // test resolving of non-existent parent dirs:
1397        TEST_EXPECT_CANONICAL_TO("./PARSIMONY/./../nosuchpath/../ARBDB", "ARBDB");
1398        TEST_EXPECT_CANONICAL_TO("./nosuchpath/./../ARBDB", "ARBDB");
1399
1400        // test GB_unfold_path
1401        TEST_EXPECT_EQUAL(GB_unfold_path("ARBHOME", somefile), somefile_in_arbhome);
1402        TEST_EXPECT_EQUAL(GB_unfold_path("ARBHOME", nosuchfile), nosuchfile_in_arbhome);
1403
1404        char *inhome = strdup(GB_unfold_path("HOME", "whatever"));
1405        TEST_EXPECT_EQUAL(inhome, GB_canonical_path("~/whatever"));
1406        free(inhome);
1407
1408        // test GB_unfold_in_directory
1409        TEST_EXPECT_EQUAL(GB_unfold_in_directory(arbhome, somefile), somefile_in_arbhome);
1410        TEST_EXPECT_EQUAL(GB_unfold_in_directory(nosuchpath_in_arbhome, somefile_in_arbhome), somefile_in_arbhome);
1411        TEST_EXPECT_EQUAL(GB_unfold_in_directory(arbhome, nosuchfile), nosuchfile_in_arbhome);
1412        TEST_EXPECT_EQUAL(GB_unfold_in_directory(nosuchpath_in_arbhome, "whatever"), file_in_nosuchpath);
1413        TEST_EXPECT_EQUAL(GB_unfold_in_directory(somepath_in_arbhome, "../nosuchfile"), nosuchfile_in_arbhome);
1414
1415        // test unfolding absolute paths (HOME is ignored)
1416        TEST_EXPECT_EQUAL(GB_unfold_path("HOME", arbhome), arbhome);
1417        TEST_EXPECT_EQUAL(GB_unfold_path("HOME", somefile_in_arbhome), somefile_in_arbhome);
1418        TEST_EXPECT_EQUAL(GB_unfold_path("HOME", nosuchfile_in_arbhome), nosuchfile_in_arbhome);
1419
1420        // test GB_path_in_ARBHOME
1421        TEST_EXPECT_EQUAL(GB_path_in_ARBHOME(somefile), somefile_in_arbhome);
1422        TEST_EXPECT_EQUAL(GB_path_in_ARBHOME(nosuchfile), nosuchfile_in_arbhome);
1423
1424        free(file_in_nosuchpath);
1425        free(somepath_in_arbhome);
1426        free(nosuchpath_in_arbhome);
1427        free(nosuchfile_in_arbhome);
1428        free(somefile_in_arbhome);
1429        free(arbhome);
1430    }
1431
1432    TEST_EXPECT_EQUAL(GB_path_in_ARBLIB("help"), GB_path_in_ARBHOME("lib", "help"));
1433
1434}
1435
1436// ----------------------------------------
1437
1438class TestFile : virtual Noncopyable {
1439    const char *name;
1440    bool open(const char *mode) {
1441        FILE *out = fopen(name, mode);
1442        if (out) fclose(out);
1443        return out;
1444    }
1445    void create() { ASSERT_RESULT(bool, true, open("w")); }
1446    void unlink() { ::unlink(name); }
1447public:
1448    TestFile(const char *name_) : name(name_) { create(); }
1449    ~TestFile() { if (exists()) unlink(); }
1450    const char *get_name() const { return name; }
1451    bool exists() { return open("r"); }
1452};
1453
1454void TEST_GB_remove_on_exit() {
1455    {
1456        // first test class TestFile
1457        TestFile file("test1");
1458        TEST_EXPECT(file.exists());
1459        TEST_EXPECT(TestFile(file.get_name()).exists()); // removes the file
1460        TEST_REJECT(file.exists());
1461    }
1462
1463    TestFile t("test1");
1464    {
1465        GB_shell shell;
1466        GBDATA *gb_main = GB_open("no.arb", "c");
1467
1468        GB_remove_on_exit(t.get_name());
1469        GB_close(gb_main);
1470    }
1471    TEST_REJECT(t.exists());
1472}
1473
1474void TEST_some_paths() {
1475    gb_getenv_hook old = GB_install_getenv_hook(arb_test::fakeenv);
1476    {
1477        // ../UNIT_TESTER/run/homefake
1478
1479        TEST_EXPECT_CONTAINS__BROKEN(GB_getenvHOME(), "/UNIT_TESTER/run/homefake"); // GB_getenvHOME() ignores the hook
1480        // @@@ this is a general problem - unit tested code cannot use GB_getenvHOME() w/o problems
1481
1482        TEST_EXPECT_CONTAINS(GB_getenvARB_PROP(), "/UNIT_TESTER/run/homefake/.arb_prop");
1483        TEST_EXPECT_CONTAINS(GB_getenvARBMACRO(), "/lib/macros");
1484
1485        TEST_EXPECT_CONTAINS(GB_getenvARBCONFIG(),    "/UNIT_TESTER/run/homefake/.arb_prop/cfgSave");
1486        TEST_EXPECT_CONTAINS(GB_getenvARBMACROHOME(), "/UNIT_TESTER/run/homefake/.arb_prop/macros");  // works in [11068]
1487    }
1488    TEST_EXPECT_EQUAL((void*)arb_test::fakeenv, (void*)GB_install_getenv_hook(old));
1489}
1490
1491#endif // UNIT_TESTS
1492
Note: See TracBrowser for help on using the repository browser.