aboutsummaryrefslogtreecommitdiff
path: root/src/vmod_dbrw.c
blob: 9f517a84229359195ed92f7997638580e46ab109 (plain)
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/* This file is part of vmod-dbrw
   Copyright (C) 2013-2014 Sergey Poznyakoff

   Vmod-dbrw 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 3, or (at your option)
   any later version.

   Vmod-dbrw 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 for more details.

   You should have received a copy of the GNU General Public License
   along with vmod-dbrw.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "dbrw.h"
#include <stdarg.h>
#include "wordsplit.h"
#include "vrt.h"
#include "vcc_if.h"
#include "pthread.h"
#if VARNISHVERSION == 3
# include "bin/varnishd/cache.h"
# define VCL_VOID void
# define VCL_STRING const char *
# define WS_Copy(w,s,l) WS_Dup(w,s)
# define DBRW_CTX struct sess *
# define WSPTR(s) ((s)->wrk->ws)
#else
# include "bin/varnishd/cache/cache.h"
# define DBRW_CTX const struct vrt_ctx *
# define WSPTR(s) ((s)->ws)
#endif

static pthread_once_t thread_once = PTHREAD_ONCE_INIT;
static pthread_key_t thread_key;

enum {
	QDISP_NONE,
	QDISP_APPEND,
	QDISP_DISCARD
};

void
dbrw_debug(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	vsyslog(LOG_DAEMON|LOG_DEBUG, fmt, ap);
	va_end(ap);
}

void
dbrw_error(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	vsyslog(LOG_DAEMON|LOG_ERR, fmt, ap);
	va_end(ap);
}

static void
conn_free(void *f)
{
	struct dbrw_connection *p = f;
	sql_disconnect(p);
	sql_destroy(p);
}

static void
make_key()
{
	pthread_key_create(&thread_key, conn_free);
}

int
dbrw_init(struct vmod_priv *priv, const struct VCL_conf *vclconf)
{
	struct dbrw_config *conf = calloc(1, sizeof(*conf));
	if (!conf) {
		dbrw_error("not enough memory");
		abort();
	}
	priv->priv = conf;
	pthread_once(&thread_once, make_key);
	return 0;
}

static void
argv_free(char **argv)
{
	if (!argv)
		return;
	while (*argv) {
		free(*argv);
		++*argv;
	}
}

static int
is_http_status(const char *arg)
{
	if (strlen(arg) != HTTP_STATUS_LEN)
		return 0;
	return  '1' <= arg[0] && arg[0] <= '5' &&
		'0' <= arg[1] && arg[1] <= '9' &&
		'0' <= arg[2] && arg[2] <= '9';
}

static int
parse_flags(const char *arg, int *qdisp, int *flags, char status[])
{
	struct wordsplit ws;
	int rc = 0;
	int i;
	
	if (!arg)
		return 0;
	ws.ws_delim = ",";
	if (wordsplit(arg, &ws, 
		      WRDSF_NOVAR | WRDSF_NOCMD | WRDSF_QUOTE |
		      WRDSF_CESCAPES |
		      WRDSF_DELIM)) {
		dbrw_error("cannot split string `%s': %s",
			   arg, wordsplit_strerror (&ws));
		return 1;
	}

	for (i = 0; i < ws.ws_wordc; i++) {
		if (strcmp(ws.ws_wordv[i], "nocase") == 0 ||
		    strcmp(ws.ws_wordv[i], "NC") == 0)
			*flags |= REG_ICASE;
		else if (strcmp(ws.ws_wordv[i], "case") == 0)
			*flags &= ~REG_ICASE;
		else if (strcmp(ws.ws_wordv[i], "qsappend") == 0 ||
			 strcmp(ws.ws_wordv[i], "QSA") == 0)
			*qdisp = QDISP_APPEND;
		else if (strcmp(ws.ws_wordv[i], "qsdiscard") == 0 ||
			 strcmp(ws.ws_wordv[i], "QSD") == 0)
			*qdisp = QDISP_DISCARD;
		else if (strncmp(ws.ws_wordv[i], "redirect=", 9) == 0) {
			if (!is_http_status(ws.ws_wordv[i] + 9)) {
				dbrw_error("invalid status code: %s",
					   ws.ws_wordv[i] + 9);
				rc = 1;
			} else
				strncpy(status, ws.ws_wordv[i] + 9,
					HTTP_STATUS_LEN);
		} else if (strncmp(ws.ws_wordv[i], "R=", 2) == 0) {
			if (!is_http_status(ws.ws_wordv[i] + 2)) {
				dbrw_error("invalid status code: %s",
					   ws.ws_wordv[i] + 2);
				rc = 1;
			} else
				strncpy(status, ws.ws_wordv[i] + 2,
					HTTP_STATUS_LEN);
		} else {
				dbrw_error("unrecognized flag: %s", ws.ws_wordv[i]);
			rc = 1;
		}
	}		   
	
	wordsplit_free(&ws);
	return rc;
}


/* Configure the module.
   BACKEND  - "mysql" or "pgsql"
   PARAM    - VAR=VALUE*:
                 db=S                  
		 port=N
		 socket=S
		 user=S
		 password=S
		 options=S
		 debug=N
   QUERY    - Query to obtain the redirection target   
 */
VCL_VOID
vmod_config(DBRW_CTX ctx, struct vmod_priv *priv,
	    VCL_STRING bkname, VCL_STRING param, VCL_STRING query)
{
	char *s;
	struct wordsplit ws;
	struct dbrw_config *conf = priv->priv;
	
	ws.ws_delim = ";";
	if (wordsplit(param, &ws, 
		      WRDSF_NOVAR | WRDSF_NOCMD | WRDSF_QUOTE |
		      WRDSF_CESCAPES |
		      WRDSF_DELIM)) {
		dbrw_error("cannot split string `%s': %s",
			      param, wordsplit_strerror (&ws));
		return;
	}
	conf->param = ws.ws_wordv;
	ws.ws_wordv = NULL;
	ws.ws_wordc = 0;
	wordsplit_free(&ws);

	conf->query = strdup(query);
	if (!conf->query) {
		dbrw_error("not enough memory");
		argv_free(conf->param);
		conf->param = NULL;
		return;
	}

	/* Select backend */
	conf->backend = dbrw_backend_select(bkname);
	if (!conf->backend) {
		dbrw_error("unsupported backend: %s", bkname);
		argv_free(conf->param);
		free(conf->query);
		conf->query = NULL;
		conf->param = NULL;
		return;
	}

	s = findparam(conf->param, "debug");
	conf->debug_level = s ? atoi(s) : 0;

	conf->qdisp = QDISP_NONE;
	conf->regflags = REG_EXTENDED;
	conf->status[0] = 0;

	s = findparam(conf->param, "flags");
	if (s && parse_flags(s, &conf->qdisp, &conf->regflags, conf->status)) {
		argv_free(conf->param);
		free(conf->query);
		conf->query = NULL;
		conf->param = NULL;
	}
}

static char *
expand_backref(DBRW_CTX ctx, const char *str, const char *val,
	       size_t matchcount, regmatch_t *matches, char *qry)
{
	unsigned u;
        char *b, *p;
	
        u = WS_Reserve(WSPTR(ctx), 0);
        p = b = WSPTR(ctx)->f;

	while (*val) {
		if (u == 0) {
			WS_Release(WSPTR(ctx), 0);
			return NULL;
		}
		if (*val == '\\' || *val == '$') {
			if (val[1] >= 0 && val[1] <= '9') {
				int n = val[1] - '0';
				if (n < matchcount) {
					size_t len;

					len = matches[n].rm_eo -
						  matches[n].rm_so;

					if (len > u) {
						WS_Release(WSPTR(ctx), 0);
						return NULL;
					}

					memcpy(p, str + matches[n].rm_so, len);

					p += len;
					u -= len;
					val += 2;
					continue;
				}
			} else if (*val == '\\' && val[1]) {
				*p++ = val[1];
				u--;
				val += 2;
				continue;
			}
		}

		*p++ = *val++;
		u--;
	}

	if (qry) {
		size_t len = strlen(qry);
		if (len + 1 >= u)  {
			WS_Release(WSPTR(ctx), 0);
			return NULL;
		}
		if (strchr(b, '?'))
			*p++ = '&';
		else
			*p++ = '?';
		memcpy(p, qry, len);
		p += len;
		u -= len;
	}
	
	if (u == 0) {
		WS_Release(WSPTR(ctx), 0);
		return NULL;
	}
	*p++ = 0;
	
	WS_ReleaseP(WSPTR(ctx), p);

	return b;
}

#define ISEMPTY(s) ((s) == NULL || (s)[0] == 0)

static void
dbrw_sethdr(DBRW_CTX ctx, int where, const char *what, const char *value)
{
#if VARNISHVERSION == 3
	VRT_SetHdr(ctx, where, what, value, vrt_magic_string_end);
#else
	struct gethdr_s s = { where, what };
	VRT_SetHdr(ctx, &s, value, vrt_magic_string_end);
#endif
}	

static char *
findmatch(DBRW_CTX ctx, struct dbrw_connection *conn, char **param)
{
	unsigned i;
	unsigned nt, nf;
	char *res;
	struct wordsplit ws;
	int wsflags = WRDSF_NOCMD | WRDSF_QUOTE |
		      WRDSF_NOSPLIT |
		      WRDSF_ENV | WRDSF_UNDEF;
	
	if ((nt = sql_num_tuples(conn)) == 0 ||
	    (nf = sql_num_fields(conn)) == 0)
		return NULL;

	debug(conn->conf, 2, ("query returned %u tuples, %u columns", nt, nf));
	
	if (nf < 3)
		return WS_Copy(WSPTR(ctx), sql_get_column(conn, 0, 0), -1);

	/* Three or four fields:
	     result
	     pattern
	     value
	     [flags]
	*/	     
	ws.ws_env = (const char **)param;
	res = NULL;
	for (i = 0; i < nt; i++) {
		const char *pat = sql_get_column(conn, i, 1);
		const char *val = sql_get_column(conn, i, 2);
		regex_t re;
		int rc;
		size_t matchcount;     /* Number of used entries in matches */
		int rflags = conn->conf->regflags;
		char status[HTTP_STATUS_LEN+1];
		int qdisp = conn->conf->qdisp;
		char *qry = NULL;

		if (ISEMPTY(pat)) {
			res = WS_Copy(WSPTR(ctx), sql_get_column(conn, i, 0), -1);
			break;
		}
		
		debug(conn->conf, 1, ("considering \"%s\" ~ \"%s\"", pat, val));
		if (wordsplit(val, &ws, wsflags)) {
			dbrw_error("cannot expand string `%s': %s",
				      val, wordsplit_strerror(&ws));
			continue;
		}
		wsflags |= WRDSF_REUSE;

		val = ws.ws_wordv[0];
		debug(conn->conf, 1, ("expanded to \"%s\" ~ \"%s\"",
				      pat, val));

		strcpy(status, conn->conf->status);
		if (nf == 4) {
			if (parse_flags(sql_get_column(conn, i, 3),
					&qdisp, &rflags, status))
				continue;
		}
		
		switch (qdisp) {
		case QDISP_NONE:
			break;
		case QDISP_APPEND:
			qry = strchr(val, '?');
			if (qry)
				*qry++ = 0;
			break;
		case QDISP_DISCARD:
			qry = strchr(val, '?');
			if (qry) {
				debug(conn->conf, 1,
				      ("discarding query part \"%s\"", qry));
				*qry = 0;
				qry = NULL;
			}
		}
			
		rc = regcomp(&re, pat, rflags);
		if (rc) {
			char errbuf[512];

			regerror(rc, &re, errbuf, sizeof(errbuf));
			dbrw_error("cannot compile regexp \"%s\": %s",
				      pat, errbuf);
			continue;
		}

		matchcount = re.re_nsub + 1;
		if (conn->matchsize < matchcount) {
			void *p = realloc(conn->matches,
					sizeof(conn->matches[0]) * matchcount);
			if (!p) {
				dbrw_error("not enough memory");
				regfree(&re);
				continue;
			}
			conn->matches = p;
			conn->matchsize = matchcount;
		}

		rc = regexec(&re, val, matchcount, conn->matches, 0);
		
		if (rc == 0)
			res = expand_backref(ctx, val,
					     sql_get_column(conn, i, 0),
					     matchcount, conn->matches, qry);

		regfree(&re);
		if (rc == 0) {
			debug(conn->conf, 1, ("match"));
			if (status[0]) {
				debug(conn->conf, 1,
				      ("setting status %s", status));
				dbrw_sethdr(ctx, HDR_REQ, 
					    "\023X-VMOD-DBRW-Status:",
					    status);
			}
			break;
		}
	}

	if (wsflags & WRDSF_REUSE)
		wordsplit_free(&ws);

	return res;
}

static struct dbrw_connection *
get_connection(struct dbrw_config *conf)
{
	struct dbrw_connection *cp = pthread_getspecific(thread_key);

	if (!cp) {
		cp = malloc(sizeof(*cp));
		if (!cp)
			return NULL;
		cp->state = state_init;
		cp->conf = conf;
		cp->data = NULL;
		cp->matches = NULL;
		cp->matchsize = 0;

		if (sql_init(cp)) {
			free(cp);
			return NULL;
		}
		if (pthread_setspecific(thread_key, cp)) {
			dbrw_error("cannot set thread-specific data");
			sql_destroy(cp);
			free(cp);
			return NULL;
		}
	}
	return cp;
}

VCL_STRING
vmod_rewrite(DBRW_CTX ctx, struct vmod_priv *priv, VCL_STRING arg)
{
	struct dbrw_config *conf = priv->priv;
	struct dbrw_connection *cp;
	struct wordsplit ws, wsenv;
	int i, rc;
	char *res;

	debug(conf, 2, ("vmod_rewrite(%s) begin", arg));
	if (!conf || !conf->query) {
		debug(conf, 2, ("vmod_rewrite: not configured; exiting"));
		return NULL;
	}
	cp = get_connection(conf);
	if (!cp) {
		debug(conf, 2, ("vmod_rewrite: no private data; exiting"));
		return NULL;
	}
	
	if (sql_connect(cp) || cp->state != state_connected)
		return NULL;

	debug(conf, 2, ("vmod_rewrite: splitting arg"));
	wsenv.ws_delim = ";";
	if (wordsplit(arg, &wsenv, WRDSF_NOVAR|WRDSF_NOCMD|WRDSF_DELIM)) {
		dbrw_error("cannot split string `%s': %s",
			      arg, wordsplit_strerror(&wsenv));
		return NULL;
	}

	if (conf->backend->sql_escape) {
		debug(conf, 2, ("escaping variables"));
		for (i = 0; i < wsenv.ws_wordc; i++) {
			char *p = sql_escape(cp, wsenv.ws_wordv[i]);
			if (!p) {
				dbrw_error("cannot expand argument");
				wordsplit_free(&wsenv);
				return NULL;
			}
			free(wsenv.ws_wordv[i]);
			wsenv.ws_wordv[i] = p;
			debug(conf, 3, ("%d: %s",i,p));
		}
	}

	debug(conf, 2, ("expanding query"));
	ws.ws_env = (const char **)wsenv.ws_wordv;
	rc = wordsplit(conf->query, &ws,
		       WRDSF_NOCMD | WRDSF_QUOTE |
		       WRDSF_NOSPLIT |
		       WRDSF_ENV | WRDSF_UNDEF);
	if (rc) {
		dbrw_error("cannot expand query `%s': %s",
			      conf->query, wordsplit_strerror(&ws));
		wordsplit_free(&wsenv);
		return NULL;
	}

	rc = sql_query(cp, ws.ws_wordv[0]);
	wordsplit_free(&ws);

	if (rc) {
		debug(conf, 1, ("vmod_rewrite: query failed"));
		wordsplit_free(&wsenv);
		return NULL;
	}
	
	res = findmatch(ctx, cp, wsenv.ws_wordv);
	wordsplit_free(&wsenv);

	sql_free_result(cp);

	debug(conf, 1, ("vmod_rewrite: res=%s", res ? res : "(NULL)"));
	
	return res;
}

Return to:

Send suggestions and report system problems to the System administrator.