summaryrefslogtreecommitdiffabout
path: root/src/variable.c
blob: 667cfc092eb943767df7d591f7e7f5b9a5805a88 (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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
/* This file is part of vmod-tbf
   Copyright (C) 2013-2015 Sergey Poznyakoff
  
   Vmod-tbf 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-tbf 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-tbf.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdlib.h>
#include <stdarg.h>
#include <syslog.h>
#include <ctype.h>
#include <pcre.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 VCL_REAL double
# define VCL_DURATION double
# define WS_Copy(w,s,l) WS_Dup(w,s)
# define VARIABLE_CTX struct sess *
# define WSPTR(s) ((s)->wrk->ws)
#else
# include "bin/varnishd/cache/cache.h"
# define VARIABLE_CTX const struct vrt_ctx *
# define WSPTR(s) ((s)->ws)
#endif

/* |hash_size| defines a sequence of symbol table sizes. These are prime
   numbers, each of which is approximately twice its predecessor. */

static unsigned int hash_size[] = {
	7, 17, 37, 101, 229, 487, 1009, 2039, 4091, 8191, 16411
};

/* max_rehash keeps the number of entries in |hash_size| table. */
static unsigned int max_rehash = sizeof(hash_size) / sizeof(hash_size[0]);

enum variable_type {
	variable_unset,
	variable_string,
	variable_int,
	variable_real,
	variable_duration
};

static char *typestr[] = {
	"UNSET",
	"STRING",
	"INT",
	"REAL",
	"DURATION"
};

union value {
	char *s;
	int i;
	double r;
	double d;
};

struct variable {
	char *name;
	enum variable_type type;
	union value v;
};

struct symtab {
	uint32_t vxid;
	unsigned int hash_num;  /* Index to hash_size table */
	struct variable **tab;
};

static struct variable *
var_alloc(const char *name)
{
	struct variable *ent;
	
	ent = malloc(sizeof(struct variable));
	AN(ent);
	ent->name = strdup(name);
	ent->type = variable_unset;
	AN(ent->name);
	return ent;
}

static unsigned
hash_string(const char *name, unsigned long hashsize)
{
	unsigned i;
	
	for (i = 0; *name; name++) {
		i <<= 1;
		i ^= *(unsigned char*) name;
	}
	return i % hashsize;
}

static unsigned
var_hash(struct variable *var, unsigned long hashsize)
{
	return hash_string(var->name, hashsize);
}

static void
var_free(struct variable *var)
{
	free(var->name);
	if (var->type == variable_string)
		free(var->v.s);
	free(var);
}		

static unsigned
symtab_insert_pos(struct symtab *st, struct variable *elt)
{
	unsigned i;
	unsigned pos = var_hash(elt, hash_size[st->hash_num]);
	
	for (i = pos; st->tab[i];) {
		if (++i >= hash_size[st->hash_num])
			i = 0;
		if (i == pos)
			abort();
	}
	return i;
}

static int
symtab_rehash(struct symtab *st)
{
	struct variable **old_tab = st->tab;
	struct variable **new_tab;
	unsigned int i;
	unsigned int hash_num = st->hash_num + 1;
	
	if (hash_num >= max_rehash)
		return E2BIG;

	new_tab = calloc(hash_size[hash_num], sizeof(*new_tab));
	AN(new_tab);
	st->tab = new_tab;
	if (old_tab) {
		st->hash_num = hash_num;
		for (i = 0; i < hash_size[hash_num-1]; i++) {
			struct variable *elt = old_tab[i];
			if (elt->name) {
				unsigned n = symtab_insert_pos(st, elt);
				new_tab[n] = elt;
			}
		}
		free(old_tab);
	}
	return 0;
}

static int
symtab_remove(struct symtab *st, const char *name)
{
	unsigned int pos, i, j, r;
	struct variable *entry;
	
	pos = hash_string(name, hash_size[st->hash_num]);
	for (i = pos; (entry = st->tab[i]);) {
		if (strcmp(entry->name, name) == 0)
			break;
		if (++i >= hash_size[st->hash_num])
			i = 0;
		if (i == pos)
			return ENOENT;
	}
	
	var_free(entry);

	for (;;) {
		st->tab[i] = NULL;
		j = i;

		do {
			if (++i >= hash_size[st->hash_num])
				i = 0;
			if (!st->tab[i])
				return 0;
			r = hash_string(st->tab[i]->name, hash_size[st->hash_num]);
		}
		while ((j < r && r <= i)
		       || (i < j && j < r) || (r <= i && i < j));
		st->tab[j] = st->tab[i];
	}
	return 0;
}

static int
symtab_get_index(unsigned *idx, struct symtab *st,
		 const char *name, int *install)
{
	int rc;
	unsigned i, pos;
	struct variable *elem;
  
	if (!st->tab) {
		if (install) {
			rc = symtab_rehash(st);
			if (rc)
				return rc;
		} else
			return ENOENT;
	}

	pos = hash_string(name, hash_size[st->hash_num]);

	for (i = pos; (elem = st->tab[i]);) {
		if (strcmp(elem->name, name) == 0) {
			if (install)
				*install = 0;
			*idx = i; 
			return 0;
		}
      
		if (++i >= hash_size[st->hash_num])
			i = 0;
		if (i == pos)
			break;
	}

	if (!install)
		return ENOENT;
  
	if (!elem) {
		*install = 1;
		*idx = i;
		return 0;
	}

	if ((rc = symtab_rehash(st)) != 0)
		return rc;

	return symtab_get_index(idx, st, name, install);
}

static struct variable *
symtab_lookup_or_install(struct symtab *st, const char *name, int *install)
{
	unsigned i;
	int rc = symtab_get_index(&i, st, name, install);
	if (rc == 0) {
		if (install && *install == 1) {
			struct variable *ent = var_alloc(name);
			if (!ent) {
				errno = ENOMEM;
				return NULL;
			}
			st->tab[i] = ent;
			return ent;
		} else
			return st->tab[i];
	}
	errno = rc;
	return NULL;
}

static void
symtab_clear(struct symtab *st)
{
	unsigned i, hs;
  
	if (!st || !st->tab)
		return;

	hs = hash_size[st->hash_num];
	for (i = 0; i < hs; i++) {
		struct variable *elem = st->tab[i];
		if (elem) {
			var_free(elem);
			st->tab[i] = NULL;
		}
	}
}

static struct symtab *
symtab_create()
{
	struct symtab *st = calloc(1, sizeof(*st));
	AN(st);
	st->tab = calloc(hash_size[st->hash_num], sizeof(*st->tab));
	AN(st->tab);
	return st;
}

static void
symtab_free(struct symtab *st)
{
	if (st) {
		symtab_clear(st);
		free(st->tab);
		free(st);
	}
}


static struct symtab **symtabv;
static size_t symtabc;
static pthread_mutex_t symtab_mtx = PTHREAD_MUTEX_INITIALIZER;

static struct symtab *global_symtab;
static pthread_mutex_t global_mtx = PTHREAD_MUTEX_INITIALIZER;

VCL_VOID
vmod_global_set(VARIABLE_CTX ctx, VCL_STRING name, VCL_STRING value)
{
	struct variable *var;
	int inst;
	
	AZ(pthread_mutex_lock(&global_mtx));
	if (!global_symtab)
		global_symtab = symtab_create();
	if (!value)
		symtab_remove(global_symtab, name);
	else {
		inst = 1;
		var = symtab_lookup_or_install(global_symtab, name, &inst);
		if (!inst && var->type == variable_string)
			free(var->v.s);
		var->type = variable_string;
		var->v.s = strdup(value);
		AN(var->v.s);
	}
	AZ(pthread_mutex_unlock(&global_mtx));	
}

VCL_STRING
vmod_global_get(VARIABLE_CTX ctx, VCL_STRING name)
{
	char *s;
	struct variable *var;
	
	AZ(pthread_mutex_lock(&global_mtx));
	if (!global_symtab)
		global_symtab = symtab_create();
	var = symtab_lookup_or_install(global_symtab, name, NULL);
	if (var && var->type == variable_string) {
		s = WS_Copy(ctx->ws, var->v.s, -1);
		AN(s);
	} else
		s = NULL;
	AZ(pthread_mutex_unlock(&global_mtx));
	return s;
}

static struct symtab *
get_symtab(VARIABLE_CTX ctx)
{
	struct symtab *st;
	int fd = ctx->req->sp->fd;
	AZ(pthread_mutex_lock(&symtab_mtx));
	if (symtabc <= fd) {
		size_t n = fd + 1;
		symtabv = realloc(symtabv, n * sizeof(symtabv[0]));
		while (symtabc < n)
			symtabv[symtabc++] = NULL;
	}
	if (!symtabv[fd])
		symtabv[fd] = symtab_create();
	st = symtabv[fd];
	if (st->vxid != ctx->req->sp->vxid)
		symtab_clear(st);
	st->vxid = ctx->req->sp->vxid;
	AZ(pthread_mutex_unlock(&symtab_mtx));
	return st;
}

#define getvar(vt, name) symtab_lookup_or_install(vt, name, NULL)

struct variable *
defvar(struct symtab *vt, const char *name, enum variable_type t,
       union value *val)
{
	int inst = 1;
	struct variable *var = symtab_lookup_or_install(vt, name, &inst);
	if (!inst && var->type == variable_string)
		free(var->v.s);
	if (t != variable_unset && val) {
		var->type = t;
		var->v = *val;
	} else
		var->type = variable_unset;
	return var;
}

VCL_VOID
vmod_clear(VARIABLE_CTX ctx)
{
	symtab_clear(get_symtab(ctx));
}

VCL_STRING
vmod_get_string(VARIABLE_CTX ctx, VCL_STRING name)
{
	struct variable *var = getvar(get_symtab(ctx), name);
	if (var && var->type == variable_string)
		return var->v.s;
	return NULL;
}

VCL_VOID
vmod_set_string(VARIABLE_CTX ctx, VCL_STRING name, VCL_STRING value)
{
	struct symtab *vt = get_symtab(ctx);
	struct variable *var = defvar(vt, name, variable_unset, NULL);
	var->type = variable_string;
	var->v.s = strdup(value ? value : "");
	AN(var->v.s);
}

VCL_STRING
vmod_get(VARIABLE_CTX ctx, VCL_STRING name)
{
	return vmod_get_string(ctx, name);
}

VCL_VOID
vmod_set(VARIABLE_CTX ctx, VCL_STRING name, VCL_STRING value)
{
	vmod_set_string(ctx, name, value);
}

#define __cat__(a,b) a ## b
#define DEFGET(r_type, vcl_type, memb)	                            \
vcl_type					                    \
__cat__(vmod_get_,r_type)(VARIABLE_CTX ctx, VCL_STRING name)	    \
{							            \
	struct variable *var = getvar(get_symtab(ctx), name);	    \
	if (var && var->type == __cat__(variable_,r_type))          \
		return var->v.memb;                                 \
	return 0;                                                   \
}

#define DEFSET(r_type, vcl_type, memb)                              \
VCL_VOID                                                            \
__cat__(vmod_set_,r_type)(VARIABLE_CTX ctx, VCL_STRING name,        \
			  vcl_type value)			    \
{                                                                   \
	struct symtab *vt = get_symtab(ctx);			       \
	struct variable *var = defvar(vt, name, variable_unset, NULL); \
	var->type = __cat__(variable_,r_type);                      \
	var->v.memb = value;                                        \
}

#define DEF(name, vcl_type, memb)                                   \
DEFGET(name, vcl_type, memb)                                        \
DEFSET(name, vcl_type, memb)

DEF(int, VCL_INT, i)
DEF(real, VCL_REAL, r)
DEF(duration, VCL_DURATION, d)

VCL_INT
vmod_defined(VARIABLE_CTX ctx, VCL_STRING name)
{
	return !!getvar(get_symtab(ctx), name);
}

VCL_STRING
vmod_type_of(VARIABLE_CTX ctx, VCL_STRING name)
{
	struct variable *var = getvar(get_symtab(ctx), name);
	return typestr[var ? var->type : variable_unset];
}

VCL_VOID
vmod_undef(VARIABLE_CTX ctx, VCL_STRING name)
{
	symtab_remove(get_symtab(ctx), name);
}

void
log_error(const char *fmt, ...)
{
        va_list ap;

        va_start(ap, fmt);
        vsyslog(LOG_DAEMON|LOG_NOTICE, fmt, ap);
        va_end(ap);
}

#define S(s) ((s) ? (s) : "NULL")

struct vardef {
	struct vardef *next;
	enum variable_type type;
	char *name;
	char *repl;
};

static void
vardef_free(struct vardef *v)
{
	while (v) {
		struct vardef *n = v->next;
		free(v);
		v = n;
	}
}

static enum variable_type
str2type(const char *s, size_t len)
{
	int i;

	for (i = 0; i < sizeof(typestr)/sizeof(typestr[0]); i++) {
		if (strlen(typestr[i]) < len)
			continue;
		if (strncasecmp(typestr[i], s, len) == 0)
			return i;
	}
	return variable_unset;
}

static double
str2duration(const char *str)
{
	char *p;
	double r;
	
	errno = 0;
	r = strtod(str, &p);
	if (errno)
		return 0.0;
	while (*p && isspace(*p))
		p++;

	switch (*p++) {
	case 's':
		break;
	case 'm':
                if (*p == 's') {
                        r *= 1e-3;
                        p++;
                } else
                        r *= 60.;
                break;
	case 'h':
		r *= 60.*60.;
		break;
        case 'd':
		r *= 60.*60.*24.;
		break;
        case 'w':
		r *= 60.*60.*24.*7.;
		break;
        case 'y':
		r *= 60.*60.*24.*365.;
		break;
        default:
                return 0.0;
        }
	while (*p && isspace(*p))
		p++;
	return *p ? 0 : r;
}	

char *
bref_expand(const char *str, const char *input, pcre *re,
	    int ovsize, int *ovector)
{
	size_t rlen = 0;
	char *rbase = NULL;
	char *rptr;
	int nm = 2*ovsize/3;
	const char *p;
	
	for (p = str; *p; ) {
		if (*p == '\\' && strchr("123456789", p[1])) {
			int n = 2*(p[1] - '0');
			if (n < nm) {
				rlen += ovector[n+1] - ovector[n];
				p += 2;
				continue;
			}
		}
		++p;
		++rlen;
	}
	rbase = malloc(rlen + 1);
	AN(rbase);
	p = str;
	rptr = rbase;
	while (*p) {
		if (*p == '\\' && strchr("123456789", p[1])) {
			int n = 2*(p[1] - '0');
			if (n < nm) {
				memcpy(rptr, input + ovector[n],
				       ovector[n+1] - ovector[n]);
				rptr += ovector[n+1] - ovector[n];
				p += 2;
				continue;
			} 
		} 

		*rptr++ = *p++;
	}
	*rptr = 0;

	return rbase;
}

VCL_VOID
vmod_regset(VARIABLE_CTX ctx, VCL_STRING vars, VCL_STRING rxs, VCL_STRING input)
{
	struct symtab *vt = get_symtab(ctx);
	struct vardef *head = NULL, *tail = NULL, *def;
	size_t count = 0;
	size_t n;
	const char *v = vars;
	const char *error_ptr;
	int error_offset;
	int cflags = 0;
	long lval;
	union value value;
	char *p;
	int ovsize;
	int *ovector;
	int i;
	int rc;
	pcre *re;

	if (!vars || !rxs || !input) {
		log_error("variable.regset: bad arguments: vars=%s, rxs=%s, input=%s",
		      S(vars), S(rxs), S(input));
		return;
	}

	while (*v) {
		char const *nameptr = v;
		size_t n = strcspn(v, ":=,");
		size_t namelen;
		char const *replptr;
		size_t repllen;
		char rbuf[3];
		enum variable_type type;
		int delim;
		
		namelen = n;
		
		v += n;
		delim = *v ? *v++ : 0;

		if (delim == ':') {
			n = strcspn(v, "=,");
			type = str2type(v, n);
			v += n;
			delim = *v ? *v++ : 0;
		} else
			type = variable_string;

		if (delim == '=') {
			n = strcspn(v, ",");
			replptr = v;
			repllen = n;
			v += n;
			delim = *v ? *v++ : 0;
		} else {
			rbuf[0] = '\\';
			rbuf[1] = count + '1';
			rbuf[2] = 0;
			replptr = rbuf;
			repllen = 2;
		}

		def = malloc(sizeof(def[0]) + namelen + repllen + 2);
		def->next = NULL;
		if (tail)
			tail->next = def;
		else
			head = def;
		tail = def;
		++count;
		def->type = type;
		def->name = (char*)(def + 1);
		memcpy(def->name, nameptr, namelen);
		def->name[namelen] = 0;
		def->repl = def->name + namelen + 1;
		memcpy(def->repl, replptr, repllen);
		def->repl[repllen] = 0;
	}

	re = pcre_compile(rxs, cflags, &error_ptr, &error_offset, NULL);
	if (!re) {
		log_error("variable.regset: %s: compilation failed near %s: %s",
			  rxs, rxs + error_offset, error_ptr);
		vardef_free(head);
		return;
	}

	rc = pcre_fullinfo(re, NULL, PCRE_INFO_CAPTURECOUNT, &n);
	if (rc) {
		log_error("pcre_fullinfo() failed: %d", rc);
		vardef_free(head);
		return;
	}

	if (n < count) {
		log_error("variable.regset: %s: too few subexpressions to satisfy %s",
		      rxs, vars);
		vardef_free(head);
		return;
	}		

	ovsize = (count + 1) * 3;
	ovector = calloc(ovsize, sizeof(*ovector));

	rc = pcre_exec(re, 0, input, strlen(input), 0, 0, ovector, ovsize);
	if (rc <= 0) {
		if (rc != PCRE_ERROR_NOMATCH)
			log_error("variable.regset: pcre_exec failed: %d", rc);
		vardef_free(head);
		return;
	}

	for (def = head; def; def = def->next, i++) {
		char *s = bref_expand(def->repl, input, re, ovsize, ovector);

		switch (def->type) {
		case variable_string:
			value.s = (char*)s;
			break;
		case variable_int:
			errno = 0;
			lval = strtol(s, &p, 10);
			if (*p) {
				log_error("variable.regset: %s(%s)#%d: not an integer", rxs, input, i);
				value.i = 0;
			} else if (errno) {
				log_error("variable.regset: %s(%s)#%d: %s",
					  rxs, input, i, strerror(errno));
				value.i = 0;
			} else if (lval < INT_MIN || lval > INT_MAX) {
				log_error("variable.regset: %s(%s)#%d: value out of range",
				      rxs, input, i);
				value.i = 0;
			} else
				value.i = lval;
			free(s);
			break;
		case variable_real:
			errno = 0;
			value.r = strtod(s, &p);
			if (*p) {
				log_error("variable.regset: %s(%s)#%d: not a valid number", rxs, input, i);
				value.r = 0;
			} else if (errno) {
				log_error("variable.regset: %s(%s)#%d: %s",
				      rxs, input, i, strerror(errno));
				value.r = 0;
			}
			free(s);
			break;
			
		case variable_duration:
			value.d = str2duration(s);
			free(s);
 			break;
		default:
			abort();
		}
		defvar(vt, def->name, def->type, &value);
	}
	
	pcre_free(re);
	free(ovector);
	vardef_free(head);
}

Return to:

Send suggestions and report system problems to the System administrator.