source: tags/ms_r18q1/ARBDB/adsocket.cxx

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