source: tags/ms_ra2q56/ARBDB/adsocket.cxx

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