File: strutil.c

package info (click to toggle)
gentoo 0.11.46-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 5,648 kB
  • ctags: 4,313
  • sloc: ansic: 33,912; sh: 3,903; makefile: 649; yacc: 316; sed: 16
file content (422 lines) | stat: -rw-r--r-- 12,366 bytes parent folder | download | duplicates (4)
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*
** 1998-08-02 -	This module holds various utility functions sharing one common trait:
**		they all deal with character strings in one way or another.
*/

#include "gentoo.h"

#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "sizeutil.h"
#include "strutil.h"

/* ----------------------------------------------------------------------------------------- */

/* 1998-08-02 -	Copy at most <n> bytes from <src> to <dst>, including the terminating
**		'\0'-byte. If <src> is longer than <n-1>, it will be truncated with a
**		'\0'-byte at position n-1. Example: stu_strncpy(b, "string", 1) would
**		put a '\0'-byte at b[0] and return. Basically, think of the <n> as a
**		limiter on the number of bytes at <dst> we're allowed to touch, and
**		then fit a string-copying idea on top of that. :^) Works for me, and a
**		lot better than the standard strncpy(), too. Returns <dst>.
*/
gchar * stu_strncpy(gchar *dst, const gchar *src, gssize n)
{
	gchar	*ret = dst;

	if(dst && !src && n)
		*dst = '\0';
	else if(dst && src && (n >= 1))
	{
		for(n--; n > 0 && *src != '\0'; n--)
			*dst++ = *src++;
		*dst = '\0';
	}
	return ret;
}

/* ----------------------------------------------------------------------------------------- */

/* 2002-04-28 -	Create a textual representation of <n>, with <tick> inserted every
**		3rd digit (counting from the right) into <buf>. Returns pointer to
**		first digit.
** NOTE NOTE	That <buf> pointer should point at one position past where the **last**
**		character of the tickified number is to appear. This is for speed reasons.
*/
gchar * stu_tickify(gchar *buf, guint64 n, gchar tick)
{
	register gint	cnt = 0;

	do
	{
		if(tick && cnt == 3)
			*--buf = tick, cnt = 0;
		*--buf = '0' + n % 10;
		n /= 10;
		cnt++;
	} while(n);
	return buf;
}

/* ----------------------------------------------------------------------------------------- */

/* 1999-09-11 -	Return pointer to first occurance of <c> in <str>, disregarding case.
**		If <c> cannot be found, NULL is returned. The string is not modified.
*/
const gchar * stu_strcasechr(const gchar *str, gchar c)
{
	for(c = toupper((guchar) c); *str; str++)
	{
		if(toupper((guchar) *str) == c)
			return str;
	}
	return NULL;
}

/* 1998-09-06 -	This function has a silly name. It is used to get a pointer to the
**		last occurance of the character <c> in the string <str>, ignoring case.
**		It returns such a pointer, or NULL if <c> doesn't appear in <str>. The
**		string being searched is not modified.
*/
const gchar * stu_strcaserchr(const gchar *str, gchar c)
{
	const gchar	*ptr;
	gsize		len;

	if((len = strlen(str)) == 0)
		return NULL;

	for(c = toupper((guchar) c), ptr = str + len - 1; ptr >= str; ptr--)
		if(toupper((guchar) *ptr) == c)
			return ptr;

	return NULL;
}

/* 1998-08-02 -	Check if <string> ends with the suffix <suffix>. Note that this is fairly
**		general; it does not assume (or require) <suffix> to begin with a period
**		or any some such. If you want it to, include the period yourself. Returns
**		1 if there is indeed a suffix match, 0 otherwise.
** 1998-09-13 -	Now handles suffixes of the ".tar.gz" kind, where the initial letter to
**		match is NOT the last letter of its kind in the string. This made it a tad
**		slower, sure, but hey.
*/
gboolean stu_has_suffix(const gchar *string, const gchar *suffix)
{
	gssize	len, sl;

	if((string == NULL) || (suffix == NULL))
		return FALSE;

	len = strlen(string);
	sl  = strlen(suffix);

	if(len < sl)		/* String shorter than suffix? */
		return FALSE;

	return g_strcasecmp(string + len - sl, suffix) == 0;
}

/* ----------------------------------------------------------------------------------------- */

/* Attempt to find <string> in <vector> of strings. Returns vector index, or <default>. */
gint stu_strcmp_vector(const gchar *string, const gchar **vector, gsize vector_size, gint def)
{
	gsize	i;

	for(i = 0; vector[i] && i < vector_size; i++)
	{
		if(strcmp(string, vector[i]) == 0)
			return (gint) i;
	}
	return def;
}

/* ----------------------------------------------------------------------------------------- */

/* 1998-08-30 -	Core glob->RE translator. Returns a pointer to a (dynamically allocated)
**		piece of memory holding the RE. When done with that, please g_free() it.
*/
gchar * stu_glob_to_re(const gchar *glob)
{
	GString		*re;
	gchar		here, *ret;
	const gchar	*ptr, *end;

	if((re = g_string_new(NULL)) == NULL)
		return NULL;

	for(ptr = glob; *ptr != '\0'; ptr++)
	{
		here = *ptr;
		if(here == '[' && ptr[1] != ']')		/* Character set begins? */
		{
			if((end = strchr(ptr + 1, ']')) != NULL)
			{
				for(; ptr <= end; ptr++)
					g_string_append_c(re, *ptr);
				ptr--;
			}
		}
		else
		{
			switch(here)
			{
				case '.':
					g_string_append(re, "\\.");
					break;
				case '*':
					g_string_append(re, ".*");
					break;
				case '+':
					g_string_append(re, "\\+");
					break;
				case '?':
					g_string_append_c(re, '.');
					break;
				default:
					g_string_append_c(re, here);
			}
		}
	}
	ret = re->str;
	g_string_free(re, FALSE);	/* Keeps the buffer. */
	return ret;
}

/* 1998-08-30 -	Translate a glob pattern into a System V8 regular expression. Thanks to the
**		magic of GStrings, it will look to the caller as if the string is simply
**		replaced by the translation. This code was moved from the good 'ol cmd_select
**		module, since I wanted glob->RE translation in other places, too (types).
**		This routine doesn't exactly fit in among the other, but since it deals with
**		strings, I thought it could live here at least for a while.
*/
void stu_gstring_glob_to_re(GString *glob)
{
	gchar	*re;

	if((re = stu_glob_to_re(glob->str)) != NULL)
	{
		g_string_assign(glob, re);
		g_free(re);
	}
}

/* ----------------------------------------------------------------------------------------- */

/* 1998-09-19 -	Convert the protection <mode> to a (more) human-readable form stored at <buf>.
**		Will not use more than <max> bytes of <buf>. Returns <buf>, or NULL on failure.
** 1999-01-05 -	Finally sat down and experimentally deduced the way GNU 'ls' formats its mode
**		strings, and did something similar here.
** 2000-09-14 -	g_snprintf() is not scanf(). Remembered that.
*/
gchar * stu_mode_to_text(gchar *buf, gsize buf_max, mode_t mode)
{
	gchar	*grp[] = { "---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx" };
	gint	u, g, o;

	if(buf_max < 12)			/* A lazy size limitation. */
		return NULL;

	u = (mode & S_IRWXU) >> 6;
	g = (mode & S_IRWXG) >> 3;
	o = (mode & S_IRWXO);
	if(g_snprintf(buf, buf_max, "-%s%s%s", grp[u], grp[g], grp[o]) < 0)
		return NULL;

	/* Set the left-most character according to the file's intrinsic type. */
	if(S_ISLNK(mode))
		buf[0] = 'l';
	else if(S_ISDIR(mode))
		buf[0] = 'd';
	else if(S_ISBLK(mode))
		buf[0] = 'b';
	else if(S_ISCHR(mode))
		buf[0] = 'c';
	else if(S_ISFIFO(mode))
		buf[0] = 'p';
	else if(S_ISSOCK(mode))		/* This is just a guess... */
		buf[0] = 's';

	/* This is magic until you understand how it works. The trick seems to be that one
	** bit (e.g. "SETUID") is displayed on top of another bit (in this case user read)
	** by changing that character either to 'S' (if it was not set) or 's' (if set).
	** AFAIK, this is not documented anywhere (except perhaps in ls's source).
	*/
	if(mode & S_ISVTX)		/* Sticky bit set? This is not POSIX... */
		buf[9] = (buf[9] == '-') ? 'T' : 't';
	if(mode & S_ISGID)		/* Set GID bit set? */
		buf[6] = (buf[6] == '-') ? 'S' : 's';
	if(mode & S_ISUID)		/* Set UID bit set? */
		buf[3] = (buf[3] == '-') ? 'S' : 's';

	return buf;
}

/* ----------------------------------------------------------------------------------------- */

/* 1998-10-07 -	Scan a string from <def>, and put a pointer to a dynamically allocated version
**		of it into <str>. The string should be delimited by double quotes. Characters
**		(such as commas and whitespace) between strings are ignored. Returns a pointer
**		to the beginning of the next string (suitable for a repeat call), or NULL when
**		no more strings were found.
** 1999-02-24 -	Added support for backslash escaping. Might be useful when this routine is used
**		to scan strings which are then parsed by the command argument stuff. Or, you
**		could just use single quotes of course...
*/
const gchar * stu_scan_string(const gchar *def, const gchar **str)
{
	GString	*tmp;

	if((def == NULL) || (str == NULL))
		return NULL;

	while(*def && *def != '"')
		def++;

	if(*def == '"')			/* Beginning of string actually found? */
	{
		def++;
		if((tmp = g_string_new(NULL)) != NULL)
		{
			while(*def && *def != '"')
			{
				if(*def == '\\')
				{
					def++;
					if(*def == '\0')
						break;
				}
				g_string_append_c(tmp, *def++);
			}
			if(*def == '"')		/* Closing quote here, too? */
			{
				*str = tmp->str;
				g_string_free(tmp, FALSE);				
				return ++def;	/* Then return with an OK status. */
			}
			g_string_free(tmp, TRUE);
		}
	}
	return NULL;
}

/* ----------------------------------------------------------------------------------------- */

/* 1999-02-24 -	Compute the length and content of the first word at <str>. Knows about
**		quoting and backslash escapes. Stores word at <store>. Will typically be
**		run twice on the same input, since you can't know how much space is going
**		to be needed without running it once (with store == NULL).
**		Quoting rules:	A word can contain whitespace (space, tab) only if quoted.
**				Double (") and single (') quotes can both be used, and have
**				the same "power". One quotes the other, so "'" and '"' are
**				both legal 1-character words. To include the quote used for
**				a word IN the word, it must be backslash escaped: "\"" is
**				the 1-character word ".
**		Returns pointer to first character after word, or NULL if there are no more
**		words. Stores word length at <len> (if non-NULL).
*/
const gchar * stu_word_length(const gchar *str, gsize *len, gchar *store)
{
	gchar	quote = 0, here;
	gsize	l = 0;

	if(str == NULL)
		return NULL;

	while(*str && isspace((guchar) *str))		/* Skip inter-word spaces. */
		str++;

	if(*str == '\0')
		return NULL;
	for(; *str && !(quote == 0 && isspace((guchar) *str)); l++)
	{
		if((here = *str) == '\\')	/* Backslash escapade? */
		{
			here = *++str;
			if(here == '\0')	/* At end of string? */
				break;
		}
		else if(here == '\'' || here == '"')
		{
			if(quote == 0 || quote == here)	/* Ignore "other" quote. */
			{
				if(quote == here)
					quote = 0;
				else
					quote = here;
				str++;
				l--;			/* Don't count the quote. */
				continue;		/* Avoid storing the quote. */
			}
		}
		if(store != NULL)
			*store++ = here;
		str++;
	}
	if(quote != '\0' && *str == quote)	/* Skip ending quote. */
		str++;
	if(len != NULL)
		*len = l;

	return str;
}

/* 1999-02-24 -	This takes a string intended as a shell command and splits it into a word-
**		vector as used by exec() functions. Think argv[]. Handles some quoting and
**		escaped characters, too. The returned vector will be NULL-terminated, and
**		can be freed by a single call to g_free().
*/
gchar ** stu_split_args(const gchar *argstring)
{
	gsize		wlen;
	gint		wtotlen, wnum, i;
	const gchar	*ptr = argstring;
	gchar		**argv, *store;

	for(wnum = wlen = wtotlen = 0; (ptr = stu_word_length(ptr, &wlen, NULL)) != NULL; wnum++, wtotlen += wlen + 1)
		;

	if(wnum == 0)		/* Nothing found? */
		return NULL;

	argv  = g_malloc((wnum + 1) * sizeof *argv + wtotlen);
	store = (gchar *) argv + (wnum + 1) * sizeof *argv;
	for(ptr = (gchar *) argstring, i = 0; (ptr = stu_word_length(ptr, &wlen, store)) != NULL; i++)
	{
		argv[i] = store;
		store[wlen] = '\0';
		store += (wlen + 1);
	}
	argv[i] = NULL;

	return argv;
}

/* ----------------------------------------------------------------------------------------- */

/* 2003-11-25 -	Create internal (static, be careful!) version of <string> where certain
**		characters have been escaped by backslashes, and return pointer to it.
*/
const gchar * stu_escape(const gchar *string)
{
	static GString	*str = NULL;

	if(str == NULL)
		str = g_string_new("");
	else
		g_string_truncate(str, 0);
	for(; *string; string++)
	{
		if(*string == '"' || *string == '\'' || *string == '\\')
			g_string_append_c(str, '\\');
		g_string_append_c(str, *string);
	}
	return str->str;
}