2 * Name : application_configuration
3 * Author : Chris Koeritz
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
13 #include "application_configuration.h"
14 #include "ini_configurator.h"
16 #include <application/windoze_helper.h>
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>
25 #include <structures/static_memory_gremlin.h>
26 #include <textual/parser_bits.h>
29 #include <mach-o/dyld.h>
39 #include <sys/utsname.h>
47 using namespace basis;
48 using namespace filesystem;
49 using namespace mathematics;
50 using namespace structures;
51 using namespace textual;
54 #define LOG(to_print) printf("%s\n", astring(to_print).s())
56 namespace configuration {
58 const int MAXIMUM_COMMAND_LINE = 32 * KILOBYTE;
59 // maximum command line that we'll deal with here.
62 astring application_configuration::get_cmdline_from_proc()
64 FUNCDEF("get_cmdline_from_proc");
65 static astring __check_once_app_path;
66 //hmmm: we want to use a single per app static synch here!
67 if (__check_once_app_path.length()) return __check_once_app_path;
70 __check_once_app_path = query_for_process_info();
71 return __check_once_app_path;
74 // we have not looked this app's name up in the path yet.
75 a_sprintf cmds_filename("/proc/%d/cmdline", process_id());
76 FILE *cmds_file = fopen(cmds_filename.s(), "r");
78 LOG("failed to open our process's command line file.\n");
81 //hmmm: this would be a lot nicer using a byte filer.
83 char *filebuff = new char[size + 1];
84 ssize_t chars_read = getline((char **)&filebuff, &size, cmds_file);
85 // read the first line, giving ample space for how long it might be.
86 fclose(cmds_file); // drop the file again.
87 if (!chars_read || negative(chars_read)) {
88 LOG("failed to get any characters from our process's cmdline file.\n");
91 // copy the buffer into a string, which works great since the entries in the
92 // command line are all separated by zero characters.
93 __check_once_app_path = filebuff;
95 //printf("got an app name before chewing: %s\n", __check_once_app_path.s());
96 // clean out quote characters from the name.
97 for (int i = __check_once_app_path.length() - 1; i >= 0; i--) {
98 if (__check_once_app_path[i] == '"') __check_once_app_path.zap(i, i);
100 // check if the thing has a path attached to it. if it doesn't, we need to accentuate
101 // our knowledge about the file.
102 filename testing(__check_once_app_path);
103 if (testing.had_directory()) return __check_once_app_path; // all set.
105 //printf("no dir part found, app name after chewing: %s\n", __check_once_app_path.s());
107 //hmmm: the below might be better off as a find app in path method, which relies on which.
108 // there was no directory component, so we'll try to guess one.
109 astring temp_filename(environment::TMP()
110 + a_sprintf("/zz_cmdfind.%d", chaos().inclusive(0, 999999999)));
111 system((astring("which ") + __check_once_app_path + " >" + temp_filename).s());
112 FILE *which_file = fopen(temp_filename.s(), "r");
114 LOG("failed to open the temporary output from which.\n");
117 // reallocate the file buffer.
119 filebuff = new char[size + 1];
120 chars_read = getline((char **)&filebuff, &size, which_file);
122 unlink(temp_filename.s());
123 if (!chars_read || negative(chars_read)) {
124 LOG("failed to get any characters from the which cmd output.\n");
127 // we had some luck using 'which' to locate the file, so we'll use this version.
128 __check_once_app_path = filebuff;
129 while (parser_bits::is_eol(__check_once_app_path[__check_once_app_path.end()])) {
130 __check_once_app_path.zap(__check_once_app_path.end(), __check_once_app_path.end());
134 return __check_once_app_path; // return whatever which told us.
137 // deprecated; better to use the /proc/pid/cmdline file.
138 astring application_configuration::query_for_process_info()
140 FUNCDEF("query_for_process_info");
141 astring to_return = "unknown";
142 // we ask the operating system about our process identifier and store
143 // the results in a temporary file.
145 a_sprintf tmpfile("/tmp/proc_name_check_%d_%d.txt", process_id(),
146 rando.inclusive(0, 128000));
148 a_sprintf cmd("ps -o args=\"\" %d >%s", process_id(),
151 a_sprintf cmd("ps h -O \"args\" %d >%s", process_id(),
154 // run the command to locate our process info.
155 int sysret = system(cmd.s());
156 if (negative(sysret)) {
157 LOG("failed to run ps command to get process info");
160 // open the output file for reading.
161 FILE *output = fopen(tmpfile.s(), "r");
163 LOG("failed to open the ps output file");
166 // read the file's contents into a string buffer.
167 char buff[MAXIMUM_COMMAND_LINE];
168 size_t size_read = fread(buff, 1, MAXIMUM_COMMAND_LINE, output);
170 // success at finding some text in the file at least.
171 while (size_read > 0) {
172 const char to_check = buff[size_read - 1];
173 if ( !to_check || (to_check == '\r') || (to_check == '\n')
174 || (to_check == '\t') )
178 to_return.reset(astring::UNTERMINATED, buff, size_read);
180 // couldn't read anything.
181 LOG("could not read output of process list");
188 // used as a return value when the name cannot be determined.
189 #define SET_BOGUS_NAME(error) { \
193 unlink(tmpfile.s()); \
195 astring home_dir = environment::get("HOME"); \
196 to_return = home_dir + "/failed_to_determine.exe"; \
199 astring application_configuration::application_name()
201 FUNCDEF("application_name");
204 char buffer[MAX_ABS_PATH] = { '\0' };
205 uint32_t buffsize = MAX_ABS_PATH - 1;
206 _NSGetExecutablePath(buffer, &buffsize);
207 to_return = (char *)buffer;
209 to_return = get_cmdline_from_proc();
210 #elif defined(__WIN32__)
211 flexichar low_buff[MAX_ABS_PATH + 1];
212 GetModuleFileName(NIL, 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.
217 #pragma error("hmmm: no means of finding app name is implemented.")
218 SET_BOGUS_NAME("not_implemented_for_this_OS");
223 #if defined(__UNIX__) || defined(__WIN32__)
224 basis::un_int application_configuration::process_id() { return getpid(); }
226 #pragma error("hmmm: need process id implementation for this OS!")
227 basis::un_int application_configuration::process_id() { return 0; }
230 astring application_configuration::current_directory()
234 char buff[MAX_ABS_PATH];
235 getcwd(buff, MAX_ABS_PATH - 1);
237 #elif defined(__WIN32__)
238 flexichar low_buff[MAX_ABS_PATH + 1];
239 GetCurrentDirectory(MAX_ABS_PATH, low_buff);
240 to_return = from_unicode_temp(low_buff);
242 #pragma error("hmmm: need support for current directory on this OS.")
248 // implement the software product function.
249 const char *application_configuration::software_product_name()
251 #ifdef GLOBAL_PRODUCT_NAME
252 return GLOBAL_PRODUCT_NAME;
258 astring application_configuration::application_directory()
259 { return filename(application_name()).dirname().raw(); }
261 structures::version application_configuration::get_OS_version()
265 utsname kernel_parms;
266 uname(&kernel_parms);
267 to_return = version(kernel_parms.release);
268 #elif defined(__WIN32__)
270 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
271 ::GetVersionEx(&info);
272 to_return = version(a_sprintf("%u.%u.%u.%u", basis::un_short(info.dwMajorVersion),
273 basis::un_short(info.dwMinorVersion), basis::un_short(info.dwPlatformId),
274 basis::un_short(info.dwBuildNumber)));
276 #pragma error("hmmm: need version info for this OS!")
283 const char *PATH_CONFIGURATION_FILENAME() { return "paths.ini"; }
285 astring application_configuration::application_configuration_file()
287 filename cfg_file(application_directory() + "/" + PATH_CONFIGURATION_FILENAME());
288 return cfg_file.raw();
291 const astring &application_configuration::GLOBAL_SECTION_NAME() { STATIC_STRING("Common"); }
293 const astring &application_configuration::LOGGING_FOLDER_NAME() { STATIC_STRING("LogPath"); }
297 ////const int MAX_LOG_PATH = 512;
298 // the maximum length of the entry stored for the log path.
300 astring application_configuration::get_logging_directory()
302 // new scheme is to just use the temporary directory, which can vary per user
303 // and which hopefully is always set to something usable.
304 astring def_log = environment::TMP();
305 // add logs directory underneath that.
307 // add the subdirectory for logs.
309 // now grab the current value for the name, if any.
310 astring log_dir = read_item(LOGGING_FOLDER_NAME());
311 // get the entry for the logging path.
313 // if the entry was absent, we set it.
314 //printf("did not find log dir in config file\n");
315 ini_configurator ini(application_configuration_file(),
316 ini_configurator::RETURN_ONLY,
317 ini_configurator::APPLICATION_DIRECTORY);
318 ini.store(GLOBAL_SECTION_NAME(), LOGGING_FOLDER_NAME(), def_log);
320 // they gave us something. let's replace the environment variables
321 // in their string so we resolve paths and such.
322 log_dir = parser_bits::substitute_env_vars(log_dir);
323 //printf("%s", (char *)a_sprintf("got log dir with %s value\n", log_dir.s()).s());
326 // now we make sure the directory exists.
327 filename testing(log_dir);
328 if (!testing.exists()) {
329 bool okay = directory::recursive_create(log_dir);
331 LOG(astring("failed to create logging directory: ") + log_dir);
332 // return a directory almost guaranteed to exist; best we can do in this case.
345 astring application_configuration::make_logfile_name(const astring &base_name)
346 { return get_logging_directory() + "/" + base_name; }
348 astring application_configuration::read_item(const astring &key_name)
350 filename ini_name = application_configuration_file();
351 ini_configurator ini(ini_name, ini_configurator::RETURN_ONLY,
352 ini_configurator::APPLICATION_DIRECTORY);
353 astring to_return = ini.load(GLOBAL_SECTION_NAME(), key_name, "");
355 // if the string has any length, then we process any environment
356 // variables found encoded in the value.
357 to_return = parser_bits::substitute_env_vars(to_return);