feisty meow concerns codebase  2.140
application_configuration.cpp
Go to the documentation of this file.
1 /*
2 * Name : application_configuration
3 * Author : Chris Koeritz
4 
5 * Copyright (c) 1994-$now By Author. This program is free software; you can
6 * redistribute it and/or modify it under the terms of the GNU General Public
7 * License as published by the Free Software Foundation; either version 2 of
8 * the License or (at your option) any later version. This is online at:
9 * http://www.fsf.org/copyleft/gpl.html
10 * Please send any updates to: fred@gruntose.com
11 */
12 
14 #include "ini_configurator.h"
15 
17 #include <basis/environment.h>
18 #include <basis/functions.h>
19 #include <basis/guards.h>
20 #include <basis/mutex.h>
21 #include <basis/utf_conversion.h>
22 #include <filesystem/directory.h>
23 #include <filesystem/filename.h>
24 #include <mathematics/chaos.h>
26 #include <textual/parser_bits.h>
27 #include <system_helper.h>
28 
29 #ifdef __APPLE__
30  #include <mach-o/dyld.h>
31  #include <limits.h>
32 #endif
33 //#ifdef _MSC_VER
34 // #include <direct.h>
35 // #include <process.h>
36 //#else
37  #include <dirent.h>
38  #include <sys/utsname.h>
39  #include <unistd.h>
40 //#endif
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <sys/stat.h>
45 
46 using namespace basis;
47 using namespace filesystem;
48 using namespace mathematics;
49 using namespace structures;
50 using namespace textual;
51 
52 #undef LOG
53 #define LOG(to_print) printf("%s\n", astring(to_print).s())
54 
55 namespace configuration {
56 
57 const int MAXIMUM_COMMAND_LINE = 32 * KILOBYTE;
58  // maximum command line that we'll deal with here.
59 
60 #if defined(__UNIX__) || defined(__GNU_WINDOWS__)
61 astring application_configuration::get_cmdline_from_proc()
62 {
63  FUNCDEF("get_cmdline_from_proc");
64  static astring __check_once_app_path;
65 //hmmm: we want to use a single per app static synch here!
66  if (__check_once_app_path.length()) return __check_once_app_path;
67 
68 #ifdef __APPLE__
69  __check_once_app_path = query_for_process_info();
70  return __check_once_app_path;
71 #endif
72 
73  // we have not looked this app's name up in the path yet.
74  a_sprintf cmds_filename("/proc/%d/cmdline", process_id());
75  FILE *cmds_file = fopen(cmds_filename.s(), "r");
76  if (!cmds_file) {
77  LOG("failed to open our process's command line file.\n");
78  return "unknown";
79  }
80 //hmmm: this would be a lot nicer using a byte filer.
81  size_t size = 2000;
82  char *filebuff = new char[size + 1];
83  ssize_t chars_read = getline((char **)&filebuff, &size, cmds_file);
84  // read the first line, giving ample space for how long it might be.
85  fclose(cmds_file); // drop the file again.
86  if (!chars_read || negative(chars_read)) {
87  LOG("failed to get any characters from our process's cmdline file.\n");
88  return "unknown";
89  }
90  // copy the buffer into a string, which works great since the entries in the
91  // command line are all separated by zero characters.
92  __check_once_app_path = filebuff;
93  delete [] filebuff;
94 //printf("got an app name before chewing: %s\n", __check_once_app_path.s());
95  // clean out quote characters from the name.
96  for (int i = __check_once_app_path.length() - 1; i >= 0; i--) {
97  if (__check_once_app_path[i] == '"') __check_once_app_path.zap(i, i);
98  }
99  // check if the thing has a path attached to it. if it doesn't, we need to accentuate
100  // our knowledge about the file.
101  filename testing(__check_once_app_path);
102  if (testing.had_directory()) return __check_once_app_path; // all set.
103 
104 //printf("no dir part found, app name after chewing: %s\n", __check_once_app_path.s());
105 
106 //hmmm: the below might be better off as a find app in path method, which relies on which.
107  // there was no directory component, so we'll try to guess one.
108  astring temp_filename(environment::TMP()
109  + a_sprintf("/zz_cmdfind.%d", chaos().inclusive(0, 999999999)));
110  system((astring("which ") + __check_once_app_path + " >" + temp_filename).s());
111  FILE *which_file = fopen(temp_filename.s(), "r");
112  if (!which_file) {
113  LOG("failed to open the temporary output from which.\n");
114  return "unknown";
115  }
116  // reallocate the file buffer.
117  size = 2000;
118  filebuff = new char[size + 1];
119  chars_read = getline((char **)&filebuff, &size, which_file);
120  fclose(which_file);
121  unlink(temp_filename.s());
122  if (!chars_read || negative(chars_read)) {
123  LOG("failed to get any characters from the which cmd output.\n");
124  return "unknown";
125  } else {
126  // we had some luck using 'which' to locate the file, so we'll use this version.
127  __check_once_app_path = filebuff;
128  while (parser_bits::is_eol(__check_once_app_path[__check_once_app_path.end()])) {
129  __check_once_app_path.zap(__check_once_app_path.end(), __check_once_app_path.end());
130  }
131  }
132  delete [] filebuff;
133  return __check_once_app_path; // return whatever which told us.
134 }
135 
136 // deprecated; better to use the /proc/pid/cmdline file.
137 astring application_configuration::query_for_process_info()
138 {
139  FUNCDEF("query_for_process_info");
140  astring to_return = "unknown";
141  // we ask the operating system about our process identifier and store
142  // the results in a temporary file.
143  chaos rando;
144  a_sprintf tmpfile("/tmp/proc_name_check_%d_%d.txt", process_id(),
145  rando.inclusive(0, 128000));
146 #ifdef __APPLE__
147  a_sprintf cmd("ps -o args=\"\" %d >%s", process_id(),
148  tmpfile.s());
149 #else
150  a_sprintf cmd("ps h -O \"args\" %d >%s", process_id(),
151  tmpfile.s());
152 #endif
153  // run the command to locate our process info.
154  int sysret = system(cmd.s());
155  if (negative(sysret)) {
156  LOG("failed to run ps command to get process info");
157  return to_return;
158  }
159  // open the output file for reading.
160  FILE *output = fopen(tmpfile.s(), "r");
161  if (!output) {
162  LOG("failed to open the ps output file");
163  return to_return;
164  }
165  // read the file's contents into a string buffer.
166  char buff[MAXIMUM_COMMAND_LINE];
167  size_t size_read = fread(buff, 1, MAXIMUM_COMMAND_LINE, output);
168  if (size_read > 0) {
169  // success at finding some text in the file at least.
170  while (size_read > 0) {
171  const char to_check = buff[size_read - 1];
172  if ( !to_check || (to_check == '\r') || (to_check == '\n')
173  || (to_check == '\t') )
174  size_read--;
175  else break;
176  }
177  to_return.reset(astring::UNTERMINATED, buff, size_read);
178  } else {
179  // couldn't read anything.
180  LOG("could not read output of process list");
181  }
182  unlink(tmpfile.s());
183  return to_return;
184 }
185 #endif
186 
187 // used as a return value when the name cannot be determined.
188 #define SET_BOGUS_NAME(error) { \
189  LOG(error); \
190  if (output) { \
191  fclose(output); \
192  unlink(tmpfile.s()); \
193  } \
194  astring home_dir = environment::get("HOME"); \
195  to_return = home_dir + "/failed_to_determine.exe"; \
196 }
197 
198 astring application_configuration::application_name()
199 {
200  FUNCDEF("application_name");
201  astring to_return;
202 #ifdef __APPLE__
203  char buffer[MAX_ABS_PATH] = { '\0' };
204  uint32_t buffsize = MAX_ABS_PATH - 1;
205  _NSGetExecutablePath(buffer, &buffsize);
206  to_return = (char *)buffer;
207 #elif defined(__UNIX__) || defined(__GNU_WINDOWS__)
208  to_return = get_cmdline_from_proc();
209 /*
210 #elif defined(_MSC_VER)
211  flexichar low_buff[MAX_ABS_PATH + 1];
212  GetModuleFileName(NULL_POINTER, low_buff, MAX_ABS_PATH - 1);
213  astring buff = from_unicode_temp(low_buff);
214  buff.to_lower(); // we lower-case the name since windows seems to UC it.
215  to_return = buff;
216 */
217 #else
218  #pragma error("hmmm: no means of finding app name is implemented.")
219  SET_BOGUS_NAME("not_implemented_for_this_OS");
220 #endif
221  return to_return;
222 }
223 
224 #if defined(__UNIX__) || defined(__GNU_WINDOWS__)
225 //defined(_MSC_VER) ||
226  basis::un_int application_configuration::process_id() { return getpid(); }
227 #else
228  #pragma error("hmmm: need process id implementation for this OS!")
229  basis::un_int application_configuration::process_id() { return 0; }
230 #endif
231 
232 astring application_configuration::current_directory()
233 {
234  astring to_return;
235 #ifdef __UNIX__
236  char buff[MAX_ABS_PATH];
237  getcwd(buff, MAX_ABS_PATH - 1);
238  to_return = buff;
239 //#elif defined(_MSC_VER)
240 // flexichar low_buff[MAX_ABS_PATH + 1];
241 // GetCurrentDirectory(MAX_ABS_PATH, low_buff);
242 // to_return = from_unicode_temp(low_buff);
243 #else
244  #pragma error("hmmm: need support for current directory on this OS.")
245  to_return = ".";
246 #endif
247  return to_return;
248 }
249 
250 // implement the software product function.
251 const char *application_configuration::software_product_name()
252 {
253 #ifdef GLOBAL_PRODUCT_NAME
254  return GLOBAL_PRODUCT_NAME;
255 #else
256  return "hoople";
257 #endif
258 }
259 
260 astring application_configuration::application_directory()
261 { return filename(application_name()).dirname().raw(); }
262 
263 structures::version application_configuration::get_OS_version()
264 {
265  version to_return;
266 #ifdef __UNIX__
267  utsname kernel_parms;
268  uname(&kernel_parms);
269  to_return = version(kernel_parms.release);
270 //#elif defined(_MSC_VER)
271 // OSVERSIONINFO info;
272 // info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
273 // ::GetVersionEx(&info);
274 // to_return = version(a_sprintf("%u.%u.%u.%u", basis::un_short(info.dwMajorVersion),
275 // basis::un_short(info.dwMinorVersion), basis::un_short(info.dwPlatformId),
276 // basis::un_short(info.dwBuildNumber)));
277 #else
278  #pragma error("hmmm: need version info for this OS!")
279 #endif
280  return to_return;
281 }
282 
284 
285 const char *PATH_CONFIGURATION_FILENAME() { return "paths.ini"; }
286 
287 astring application_configuration::application_configuration_file()
288 {
289  filename cfg_file(application_directory() + "/" + PATH_CONFIGURATION_FILENAME());
290  return cfg_file.raw();
291 }
292 
293 const astring &application_configuration::GLOBAL_SECTION_NAME() { STATIC_STRING("Common"); }
294 
295 const astring &application_configuration::LOGGING_FOLDER_NAME() { STATIC_STRING("LogPath"); }
296 
297 //const astring &application_configuration::WINDOZE_VIRTUAL_ROOT_NAME()
298 //{ STATIC_STRING("VirtualUnixRoot"); }
299 
300 const astring &application_configuration::DEFAULT_VIRTUAL_UNIX_ROOT()
301 { STATIC_STRING("c:/cygwin"); }
302 
304 
305 // static storage for virtual unix root, if it's used.
306 // we don't expect it to change during runtime, right? that would be fubar.
307 // so we cache it once we retrieve it.
308 SAFE_STATIC(astring, static_root_holder, )
309 
310 const astring &application_configuration::virtual_unix_root()
311 {
312  // see if we already cached the root. it shouldn't change during runtime.
313  if (static_root_holder().length()) {
314  return static_root_holder();
315  }
316 #ifdef __UNIX__
317  // simple implementation for unix/linux; just tell the truth about the real root.
318  static_root_holder() = astring("/");
319  return static_root_holder();
320 #endif
321 #ifdef __WIN32__
322  /*
323  use the path in our system helpers header, which should have been set during the
324  build process if this is really windows.
325  */
326  astring virtual_root = FEISTY_MEOW_VIRTUAL_UNIX_ROOT;
327  if (!virtual_root) {
328  // if it has no length, we didn't get our setting! we'll limp along with a guess.
329  return DEFAULT_VIRTUAL_UNIX_ROOT();
330  } else {
331  static_root_holder() = virtual_root;
332  return static_root_holder();
333  }
334 
335 #endif
336 }
337 
339 
341  // the maximum length of the entry stored for the log path.
342 
343 astring application_configuration::get_logging_directory()
344 {
345  // new scheme is to just use the temporary directory, which can vary per user
346  // and which hopefully is always set to something usable.
347  astring def_log = environment::TMP();
348  // add logs directory underneath that.
349  def_log += "/logs";
350  // add the subdirectory for logs.
351 
352  // now grab the current value for the name, if any.
353  astring log_dir = read_item(LOGGING_FOLDER_NAME());
354  // get the entry for the logging path.
355  if (!log_dir) {
356  // if the entry was absent, we set it.
357 //printf("did not find log dir in config file\n");
358  ini_configurator ini(application_configuration_file(),
359  ini_configurator::RETURN_ONLY,
360  ini_configurator::APPLICATION_DIRECTORY);
361  ini.store(GLOBAL_SECTION_NAME(), LOGGING_FOLDER_NAME(), def_log);
362  } else {
363  // they gave us something. let's replace the environment variables
364  // in their string so we resolve paths and such.
365  log_dir = parser_bits::substitute_env_vars(log_dir);
366 //printf("%s", (char *)a_sprintf("got log dir with %s value\n", log_dir.s()).s());
367  }
368 
369  // now we make sure the directory exists.
370  filename testing(log_dir);
371  if (!testing.exists()) {
372  bool okay = directory::recursive_create(log_dir);
373  if (!okay) {
374  LOG(astring("failed to create logging directory: ") + log_dir);
375  // return a directory almost guaranteed to exist; best we can do in this case.
376 #ifdef __UNIX__
377  return "/tmp";
378 #endif
379 #ifdef __WIN32__
380  return "c:/";
381 #endif
382  }
383  }
384 
385  return log_dir;
386 }
387 
388 astring application_configuration::make_logfile_name(const astring &base_name)
389 { return get_logging_directory() + "/" + base_name; }
390 
391 astring application_configuration::read_item(const astring &key_name)
392 {
393  filename ini_name = application_configuration_file();
394  ini_configurator ini(ini_name, ini_configurator::RETURN_ONLY,
395  ini_configurator::APPLICATION_DIRECTORY);
396  astring to_return = ini.load(GLOBAL_SECTION_NAME(), key_name, "");
397  if (!!to_return) {
398  // if the string has any length, then we process any environment
399  // variables found encoded in the value.
400  to_return = parser_bits::substitute_env_vars(to_return);
401  }
402  return to_return;
403 }
404 
405 } // namespace.
406 
#define unlink
Definition: Xos2defs.h:45
#define getcwd
Definition: Xos2defs.h:29
#define getpid
Definition: Xos2defs.h:30
#define SET_BOGUS_NAME(error)
#define LOG(to_print)
a_sprintf is a specialization of astring that provides printf style support.
Definition: astring.h:440
Provides a dynamically resizable ASCII character string.
Definition: astring.h:35
const char * s() const
synonym for observe. the 's' stands for "string", if that helps.
Definition: astring.h:113
virtual void zap(int start, int end)
Deletes the characters between "start" and "end" inclusively.
Definition: astring.cpp:521
void reset()
clears out the contents string.
Definition: astring.h:202
int end() const
returns the index of the last (non-null) character in the string.
Definition: astring.h:86
int length() const
Returns the current length of the string.
Definition: astring.cpp:132
static astring TMP()
provides a single place to get the temporary directory.
Definition: environment.cpp:39
Defines installation-specific locations in the file system.
bool store(const basis::astring &section, const basis::astring &entry, const basis::astring &to_store)
a synonym for put.
basis::astring load(const basis::astring &section, const basis::astring &entry, const basis::astring &default_value)
a synonym for get that implements the auto-store behavior.
Supports a configurator-based interface on text initialization files.
Provides operations commonly needed on file names.
Definition: filename.h:64
bool exists() const
returns true if the file exists.
Definition: filename.cpp:426
bool had_directory() const
returns true if the name that we were given had a non-empty directory.
Definition: filename.h:139
const basis::astring & raw() const
returns the astring that we're holding onto for the path.
Definition: filename.cpp:97
filename dirname() const
returns the directory for the filename.
Definition: filename.cpp:393
a platform-independent way to acquire random numbers in a specific range.
Definition: chaos.h:51
int inclusive(int low, int high) const
< Returns a pseudo-random number r, such that "low" <= r <= "high".
Definition: chaos.h:88
Holds a file's version identifier.
char * getline(register filepointer *filep)
char * base_name(register char *file)
Definition: makedep.cpp:653
#define FUNCDEF(func_in)
FUNCDEF sets the name of a function (and plugs it into the callstack).
Definition: enhance_cpp.h:57
#define MAX_ABS_PATH
Definition: filename.h:37
The guards collection helps in testing preconditions and reporting errors.
Definition: array.h:30
unsigned int un_int
Abbreviated name for unsigned integers.
Definition: definitions.h:62
bool negative(const type &a)
negative returns true if "a" is less than zero.
Definition: functions.h:43
const int KILOBYTE
Number of bytes in a kilobyte.
Definition: definitions.h:134
const char * PATH_CONFIGURATION_FILENAME()
A platform independent way to obtain the timestamp of a file.
Definition: byte_filer.cpp:37
An extension to floating point primitives providing approximate equality.
Definition: averager.h:21
A dynamic container class that holds any kind of object via pointers.
Definition: amorph.h:55
bool is_eol(char to_check)
#define STATIC_STRING(str)
Statically defines a string for the rest of the program's life.
#define SAFE_STATIC(type, func_name, parms)
Statically defines a singleton object whose scope is the program's lifetime.
chaos rando
Support for unicode builds.
Aids in achievement of platform independence.