File: paths.c

package info (click to toggle)
ballerburg 1.2.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 616 kB
  • sloc: ansic: 5,942; sh: 65; makefile: 10
file content (346 lines) | stat: -rw-r--r-- 8,394 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 * Ballerburg - paths.c
 *
 * Set up the various path strings.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * (http://www.gnu.org/licenses/) for more details.
 */
const char Paths_fileid[] = "Ballerburg paths.c : " __DATE__ " " __TIME__;

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "config.h"
#include "paths.h"

#if defined(WIN32) && !defined(mkdir)
#define mkdir(name,mode) mkdir(name)
#endif  /* WIN32 */

#ifdef WIN32
#define PATHSEP '\\'
#else
#define PATHSEP '/'
#endif


static char sWorkingDir[FILENAME_MAX];    /* Working directory */
static char sDataDir[FILENAME_MAX];       /* Directory where data files can be found */
static char sLocaleDir[FILENAME_MAX];     /* Directory where locale files can be found */
static char sUserHomeDir[FILENAME_MAX];   /* User's home directory ($HOME) */
static char sProgHomeDir[FILENAME_MAX];   /* Program's home directory ($HOME/.config/ballerburg/) */


/**
 * Return pointer to current working directory string
 */
const char *Paths_GetWorkingDir(void)
{
	return sWorkingDir;
}

/**
 * Return pointer to data directory string
 */
const char *Paths_GetDataDir(void)
{
	return sDataDir;
}

/**
 * Return pointer to data directory string
 */
const char *Paths_GetLocaleDir(void)
{
	return sLocaleDir;
}

/**
 * Return pointer to user's home directory string
 */
const char *Paths_GetUserHome(void)
{
	return sUserHomeDir;
}

/**
 * Return pointer to program's home directory string
 */
const char *Paths_GetProgHome(void)
{
	return sProgHomeDir;
}


/**
 * Return TRUE if file exists, is readable or writable at least and is not
 * a directory.
 */
static bool Paths_FileExists(const char *filename)
{
	struct stat buf;
	if (stat(filename, &buf) == 0 &&
	    (buf.st_mode & (S_IRUSR|S_IWUSR)) && !(buf.st_mode & S_IFDIR))
	{
		/* file points to user readable regular file */
		return true;
	}
	return false;
}


/**
 * Return TRUE if directory exists.
 */
static bool Paths_DirExists(const char *path)
{
	struct stat buf;
	return (stat(path, &buf) == 0 && S_ISDIR(buf.st_mode));
}


/**
 * Explore the PATH environment variable to see where our executable is
 * installed.
 */
static void Paths_GetExecDirFromPATH(const char *argv0, char *pExecDir, int nMaxLen)
{
	char *pPathEnv;
	char *pAct;
	char *pTmpName;
	const char *pToken;

	/* Get the PATH environment string */
	pPathEnv = getenv("PATH");
	if (!pPathEnv)
		return;
	/* Duplicate the string because strtok destroys it later */
	pPathEnv = strdup(pPathEnv);
	if (!pPathEnv)
		return;

	pTmpName = malloc(FILENAME_MAX);
	if (!pTmpName)
	{
		free(pPathEnv);
		return;
	}

	/* If there is a semicolon in the PATH, we assume it is the PATH
	 * separator token (like on Windows), otherwise we use a colon. */
	if (strchr((pPathEnv), ';'))
		pToken = ";";
	else
		pToken = ":";

	pAct = strtok (pPathEnv, pToken);
	while (pAct)
	{
		snprintf(pTmpName, FILENAME_MAX, "%s%c%s",
		         pAct, PATHSEP, argv0);
		if (Paths_FileExists(pTmpName))
		{
			/* Found the executable - so use the corresponding path: */
			strncpy(pExecDir, pAct, nMaxLen);
			pExecDir[nMaxLen-1] = 0;
			break;
		}
		pAct = strtok (0, pToken);
  	}

	free(pPathEnv);
	free(pTmpName);
}


/**
 * Locate the directory where the executable resides
 */
static char *Paths_InitExecDir(const char *argv0)
{
	char *psExecDir;  /* Path string where the executable can be found */

	/* Allocate memory for storing the path string of the executable */
	psExecDir = malloc(FILENAME_MAX);
	if (!psExecDir)
	{
		fprintf(stderr, "Out of memory (Paths_Init)\n");
		exit(-1);
	}

	/* Determine the bindir...
	 * Start with empty string, then try to use OS specific functions,
	 * and finally analyze the PATH variable if it has not been found yet. */
	psExecDir[0] = '\0';

#if defined(__linux__)
	{
		int i;
		/* On Linux, we can analyze the symlink /proc/self/exe */
		i = readlink("/proc/self/exe", psExecDir, FILENAME_MAX);
		if (i > 0)
		{
			char *p;
			psExecDir[i] = '\0';
			p = strrchr(psExecDir, '/');    /* Search last slash */
			if (p)
				*p = 0;                     /* Strip file name from path */
		}
	}
//#elif defined(WIN32) || defined(__CEGCC__)
//	/* On Windows we can use GetModuleFileName for getting the exe path */
//	GetModuleFileName(NULL, psExecDir, FILENAME_MAX);
#endif

	/* If we do not have the execdir yet, analyze argv[0] and the PATH: */
	if (psExecDir[0] == 0)
	{
		if (strchr(argv0, PATHSEP) == 0)
		{
			/* No separator in argv[0], we have to explore PATH... */
			Paths_GetExecDirFromPATH(argv0, psExecDir, FILENAME_MAX);
		}
		else
		{
			/* There was a path separator in argv[0], so let's assume a
			 * relative or absolute path to the current directory in argv[0] */
			char *p;
			strncpy(psExecDir, argv0, FILENAME_MAX);
			psExecDir[FILENAME_MAX-1] = 0;
			p = strrchr(psExecDir, PATHSEP);  /* Search last slash */
			if (p)
				*p = 0;                       /* Strip file name from path */
		}
	}

	return psExecDir;
}


/**
 * Initialize the users home directory string
 * and program's home directory (~/.config/xxx)
 */
static void Paths_InitHomeDirs(void)
{
	char *psHome;

	psHome = getenv("HOME");
	if (!psHome)
	{
		/* Windows home path? */
		psHome = getenv("HOMEPATH");
	}
	if (!psHome)
	{
		/* $HOME not set, so let's use current working dir as home */
		strcpy(sUserHomeDir, sWorkingDir);
		strcpy(sProgHomeDir, sWorkingDir);
	}
	else
	{
		strncpy(sUserHomeDir, psHome, FILENAME_MAX);
		sUserHomeDir[FILENAME_MAX-1] = 0;

		/* Try to use a .config directory in the users home directory */
		snprintf(sProgHomeDir, FILENAME_MAX, "%s%c./config/ballerburg",
		         sUserHomeDir, PATHSEP);
		if (!Paths_DirExists(sProgHomeDir))
		{
			/* Program home directory does not exists yet...
			 * ...so let's try to create it: */
			if (1 /*mkdir(sProgHomeDir, 0755) != 0*/)
			{
				/* Failed to create, so use user's home dir instead */
				strcpy(sProgHomeDir, sUserHomeDir);
			}
		}
	}
}


/**
 * Initialize the data directory string
 */
static void Paths_InitPackageDir(char *psPkgDir, const char *psRelPath,
                                 const char *psExecDir)
{
	char *pTempName;

	if (psExecDir && strlen(psExecDir) > 0)
	{
		snprintf(psPkgDir, FILENAME_MAX, "%s%c%s",
		         psExecDir, PATHSEP, psRelPath);
	}
	else
	{
		/* bindir could not be determined, let's assume the destination dir is
		 * relative to current working directory... */
		strcpy(psPkgDir, psRelPath);
	}

	pTempName = malloc(FILENAME_MAX);
	if (!pTempName)
	{
		perror("Init data dir malloc");
		return;
	}

	if (realpath(psPkgDir, pTempName) != NULL)
	{
		strncpy(psPkgDir, pTempName, FILENAME_MAX);
	}

	strcpy(psPkgDir, "/usr/share/games/ballerburg/");

	free(pTempName);
}


/**
 * Initialize directory names
 *
 * The datadir will be initialized relative to the bindir (where the executable
 * has been installed to). This means a lot of additional effort since we first
 * have to find out where the executable is. But thanks to this effort, we get
 * a relocatable package (we don't have any absolute path names in the program)!
 */
void Paths_Init(const char *argv0)
{
	char *psExecDir;  /* Path string where the executable can be found */

	/* Init working directory string */
	if (getcwd(sWorkingDir, FILENAME_MAX) == NULL)
	{
		/* This should never happen... just in case... */
		strcpy(sWorkingDir, ".");
	}

	/* Init the user's home directory string */
	Paths_InitHomeDirs();

	/* Get the directory where the executable resides */
	psExecDir = Paths_InitExecDir(argv0);

	/* Now create the package path names from the bindir path name: */
	Paths_InitPackageDir(sDataDir, BIN2DATADIR, psExecDir);
	Paths_InitPackageDir(sLocaleDir, BIN2LOCALEDIR, psExecDir);

	free(psExecDir);

	/*fprintf(stderr, " WorkingDir = %s\n DataDir = %s\n UserHomeDir = %s\n ProgHomeDir = %s\n",
	        sWorkingDir, sDataDir, sUserHomeDir, sProgHomeDir);*/
}