source: git/kernel/feResource.cc @ b15b8f

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