source: git/resources/feResource.cc @ 96c5cb

spielwiese
Last change on this file since 96c5cb was 96c5cb, checked in by Hans Schoenemann <hannes@…>, 11 years ago
chg: search p_Procs in %P and %b/MOD, report last try on failure
  • Property mode set to 100644
File size: 18.6 KB
Line 
1/****************************************
2*  Computer Algebra System SINGULAR     *
3****************************************/
4/*
5* ABSTRACT: management of resources
6*/
7
8#include <stdlib.h>
9#include <unistd.h>
10#include <string.h>
11#include <stdio.h>
12#include <sys/param.h>
13
14#ifdef HAVE_CONFIG_H
15#include "config.h"
16#endif /* HAVE_CONFIG_H */
17
18#include "omFindExec.h"
19
20#include "feResource.h"
21
22char* feArgv0 = NULL;
23
24#ifdef AIX_4
25#ifndef HAVE_PUTENV
26#define HAVE_PUTENV 1
27#endif
28#endif
29
30#if defined(HPUX_10) || defined(HPUX_9)
31#ifndef HAVE_SETENV
32extern "C" int setenv(const char *name, const char *value, int overwrite);
33#endif
34#endif
35
36
37//#include <reporter/reporter.h>
38//char* feResource(const char id, int warn = -1);
39//char* feResource(const char* key, int warn = -1);
40
41// define RESOURCE_DEBUG for chattering about resource management
42// #define RESOURCE_DEBUG
43
44#define SINGULAR_DEFAULT_DIR "/usr/local/Singular/"
45
46/*****************************************************************
47 *
48 * Declarations: Data  structures
49 *
50 *****************************************************************/
51// feSprintf transforms format strings as follows:
52// 1.) substrings of the form %c (c being a letter) are replaced by respective resource value
53// 2.) substrings of the form $string are replaced by value of resp. env variable
54
55// feCleanResource makes furthermore  the following transformations (except for URL resources)
56// 1.) '/' characters are replaced by respective directory - separators
57// 2.) ';' characters are replaced by respective path separators
58feResourceConfig_s feResourceConfigs[] =
59{
60  {"SearchPath",    's', feResPath,  NULL,
61   "$SINGULARPATH;"
62   "%D/singular/LIB;"
63   "%r/share/singular/LIB;"
64   "%b/../share/singular/LIB;"
65   "%D/factory;"
66   "%r/share/factory;"
67   "%b/../share/factory;"
68   "%r/libexec/singular/MOD;"
69   "%b/../libexec/singular/MOD;"
70   "%b/LIB;"
71   "%r/LIB;"
72   "%d/LIB;"
73   "%b/MOD;"
74   "%r/MOD;"
75   "%d/MOD;"
76   "%b;"
77   "%b/../factory;"
78   "%b/../../factory",
79   ""},
80  {"Singular",  'S',    feResBinary,"SINGULAR_EXECUTABLE",  "%d/Singular",          (char *)""},
81  {"BinDir",    'b',    feResDir,   "SINGULAR_BIN_DIR",     "%d/MOD/",                  (char *)""},
82  // should be changed to %b/../libexec/singular/pProcs/:
83  {"ProcDir",   'P',    feResDir,   "SINGULAR_PROCS_DIR",   "%b/MOD/",                  (char *)""},
84  {"RootDir",   'r',    feResDir,   "SINGULAR_ROOT_DIR",    "%b/..",                (char *)""},
85  {"DataDir",   'D',    feResDir,   "SINGULAR_DATA_DIR",    "%b/../share/",          (char *)""},
86  {"DefaultDir",'d',    feResDir,   "SINGULAR_DEFAULT_DIR",  SINGULAR_DEFAULT_DIR,  (char *)""},
87  {"InfoFile",  'i',    feResFile,  "SINGULAR_INFO_FILE",   "%r/info/singular.hlp", (char *)""},
88  {"IdxFile",   'x',    feResFile,  "SINGULAR_IDX_FILE",    "%r/doc/singular.idx",  (char *)""},
89  {"HtmlDir",   'h',    feResDir,   "SINGULAR_HTML_DIR",    "%r/html",              (char *)""},
90#ifdef ix86_Win
91  {"HtmlHelpFile",'C',  feResFile,  "SINGULAR_CHM_FILE",    "%r/doc/Manual.chm",    (char *)""},
92#endif
93  {"ManualUrl", 'u',    feResUrl,   "SINGULAR_URL",         "http://www.singular.uni-kl.de/index.php/singular-manual.html",    (char *)""},
94  {"ExDir",     'm',    feResDir,   "SINGULAR_EXAMPLES_DIR","%r/examples",          (char *)""},
95  {"Path",      'p',    feResPath,  NULL,                   "%b;$PATH",             (char *)""},
96
97  {"emacs",     'E',    feResBinary,"ESINGULAR_EMACS",      "%b/emacs",             (char *)""},
98  {"xemacs",    'A',    feResBinary,"ESINGULAR_EMACS",      "%b/xemacs",            (char *)""},
99  {"SingularEmacs",'M', feResBinary,"ESINGULAR_SINGULAR",   "%b/Singular",          (char *)""},
100  {"EmacsLoad", 'l',    feResFile,  "ESINGULAR_EMACS_LOAD", "%e/.emacs-singular",   (char *)""},
101  {"EmacsDir",  'e',    feResDir,   "ESINGULAR_EMACS_DIR",  "%D/singular/emacs",             (char *)""},
102  {"SingularXterm",'M', feResBinary,"TSINGULAR_SINGULAR",   "%b/Singular",          (char *)""},
103#ifdef ix86_Win
104  {"rxvt",      'X',    feResBinary,"RXVT",                 "%b/rxvt",              (char *)""},
105#else
106  {"xterm",     'X',    feResBinary,"XTERM",                "%b/xterm",             (char *)""},
107#endif
108  {"EmacsDir",  'e',    feResDir,   "SINGULAR_EMACS_DIR",   "%r/emacs",             (char *)""},
109  {NULL, 0, feResUndef, NULL, NULL, NULL}, // must be the last record
110};
111
112
113/*****************************************************************
114 *
115 * Declarations: Local variables / functions
116 *
117 *****************************************************************/
118
119#define MAXRESOURCELEN 5*MAXPATHLEN
120
121static feResourceConfig feGetResourceConfig(const char id);
122static feResourceConfig feGetResourceConfig(const char* key);
123static char* feResource(feResourceConfig config, int warn);
124static char* feResourceDefault(feResourceConfig config);
125static char* feInitResource(feResourceConfig config, int warn);
126static char* feGetExpandedExecutable();
127static int feVerifyResourceValue(feResourceType type, char* value);
128static char* feCleanResourceValue(feResourceType type, char* value);
129static char* feCleanUpFile(char* fname);
130static char* feCleanUpPath(char* path);
131static void mystrcpy(char* d, char* s);
132static char* feSprintf(char* s, const char* fmt, int warn = -1);
133#if defined(ix86_Win) && defined(__GNUC__)
134// utility function of Cygwin32:
135extern "C" int cygwin32_posix_path_list_p (const char *path);
136#endif
137
138/*****************************************************************
139 *
140 * Public functions
141 *
142 *****************************************************************/
143char* feResource(const char* key, int warn)
144{
145  return feResource(feGetResourceConfig(key), warn);
146}
147
148char* feResource(const char id, int warn)
149{
150  return feResource(feGetResourceConfig(id), warn);
151}
152
153char* feGetResource(const char id)
154{
155  return feResource(feGetResourceConfig(id), -1);
156}
157
158char* feResourceDefault(const char id)
159{
160  return feResourceDefault(feGetResourceConfig(id));
161}
162
163char* feResourceDefault(const char* key)
164{
165  return feResourceDefault(feGetResourceConfig(key));
166}
167
168void feInitResources(const char* argv0)
169{
170#if defined(ix86_Win) && defined(__GNUC__)
171  if (cygwin32_posix_path_list_p (getenv("PATH")))
172    fePathSep = ':';
173#endif
174  if (argv0==NULL)
175  {
176    feArgv0 = (char*)malloc(MAXPATHLEN+strlen("/Singular"));
177    getcwd(feArgv0, MAXPATHLEN);
178    strcpy(feArgv0+strlen(feArgv0),"/Singular");
179  }
180  else
181    feArgv0 = strdup(argv0);
182#ifdef RESOURCE_DEBUG
183  printf("feInitResources: entering with argv0=%s=\n", feArgv0);
184#endif
185  // init some Resources
186  feResource('b');
187  feResource('r');
188  // don't complain about stuff when initializing SingularPath
189  feResource('s',0);
190
191#if defined(HAVE_SETENV) || defined(HAVE_PUTENV)
192  char* path = feResource('p');
193#ifdef RESOURCE_DEBUG
194  printf("feInitResources: setting path with argv0=%s=\n", path);
195#endif
196#ifdef HAVE_PUTENV
197  if (path != NULL) { char *s=(char *)malloc(strlen(path)+6);
198                      sprintf(s,"PATH=%s",path);
199                      putenv(s);
200                    }
201#else
202  if (path != NULL) setenv("PATH", path, 1);
203#endif
204#endif
205}
206
207void feReInitResources()
208{
209  int i = 0;
210  while (feResourceConfigs[i].key != NULL)
211  {
212    if ((feResourceConfigs[i].value != NULL)
213    && (feResourceConfigs[i].value[0] != '\0'))
214    {
215      free(feResourceConfigs[i].value);
216      feResourceConfigs[i].value = (char *)"";
217    }
218    i++;
219  }
220#ifdef RESOURCE_DEBUG
221  printf("feInitResources: entering with argv0=%s=\n", feArgv0);
222#endif
223  // init some Resources
224  feResource('b');
225  feResource('r');
226  // don't complain about stuff when initializing SingularPath
227  feResource('s',0);
228}
229
230/*****************************************************************
231 *
232 * Local functions
233 *
234 *****************************************************************/
235static feResourceConfig feGetResourceConfig(const char id)
236{
237  int i = 0;
238  while (feResourceConfigs[i].key != NULL)
239  {
240    if (feResourceConfigs[i].id == id) return &(feResourceConfigs[i]);
241    i++;
242  }
243  return NULL;
244}
245
246static feResourceConfig feGetResourceConfig(const char* key)
247{
248  int i = 0;
249  while (feResourceConfigs[i].key != NULL)
250  {
251    if (strcmp(feResourceConfigs[i].key, key) == 0)
252      return &(feResourceConfigs[i]);
253    i++;
254  }
255  return NULL;
256}
257
258static char* feResource(feResourceConfig config, int warn)
259{
260  if (config == NULL) return NULL;
261  if (config->value != NULL && *(config->value) != '\0') return config->value;
262  return feInitResource(config, warn);
263}
264
265static char* feResourceDefault(feResourceConfig config)
266{
267  if (config == NULL) return NULL;
268  char* value = (char*) malloc(MAXRESOURCELEN);
269  feSprintf(value, config->fmt, -1);
270  return value;
271}
272
273static char* feInitResource(feResourceConfig config, int warn)
274{
275  /*assume(config != NULL);*/
276#ifdef RESOURCE_DEBUG
277  printf("feInitResource: entering for %s\n", config->key);
278#endif
279
280  char value[MAXRESOURCELEN];
281  // now we have to work
282  // First, check Environment variable
283  if (config->env != NULL)
284  {
285    char* evalue = getenv(config->env);
286    if (evalue != NULL)
287    {
288#ifdef RESOURCE_DEBUG
289      printf("feInitResource: Found value from env:%s\n", evalue);
290#endif
291      strcpy(value, evalue);
292      if (config->type == feResBinary  // do not verify binaries
293          ||
294          feVerifyResourceValue(config->type,
295                                feCleanResourceValue(config->type, value)))
296      {
297#ifdef RESOURCE_DEBUG
298        printf("feInitResource: Set value of %s to =%s=\n", config->key, value);
299#endif
300        config->value = strdup(value);
301        return config->value;
302      }
303    }
304  }
305
306  *value = '\0';
307  // Special treatment of executable
308  if (config->id == 'S')
309  {
310    char* executable = feGetExpandedExecutable();
311    if (executable != NULL)
312    {
313#ifdef RESOURCE_DEBUG
314      printf("exec:%s\n", executable);
315#endif
316      strcpy(value, executable);
317#ifdef RESOURCE_DEBUG
318      printf("value:%s\n", value);
319#endif
320      free(executable);
321    }
322  }
323  // and bindir
324  else if (config->id == 'b')
325  {
326    char* executable = feResource('S');
327#ifdef RESOURCE_DEBUG
328      printf("feInitResource: Get %s from %s\n", config->key, executable);
329#endif
330    if (executable != NULL)
331    {
332      strcpy(value, executable);
333      executable = strrchr(value, DIR_SEP);
334      if (executable != NULL) *executable = '\0';
335    }
336  }
337
338#ifdef RESOURCE_DEBUG
339  printf("value:%s\n", value);
340#endif
341
342  if (*value == '\0' && config->fmt != NULL )
343  {
344    feSprintf(value, config->fmt, warn);
345  }
346  else if (config->fmt == NULL)
347  {
348    printf("Bug >>Wrong Resource Specification of %s<< at %s:%d\n",config->key,__FILE__,__LINE__);
349    return NULL;
350  }
351
352  // Clean and verify
353  if (feVerifyResourceValue(config->type,
354                            feCleanResourceValue(config->type, value)))
355  {
356#ifdef RESOURCE_DEBUG
357    printf("feInitResource: Set value of %s to =%s=\n", config->key, value);
358#endif
359    config->value = strdup(value);
360    return config->value;
361  }
362  else if (config->type == feResBinary)
363  {
364    // for binaries, search through PATH once more
365    char* executable = omFindExec(config->key, value);
366    if (executable != NULL)
367    {
368      if (feVerifyResourceValue(config->type,
369                                feCleanResourceValue(config->type, value)))
370      {
371        config->value = strdup(value);
372#ifdef RESOURCE_DEBUG
373        printf("feInitResource: Set value of %s to =%s=\n", config->key, config->value);
374#endif
375        return config->value;
376      }
377    }
378  }
379
380  // issue warning if explicitely requested, or if
381  // this value is gotten for the first time
382  if (warn > 0 || (warn < 0 && config->value != NULL))
383  {
384    printf("// ** Could not get %s. ", config->key);
385    printf("// ** Either set environment variable %s to %s,",
386         config->env, config->key);
387    feSprintf(value, config->fmt, warn);
388    printf("// ** or make sure that %s is at %s", config->key, value);
389  }
390#ifdef RESOURCE_DEBUG
391      printf("feInitResource: Set value of %s to NULL", config->key);
392#endif
393  config->value = NULL;
394  return NULL;
395}
396
397static char* feGetExpandedExecutable()
398{
399  if (feArgv0 == NULL || *feArgv0 == '\0')
400  {
401    if (feArgv0 == NULL)
402      printf("Bug >>feArgv0 == NULL<< at %s:%d\n",__FILE__,__LINE__);
403    else
404      printf("Bug >>feArgv0 == ''<< at %s:%d\n",__FILE__,__LINE__);
405    return NULL;
406  }
407#ifdef ix86_Win // stupid WINNT sometimes gives you argv[0] within ""
408  if (*feArgv0 == '"')
409  {
410    int l = strlen(feArgv0);
411    if (feArgv0[l-1] == '"')
412    {
413      feArgv0[l-1] = '\0';
414      feArgv0++;
415    }
416  }
417#endif
418#ifdef RESOURCE_DEBUG
419  printf("feGetExpandedExecutable: calling find_exec with =%s=\n", feArgv0);
420#endif
421  char executable[MAXRESOURCELEN];
422  char* value = omFindExec(feArgv0, executable);
423#ifdef RESOURCE_DEBUG
424  printf("feGetExpandedExecutable: find_exec exited with =%s=%d\n", executable, access(executable, X_OK));
425#endif
426  if (value == NULL)
427  {
428    printf("Bug >>Could not get expanded executable from %s<< at %s:%d\n",feArgv0,__FILE__,__LINE__);
429    return NULL;
430  }
431  return strdup(value);
432}
433
434
435static int feVerifyResourceValue(feResourceType type, char* value)
436{
437#ifdef RESOURCE_DEBUG
438  printf("feVerifyResourceValue: entering with =%s=\n", value);
439  printf("%d:%d\n", access(value, R_OK), access(value, X_OK));
440#endif
441  switch(type)
442  {
443      case feResUrl:
444      case feResPath:
445        return 1;
446
447      case feResFile:
448        return ! access(value, R_OK);
449
450      case feResBinary:
451      case feResDir:
452        return ! access(value, X_OK);
453
454      default:
455        return 0;
456  }
457}
458
459/*****************************************************************
460 *
461 * Cleaning/Transformations of resource values
462 *
463 *****************************************************************/
464
465static char* feCleanResourceValue(feResourceType type, char* value)
466{
467  if (value == NULL || *value == '\0') return value;
468#ifdef RESOURCE_DEBUG
469      printf("Clean value:%s\n", value);
470#endif
471#ifdef ix86_Win
472#ifdef RESOURCE_DEBUG
473      printf("Clean WINNT value:%s\n", value);
474#endif
475  if (type == feResBinary)
476  {
477    int l = strlen(value);
478    if (l < 4 || (strcmp(&value[l-4], ".exe") != 0 &&
479                  strcmp(&value[l-4], ".EXE") != 0))
480      strcat(value, ".exe");
481  }
482#endif
483  if (type == feResFile || type == feResBinary || type == feResDir)
484    return feCleanUpFile(value);
485  if (type == feResPath)
486    return feCleanUpPath(value);
487  return value;
488}
489
490static char* feCleanUpFile(char* fname)
491{
492  char* fn;
493
494#ifdef RESOURCE_DEBUG
495  printf("feCleanUpFile: entering with =%s=\n", fname);
496#endif
497  // Remove unnecessary .. and //
498  for (fn = fname; *fn != '\0'; fn++)
499  {
500    if (*fn == '/')
501    {
502      if (*(fn+1) == '\0')
503      {
504        if (fname != fn) *fn = '\0';
505        break;
506      }
507      if (*(fn + 1) == '/' && (fname != fn))
508      {
509        mystrcpy(fn, fn+1);
510        fn--;
511      }
512      else if (*(fn+1) == '.')
513      {
514        if (*(fn+2) == '.' && (*(fn + 3) == '/' || *(fn + 3) == '\0'))
515        {
516        #if 0
517        // this does not work: ./../../mmm will be changed to ./../mmm
518        // but we only want to change ././mmm to ./mmm
519          *fn = '\0';
520          s = strrchr(fname, '/');
521          if (s != NULL)
522          {
523            mystrcpy(s+1, fn + (*(fn + 3) != '\0' ? 4 : 3));
524            fn = s-1;
525          }
526          else
527          {
528            *fn = '/';
529          }
530        #endif
531        }
532        else if (*(fn+2) == '/' || *(fn+2) == '\0')
533        {
534          mystrcpy(fn+1, fn+3);
535          fn--;
536        }
537      }
538    }
539  }
540
541#ifdef RESOURCE_DEBUG
542  printf("feCleanUpFile: leaving with =%s=\n", fname);
543#endif
544  return fname;
545}
546
547// remove duplicates dir resp. those which do not exist
548static char* feCleanUpPath(char* path)
549{
550#ifdef RESOURCE_DEBUG
551  printf("feCleanUpPath: entering with: =%s=\n", path);
552#endif
553  if (path == NULL) return path;
554
555  int n_comps = 1, i, j;
556  char* opath = path;
557  char** path_comps;
558
559  for (; *path != '\0'; path++)
560  {
561    if (*path == fePathSep) n_comps++;
562    else if (*path == ';')
563    {
564      *path = fePathSep;
565      n_comps++;
566    }
567  }
568
569  path_comps = (char**) malloc(n_comps*sizeof(char*));
570  path_comps[0]=opath;
571  path=opath;
572  i = 1;
573
574  if (i < n_comps)
575  {
576    while (1)
577    {
578      if (*path == fePathSep)
579      {
580        *path = '\0';
581        path_comps[i] = path+1;
582        i++;
583        if (i == n_comps) break;
584      }
585      path++;
586    }
587  }
588
589  for (i=0; i<n_comps; i++)
590    path_comps[i] = feCleanUpFile(path_comps[i]);
591#ifdef RESOURCE_DEBUG
592  PrintS("feCleanUpPath: after CleanUpName: ");
593  for (i=0; i<n_comps; i++)
594    Print("%s:", path_comps[i]);
595  Print("\n");
596#endif
597
598  for (i=0; i<n_comps;)
599  {
600#ifdef RESOURCE_DEBUG
601    if (access(path_comps[i], X_OK | R_OK))
602      Print("feCleanUpPath: remove %d:%s -- can not access\n", i, path_comps[i]);
603#endif
604    if ( ! access(path_comps[i], X_OK | R_OK))
605    {
606      // x- permission is granted -- we assume that it is a dir
607      for (j=0; j<i; j++)
608      {
609        if (strcmp(path_comps[j], path_comps[i]) == 0)
610        {
611          // found a duplicate
612#ifdef RESOURCE_DEBUG
613          Print("feCleanUpPath: remove %d:%s -- equal to %d:%s\n", j, path_comps[j], i, path_comps[i]);
614#endif
615          j = i+1;
616          break;
617        }
618      }
619      if (j == i)
620      {
621        i++;
622        continue;
623      }
624    }
625    // now we can either not access or found a duplicate
626    path_comps[i] = NULL;
627    for (j=i+1; j<n_comps; j++)
628        path_comps[j-1] = path_comps[j];
629    n_comps--;
630  }
631
632
633  // assemble everything again
634  for (path=opath, i=0;i<n_comps-1;i++)
635  {
636    mystrcpy(path, path_comps[i]);
637    path += strlen(path);
638    *path = fePathSep;
639    path++;
640  }
641  if (n_comps)
642  {
643    mystrcpy(path, path_comps[i]);
644  }
645  else
646  {
647    *opath = '\0';
648  }
649  free(path_comps);
650#ifdef RESOURCE_DEBUG
651  Print("feCleanUpPath: leaving with path=%s=\n", opath);
652#endif
653  return opath;
654}
655
656// strcpy where source and destination may overlap
657static void mystrcpy(char* d, char* s)
658{
659  /*assume(d != NULL && s != NULL);*/
660  while (*s != '\0')
661  {
662    *d = *s;
663    d++;
664    s++;
665  }
666  *d = '\0';
667}
668
669/*****************************************************************
670 *
671 * feSprintf
672 *
673 *****************************************************************/
674static char* feSprintf(char* s, const char* fmt, int warn)
675{
676  char* s_in = s;
677  if (fmt == NULL) return NULL;
678
679  while (*fmt != '\0')
680  {
681    *s = *fmt;
682
683    if (*fmt == '%' && *(fmt + 1) != '\0')
684    {
685      fmt++;
686      char* r = feResource(*fmt, warn);
687      if (r != NULL)
688      {
689        strcpy(s, r);
690        s += strlen(r) - 1;
691      }
692      else
693      {
694        s++;
695        *s = *fmt;
696      }
697    }
698    else if (*fmt == '$' && *(fmt + 1) != '\0')
699    {
700      fmt++;
701      char* v = s + 1;
702      while (*fmt == '_' ||
703             (*fmt >= 'A' && *fmt <= 'Z') ||
704             (*fmt >= 'a' && *fmt <= 'z'))
705      {
706        *v = *fmt;
707        v++;
708        fmt++;
709      }
710      fmt--;
711      *v = '\0';
712      v = getenv(s + 1);
713      if (v != NULL) strcpy(s, v);
714      s += strlen(s) - 1;
715    }
716    s++;
717    fmt++;
718  }
719  *s = '\0';
720  return s_in;
721}
722
Note: See TracBrowser for help on using the repository browser.