File: stringutil.c

package info (click to toggle)
skytools 2.1.8-2.2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,980 kB
  • ctags: 1,543
  • sloc: sql: 6,635; python: 6,237; ansic: 2,799; makefile: 308; sh: 268
file content (278 lines) | stat: -rw-r--r-- 6,018 bytes parent folder | download
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
/*
 * stringutil.c - some tools for string handling
 *
 * Copyright (c) 2007 Marko Kreen, Skype Technologies OÜ
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <postgres.h>
#include <lib/stringinfo.h>
#include <mb/pg_wchar.h>
#include <parser/keywords.h>
#include <utils/memutils.h>

#include "stringutil.h"

#ifndef SET_VARSIZE
#define SET_VARSIZE(x, len) VARATT_SIZEP(x) = len
#endif


StringInfo pgq_init_varbuf(void)
{
	StringInfo buf;
	buf = makeStringInfo();
	appendStringInfoString(buf, "XXXX");
	return buf;
}

Datum pgq_finish_varbuf(StringInfo buf)
{
	SET_VARSIZE(buf->data, buf->len);
	return PointerGetDatum(buf->data);
}


/*
 * Find a string in comma-separated list.
 *
 * It does not support space inside tokens.
 */
bool pgq_strlist_contains(const char *liststr, const char *str)
{
	int c, len = strlen(str);
	const char *p, *listpos = liststr;
	
loop:
	/* find string fragment, later check if actual token */
	p = strstr(listpos, str);
	if (p == NULL)
		return false;

	/* move listpos further */
	listpos = p + len;
	/* survive len=0 and avoid unneccesary compare */
	if (*listpos)
		listpos++;

	/* check previous symbol */
	if (p > liststr) {
		c = *(p - 1);
		if (!isspace(c) && c != ',')
			goto loop;
	}

	/* check following symbol */
	c = p[len];
	if (c != 0 && !isspace(c) && c != ',')
		goto loop;

	return true;
}

/*
 * quoting
 */

static int pgq_urlencode(char *dst, const uint8 *src, int srclen)
{
	static const char hextbl[] = "0123456789abcdef";
	const uint8 *end = src + srclen;
	char *p = dst;
	while (src < end) {
		unsigned c = *src++;
		if (c == ' ') {
			*p++ = '+';
		} else if ((c >= '0' && c <= '9')
			|| (c >= 'A' && c <= 'Z')
			|| (c >= 'a' && c <= 'z')
			|| c == '_' || c == '.')
		{
			*p++ = c;
		} else {
			*p++ = '%';
			*p++ = hextbl[c >> 4];
			*p++ = hextbl[c & 15];
		}
	}
	return p - dst;
}

static int pgq_quote_literal(char *dst, const uint8 *src, int srclen)
{
	const uint8 *cp1 = src, *src_end = src + srclen;
	char *cp2 = dst;
	bool is_ext = false;

	*cp2++ = '\'';
	while (cp1 < src_end) {
		int wl = pg_mblen((const char *)cp1);
		if (wl != 1) {
			while (wl-- > 0 && cp1 < src_end)
				*cp2++ = *cp1++;
			continue;
		}

		if (*cp1 == '\'') {
			*cp2++ = '\'';
		} else if (*cp1 == '\\') {
			if (!is_ext) {
				/* make room for 'E' */
				memmove(dst + 1, dst, cp2 - dst);
				*dst = 'E';
				is_ext = true;
				cp2++;
			}
			*cp2++ = '\\';
		}
		*cp2++ = *cp1++;
	}
	*cp2++ = '\'';

	return cp2 - dst;
}


/*
 * slon_quote_identifier - Quote an identifier only if needed
 */
static int
pgq_quote_ident(char *dst, const uint8 *src, int srclen)
{
	/*
	 * Can avoid quoting if ident starts with a lowercase letter or
	 * underscore and contains only lowercase letters, digits, and
	 * underscores, *and* is not any SQL keyword.  Otherwise, supply
	 * quotes.
	 */
	int                     nquotes = 0;
	bool            safe;
	const char *ptr;
	char       *optr;
	char ident[NAMEDATALEN + 1];

	/* expect idents be not bigger than NAMEDATALEN */
	if (srclen > NAMEDATALEN)
		srclen = NAMEDATALEN;
	memcpy(ident, src, srclen);
	ident[srclen] = 0;

	/*
	 * would like to use <ctype.h> macros here, but they might yield
	 * unwanted locale-specific results...
	 */
	safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');

	for (ptr = ident; *ptr; ptr++)
	{
		char            ch = *ptr;

		if ((ch >= 'a' && ch <= 'z') ||
			(ch >= '0' && ch <= '9') ||
			(ch == '_'))
			continue; /* okay */

		safe = false;
		if (ch == '"')
			nquotes++;
	}

	if (safe)
	{
		/*
		 * Check for keyword.  This test is overly strong, since many of
		 * the "keywords" known to the parser are usable as column names,
		 * but the parser doesn't provide any easy way to test for whether
		 * an identifier is safe or not... so be safe not sorry.
		 *
		 * Note: ScanKeywordLookup() does case-insensitive comparison, but
		 * that's fine, since we already know we have all-lower-case.
		 */
		if (ScanKeywordLookup(ident) != NULL)
			safe = false;
	}

	optr = dst;
	if (!safe)
		*optr++ = '"';

	for (ptr = ident; *ptr; ptr++)
	{
		char            ch = *ptr;

		if (ch == '"')
			*optr++ = '"';
		*optr++ = ch;
	}
	if (!safe)
		*optr++ = '"';

	return optr - dst;
}

static char *start_append(StringInfo buf, int alloc_len)
{
	enlargeStringInfo(buf, alloc_len);
	return buf->data + buf->len;
}

static void finish_append(StringInfo buf, int final_len)
{
	if (buf->len + final_len > buf->maxlen)
		elog(FATAL, "buffer overflow");
	buf->len += final_len;
}


static void
tbuf_encode_data(StringInfo buf,
				 const uint8 *data, int len,
				 enum PgqEncode encoding)
{
	int dlen = 0;
	char *dst;

	switch (encoding) {
	case TBUF_QUOTE_LITERAL:
		dst = start_append(buf, len * 2 + 3);
		dlen = pgq_quote_literal(dst, data, len);
		break;

	case TBUF_QUOTE_IDENT:
		dst = start_append(buf, len * 2 + 2);
		dlen = pgq_quote_ident(dst, data, len);
		break;

	case TBUF_QUOTE_URLENC:
		dst = start_append(buf, len * 3 + 2);
		dlen = pgq_urlencode(dst, data, len);
		break;

	default:
		elog(ERROR, "bad encoding");
	}

	finish_append(buf, dlen);
}

void
pgq_encode_cstring(StringInfo tbuf,
					const char *str,
					enum PgqEncode encoding)
{
	if (str == NULL)
		elog(ERROR, "tbuf_encode_cstring: NULL");
	tbuf_encode_data(tbuf, (const uint8 *)str, strlen(str), encoding);
}