Refactor TR_FILTER using a GPtrArray of filter lines
[trust_router.git] / common / tr_filter.c
1 /*
2  * Copyright (c) 2012, 2013, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <talloc.h>
39 #include <assert.h>
40
41 #include <tr_filter.h>
42 #include <trp_internal.h>
43 #include <tid_internal.h>
44 #include <tr_debug.h>
45
46 /* Function types for handling filter fields generally. All target values
47  * are represented as strings in a TR_NAME.
48  */
49
50 /* CMP functions return values like strcmp: 0 on match, <0 on target<val, >0 on target>val */
51 typedef int (*TR_FILTER_FIELD_CMP)(TR_FILTER_TARGET *target, TR_NAME *val);
52 /* get functions return TR_NAME format of the field value. Caller must free it. */
53 typedef TR_NAME *(*TR_FILTER_FIELD_GET)(TR_FILTER_TARGET *target);
54
55 static TR_FILTER_TARGET *tr_filter_target_new(TALLOC_CTX *mem_ctx)
56 {
57   TR_FILTER_TARGET *target=talloc(mem_ctx, TR_FILTER_TARGET);
58   if (target) {
59     target->trp_inforec=NULL;
60     target->trp_upd=NULL;
61     target->tid_req=NULL;
62   }
63   return target;
64 }
65 void tr_filter_target_free(TR_FILTER_TARGET *target)
66 {
67   talloc_free(target);
68 }
69
70 /**
71  * Create a filter target for a TID request. Does not change the context of the request,
72  * so this is only valid until that is freed.
73  *
74  * @param mem_ctx talloc context for the object
75  * @param req TID request object
76  * @return pointer to a TR_FILTER_TARGET structure, or null on allocation failure
77  */
78 TR_FILTER_TARGET *tr_filter_target_tid_req(TALLOC_CTX *mem_ctx, TID_REQ *req)
79 {
80   TR_FILTER_TARGET *target=tr_filter_target_new(mem_ctx);
81   if (target)
82     target->tid_req=req; /* borrowed, not adding to our context */
83   return target;
84 }
85
86 /**
87  * Create a filter target for a TRP inforec. Does not change the context of the inforec or duplicate TR_NAMEs,
88  * so this is only valid until those are freed.
89  *
90  * @param mem_ctx talloc context for the object
91  * @param upd Update containing the TRP inforec
92  * @param inforec TRP inforec
93  * @return pointer to a TR_FILTER_TARGET structure, or null on allocation failure
94  */
95 TR_FILTER_TARGET *tr_filter_target_trp_inforec(TALLOC_CTX *mem_ctx, TRP_UPD *upd, TRP_INFOREC *inforec)
96 {
97   TR_FILTER_TARGET *target=tr_filter_target_new(mem_ctx);
98   if (target) {
99     target->trp_inforec = inforec; /* borrowed, not adding to our context */
100     target->trp_upd=upd;
101   }
102   return target;
103 }
104
105 /** Handler functions for TID RP_REALM field */
106 static int tr_ff_cmp_tid_rp_realm(TR_FILTER_TARGET *target, TR_NAME *val)
107 {
108   return tr_name_cmp(tid_req_get_rp_realm(target->tid_req), val);
109 }
110
111 static TR_NAME *tr_ff_get_tid_rp_realm(TR_FILTER_TARGET *target)
112 {
113   return tr_dup_name(tid_req_get_rp_realm(target->tid_req));
114 }
115
116 /** Handler functions for TRP info_type field */
117 static int tr_ff_cmp_trp_info_type(TR_FILTER_TARGET *target, TR_NAME *val)
118 {
119   TRP_INFOREC *inforec=target->trp_inforec;
120   char *valstr=NULL;
121   int val_type=0;
122
123   assert(val);
124   assert(inforec);
125
126   /* nothing matches unknown */
127   if (inforec->type==TRP_INFOREC_TYPE_UNKNOWN)
128     return 0;
129
130   valstr = tr_name_strdup(val); /* get this as an official null-terminated string */
131   val_type = trp_inforec_type_from_string(valstr);
132   free(valstr);
133
134   /* we do not define an ordering of info types */
135   return (val_type==inforec->type);
136 }
137
138 static TR_NAME *tr_ff_get_trp_info_type(TR_FILTER_TARGET *target)
139 {
140   TRP_INFOREC *inforec=target->trp_inforec;
141   return tr_new_name(trp_inforec_type_to_string(inforec->type));
142 }
143
144 /** Handlers for TRP realm field */
145 static int tr_ff_cmp_trp_realm(TR_FILTER_TARGET *target, TR_NAME *val)
146 {
147   return tr_name_cmp(trp_upd_get_realm(target->trp_upd), val);
148 }
149
150 static TR_NAME *tr_ff_get_trp_realm(TR_FILTER_TARGET *target)
151 {
152   return tr_dup_name(trp_upd_get_realm(target->trp_upd));
153 }
154
155 /** Handlers for TID realm field */
156 static int tr_ff_cmp_tid_realm(TR_FILTER_TARGET *target, TR_NAME *val)
157 {
158   return tr_name_cmp(tid_req_get_realm(target->tid_req), val);
159 }
160
161 static TR_NAME *tr_ff_get_tid_realm(TR_FILTER_TARGET *target)
162 {
163   return tr_dup_name(tid_req_get_realm(target->tid_req));
164 }
165
166 /** Handlers for TRP community field */
167 static int tr_ff_cmp_trp_comm(TR_FILTER_TARGET *target, TR_NAME *val)
168 {
169   return tr_name_cmp(trp_upd_get_comm(target->trp_upd), val);
170 }
171
172 static TR_NAME *tr_ff_get_trp_comm(TR_FILTER_TARGET *target)
173 {
174   return tr_dup_name(trp_upd_get_comm(target->trp_upd));
175 }
176
177 /** Handlers for TID community field */
178 static int tr_ff_cmp_tid_comm(TR_FILTER_TARGET *target, TR_NAME *val)
179 {
180   return tr_name_cmp(tid_req_get_comm(target->tid_req), val);
181 }
182
183 static TR_NAME *tr_ff_get_tid_comm(TR_FILTER_TARGET *target)
184 {
185   return tr_dup_name(tid_req_get_comm(target->tid_req));
186 }
187
188 /** Handlers for TRP community_type field */
189 static TR_NAME *tr_ff_get_trp_comm_type(TR_FILTER_TARGET *target)
190 {
191   TR_NAME *type=NULL;
192
193   switch(trp_inforec_get_comm_type(target->trp_inforec)) {
194     case TR_COMM_APC:
195       type=tr_new_name("apc");
196       break;
197     case TR_COMM_COI:
198       type=tr_new_name("coi");
199       break;
200     default:
201       type=NULL;
202       break; /* unknown types always fail */
203   }
204
205   return type;
206 }
207
208 static int tr_ff_cmp_trp_comm_type(TR_FILTER_TARGET *target, TR_NAME *val)
209 {
210   TR_NAME *type=tr_ff_get_trp_comm_type(target);
211   int retval=0;
212
213   if (type==NULL)
214     retval=1;
215   else {
216     retval = tr_name_cmp(val, type);
217     tr_free_name(type);
218   }
219   return retval;
220 }
221
222 /** Handlers for TRP realm_role field */
223 static TR_NAME *tr_ff_get_trp_realm_role(TR_FILTER_TARGET *target)
224 {
225   TR_NAME *type=NULL;
226
227   switch(trp_inforec_get_role(target->trp_inforec)) {
228     case TR_ROLE_IDP:
229       type=tr_new_name("idp");
230       break;
231     case TR_ROLE_RP:
232       type=tr_new_name("rp");
233       break;
234     default:
235       type=NULL;
236       break; /* unknown types always fail */
237   }
238
239   return type;
240 }
241
242 static int tr_ff_cmp_trp_realm_role(TR_FILTER_TARGET *target, TR_NAME *val)
243 {
244   TR_NAME *type=tr_ff_get_trp_realm_role(target);
245   int retval=0;
246
247   if (type==NULL)
248     retval=1;
249   else {
250     retval = tr_name_cmp(val, type);
251     tr_free_name(type);
252   }
253   return retval;
254 }
255
256 /** Handlers for TRP apc field */
257 /* TODO: Handle multiple APCs, not just the first */
258 static int tr_ff_cmp_trp_apc(TR_FILTER_TARGET *target, TR_NAME *val)
259 {
260   return tr_name_cmp(tr_apc_get_id(trp_inforec_get_apcs(target->trp_inforec)), val);
261 }
262
263 static TR_NAME *tr_ff_get_trp_apc(TR_FILTER_TARGET *target)
264 {
265   TR_APC *apc=trp_inforec_get_apcs(target->trp_inforec);
266   if (apc==NULL)
267     return NULL;
268
269   return tr_dup_name(tr_apc_get_id(apc));
270 }
271
272 /** Handlers for TRP owner_realm field */
273 static int tr_ff_cmp_trp_owner_realm(TR_FILTER_TARGET *target, TR_NAME *val)
274 {
275   return tr_name_cmp(trp_inforec_get_owner_realm(target->trp_inforec), val);
276 }
277
278 static TR_NAME *tr_ff_get_trp_owner_realm(TR_FILTER_TARGET *target)
279 {
280   return tr_dup_name(trp_inforec_get_owner_realm(target->trp_inforec));
281 }
282
283 /** Handlers for TRP trust_router field */
284 static int tr_ff_cmp_trp_trust_router(TR_FILTER_TARGET *target, TR_NAME *val)
285 {
286   return tr_name_cmp(trp_inforec_get_trust_router(target->trp_inforec), val);
287 }
288
289 static TR_NAME *tr_ff_get_trp_trust_router(TR_FILTER_TARGET *target)
290 {
291   return tr_dup_name(trp_inforec_get_trust_router(target->trp_inforec));
292 }
293
294 /** Handlers for TRP owner_contact field */
295 static int tr_ff_cmp_trp_owner_contact(TR_FILTER_TARGET *target, TR_NAME *val)
296 {
297   return tr_name_cmp(trp_inforec_get_owner_contact(target->trp_inforec), val);
298 }
299
300 static TR_NAME *tr_ff_get_trp_owner_contact(TR_FILTER_TARGET *target)
301 {
302   return tr_dup_name(trp_inforec_get_owner_contact(target->trp_inforec));
303 }
304
305 /** Handlers for TID req original_coi field */
306 static int tr_ff_cmp_tid_orig_coi(TR_FILTER_TARGET *target, TR_NAME *val)
307 {
308   return tr_name_cmp(tid_req_get_orig_coi(target->tid_req), val);
309 }
310
311 static TR_NAME *tr_ff_get_tid_orig_coi(TR_FILTER_TARGET *target)
312 {
313   return tr_dup_name(tid_req_get_orig_coi(target->tid_req));
314 }
315
316 /**
317  * Filter field handler table
318  */
319 struct tr_filter_field_entry {
320   TR_FILTER_TYPE filter_type;
321   const char *name;
322   TR_FILTER_FIELD_CMP cmp;
323   TR_FILTER_FIELD_GET get;
324 };
325 static struct tr_filter_field_entry tr_filter_field_table[] = {
326     /* realm */
327     {TR_FILTER_TYPE_TID_INBOUND, "realm", tr_ff_cmp_tid_realm, tr_ff_get_tid_realm},
328     {TR_FILTER_TYPE_TRP_INBOUND, "realm", tr_ff_cmp_trp_realm, tr_ff_get_trp_realm},
329     {TR_FILTER_TYPE_TRP_OUTBOUND, "realm", tr_ff_cmp_trp_realm, tr_ff_get_trp_realm},
330
331     /* community */
332     {TR_FILTER_TYPE_TID_INBOUND, "comm", tr_ff_cmp_tid_comm, tr_ff_get_tid_comm},
333     {TR_FILTER_TYPE_TRP_INBOUND, "comm", tr_ff_cmp_trp_comm, tr_ff_get_trp_comm},
334     {TR_FILTER_TYPE_TRP_OUTBOUND, "comm", tr_ff_cmp_trp_comm, tr_ff_get_trp_comm},
335
336     /* community type */
337     {TR_FILTER_TYPE_TRP_INBOUND, "comm_type", tr_ff_cmp_trp_comm_type, tr_ff_get_trp_comm_type},
338     {TR_FILTER_TYPE_TRP_OUTBOUND, "comm_type", tr_ff_cmp_trp_comm_type, tr_ff_get_trp_comm_type},
339
340     /* realm role */
341     {TR_FILTER_TYPE_TRP_INBOUND, "realm_role", tr_ff_cmp_trp_realm_role, tr_ff_get_trp_realm_role},
342     {TR_FILTER_TYPE_TRP_OUTBOUND, "realm_role", tr_ff_cmp_trp_realm_role, tr_ff_get_trp_realm_role},
343
344     /* apc */
345     {TR_FILTER_TYPE_TRP_INBOUND, "apc", tr_ff_cmp_trp_apc, tr_ff_get_trp_apc},
346     {TR_FILTER_TYPE_TRP_OUTBOUND, "apc", tr_ff_cmp_trp_apc, tr_ff_get_trp_apc},
347
348     /* trust_router */
349     {TR_FILTER_TYPE_TRP_INBOUND, "trust_router", tr_ff_cmp_trp_trust_router, tr_ff_get_trp_trust_router},
350     {TR_FILTER_TYPE_TRP_OUTBOUND, "trust_router", tr_ff_cmp_trp_trust_router, tr_ff_get_trp_trust_router},
351
352     /* owner_realm */
353     {TR_FILTER_TYPE_TRP_INBOUND, "owner_realm", tr_ff_cmp_trp_owner_realm, tr_ff_get_trp_owner_realm},
354     {TR_FILTER_TYPE_TRP_OUTBOUND, "owner_realm", tr_ff_cmp_trp_owner_realm, tr_ff_get_trp_owner_realm},
355
356     /* owner_contact */
357     {TR_FILTER_TYPE_TRP_INBOUND, "owner_contact", tr_ff_cmp_trp_owner_contact, tr_ff_get_trp_owner_contact},
358     {TR_FILTER_TYPE_TRP_OUTBOUND, "owner_contact", tr_ff_cmp_trp_owner_contact, tr_ff_get_trp_owner_contact},
359
360     /* rp_realm */
361     {TR_FILTER_TYPE_TID_INBOUND, "rp_realm", tr_ff_cmp_tid_rp_realm, tr_ff_get_tid_rp_realm},
362
363     /* original coi */
364     {TR_FILTER_TYPE_TID_INBOUND, "original_coi", tr_ff_cmp_tid_orig_coi, tr_ff_get_tid_orig_coi},
365
366     /* info_type */
367     {TR_FILTER_TYPE_TRP_INBOUND, "info_type", tr_ff_cmp_trp_info_type, tr_ff_get_trp_info_type},
368     {TR_FILTER_TYPE_TRP_OUTBOUND, "info_type", tr_ff_cmp_trp_info_type, tr_ff_get_trp_info_type},
369
370     /* Unknown */
371     {TR_FILTER_TYPE_UNKNOWN, NULL } /* This must be the final entry */
372 };
373
374 /* TODO: support TRP metric field (requires > < comparison instead of wildcard match) */
375
376 static struct tr_filter_field_entry *tr_filter_field_entry(TR_FILTER_TYPE filter_type, TR_NAME *field_name)
377 {
378   unsigned int ii;
379
380   for (ii=0; tr_filter_field_table[ii].filter_type!=TR_FILTER_TYPE_UNKNOWN; ii++) {
381     if ((tr_filter_field_table[ii].filter_type==filter_type)
382         && (tr_name_cmp_str(field_name, tr_filter_field_table[ii].name)==0)) {
383       return tr_filter_field_table+ii;
384     }
385   }
386   return NULL;
387 }
388
389 /**
390  * Apply a filter to a target record or TID request.
391  *
392  * If one of the filter lines matches, out_action is set to the applicable action. If constraints
393  * is not NULL, the constraints from the matching filter line will be added to the constraint set
394  * *constraints, or to a new one if *constraints is NULL. In this case, TR_FILTER_MATCH will be
395  * returned.
396  *
397  * If there is no match, returns TR_FILTER_NO_MATCH, out_action is undefined, and constraints
398  * will not be changed.
399  *
400  * @param target Record or request to which the filter is applied
401  * @param filt Filter to apply
402  * @param constraints Pointer to existing set of constraints (NULL if not tracking constraints)
403  * @param out_action Action to be carried out (output)
404  * @return TR_FILTER_MATCH or TR_FILTER_NO_MATCH
405  */
406 int tr_filter_apply(TR_FILTER_TARGET *target,
407                     TR_FILTER *filt,
408                     TR_CONSTRAINT_SET **constraints,
409                     TR_FILTER_ACTION *out_action)
410 {
411   TALLOC_CTX *tmp_ctx = talloc_new(NULL);
412   TR_FILTER_ITER *filt_iter = tr_filter_iter_new(tmp_ctx);
413   TR_FLINE *this_fline = NULL;
414   unsigned int jj=0;
415   int retval=TR_FILTER_NO_MATCH;
416
417   /* Default action is reject */
418   *out_action = TR_FILTER_ACTION_REJECT;
419
420   /* Validate filter */
421   if ((filt_iter == NULL) || (filt==NULL) || (filt->type==TR_FILTER_TYPE_UNKNOWN)) {
422     talloc_free(tmp_ctx);
423     return TR_FILTER_NO_MATCH;
424   }
425
426   /* Step through filter lines looking for a match. If a line matches, retval
427    * will be set to TR_FILTER_MATCH, so stop then. */
428   this_fline = tr_filter_iter_first(filt_iter, filt);
429   while(this_fline) {
430     /* Assume we are going to succeed. If any specs fail to match, we'll set
431      * this to TR_FILTER_NO_MATCH. */
432     retval=TR_FILTER_MATCH;
433     for (jj=0; jj<TR_MAX_FILTER_SPECS; jj++) {
434       /* skip empty specs (these shouldn't really happen either) */
435       if (this_fline->specs[jj]==NULL)
436         continue;
437
438       if (!tr_fspec_matches(this_fline->specs[jj], filt->type, target)) {
439         retval=TR_FILTER_NO_MATCH; /* set this in case this is the last filter line */
440         break; /* give up on this filter line */
441       }
442     }
443
444     if (retval==TR_FILTER_MATCH)
445       break;
446   }
447
448   if (retval==TR_FILTER_MATCH) {
449     /* Matched line ii. Grab its action and constraints. */
450     *out_action = this_fline->action;
451     if (constraints!=NULL) {
452       /* if either constraint is missing, these are no-ops */
453       tr_constraint_add_to_set(constraints, this_fline->realm_cons);
454       tr_constraint_add_to_set(constraints, this_fline->domain_cons);
455     }
456   }
457
458   return retval;
459 }
460
461 void tr_fspec_free(TR_FSPEC *fspec)
462 {
463   talloc_free(fspec);
464 }
465
466 static int tr_fspec_destructor(void *obj)
467 {
468   TR_FSPEC *fspec = talloc_get_type_abort(obj, TR_FSPEC);
469   size_t ii;
470
471   if (fspec->field != NULL)
472     tr_free_name(fspec->field);
473   for (ii=0; ii<TR_MAX_FILTER_SPEC_MATCHES; ii++) {
474     if (fspec->match[ii] != NULL)
475       tr_free_name(fspec->match[ii]);
476   }
477   return 0;
478 }
479
480 TR_FSPEC *tr_fspec_new(TALLOC_CTX *mem_ctx)
481 {
482   TR_FSPEC *fspec = talloc(mem_ctx, TR_FSPEC);
483   size_t ii=0;
484
485   if (fspec != NULL) {
486     fspec->field = NULL;
487     for (ii=0; ii<TR_MAX_FILTER_SPEC_MATCHES; ii++)
488       fspec->match[ii] = NULL;
489
490     talloc_set_destructor((void *)fspec, tr_fspec_destructor);
491   }
492   return fspec;
493 }
494
495 void tr_fspec_add_match(TR_FSPEC *fspec, TR_NAME *match)
496 {
497   size_t ii;
498   for (ii=0; ii<TR_MAX_FILTER_SPEC_MATCHES; ii++) {
499     if (fspec->match[ii]==NULL) {
500       fspec->match[ii]=match;
501       break;
502     }
503   }
504   /* TODO: handle case that adding the match failed */
505 }
506
507 /* returns 1 if the spec matches */
508 int tr_fspec_matches(TR_FSPEC *fspec, TR_FILTER_TYPE ftype, TR_FILTER_TARGET *target)
509 {
510   struct tr_filter_field_entry *field=NULL;
511   TR_NAME *name=NULL;
512   int retval=0;
513
514   size_t ii=0;
515
516   if (fspec==NULL)
517     return 0;
518
519   /* Look up how to handle the requested field */
520   field = tr_filter_field_entry(ftype, fspec->field);
521   if (field==NULL) {
522     tr_err("tr_fspec_matches: No entry to handle field %.*s for %*s filter.",
523            fspec->field->len, fspec->field->buf,
524            tr_filter_type_to_string(ftype));
525     return 0;
526   }
527
528   name=field->get(target);
529   if (name==NULL)
530     return 0; /* if there's no value, there's no match */
531
532   for (ii=0; ii<TR_MAX_FILTER_SPEC_MATCHES; ii++) {
533     if (fspec->match[ii]!=NULL) {
534       if (tr_name_prefix_wildcard_match(name, fspec->match[ii])) {
535         retval=1;
536         tr_debug("tr_fspec_matches: Field %.*s value \"%.*s\" matches \"%.*s\" for %s filter.",
537                  fspec->field->len, fspec->field->buf,
538                  name->len, name->buf,
539                  fspec->match[ii]->len, fspec->match[ii]->buf,
540                  tr_filter_type_to_string(ftype));
541         break;
542       }
543     }
544   }
545
546   if (!retval) {
547         tr_debug("tr_fspec_matches: Field %.*s value \"%.*s\" does not match for %s filter.",
548                  fspec->field->len, fspec->field->buf,
549                  name->len, name->buf,
550                  tr_filter_type_to_string(ftype));
551   }
552   tr_free_name(name);
553   return retval;
554 }
555
556 void tr_fline_free(TR_FLINE *fline)
557 {
558   talloc_free(fline);
559 }
560
561 TR_FLINE *tr_fline_new(TALLOC_CTX *mem_ctx)
562 {
563   TR_FLINE *fl = talloc(mem_ctx, TR_FLINE);
564   int ii = 0;
565
566   if (fl != NULL) {
567     fl->action = TR_FILTER_ACTION_UNKNOWN;
568     fl->realm_cons = NULL;
569     fl->domain_cons = NULL;
570     for (ii = 0; ii < TR_MAX_FILTER_SPECS; ii++)
571       fl->specs[ii] = NULL;
572   }
573   return fl;
574 }
575
576 TR_FILTER *tr_filter_new(TALLOC_CTX *mem_ctx)
577 {
578   TR_FILTER *f = talloc(mem_ctx, TR_FILTER);
579
580   if (f != NULL) {
581     f->type = TR_FILTER_TYPE_UNKNOWN;
582     f->lines = g_ptr_array_new();
583     if (f->lines == NULL) {
584       talloc_free(f);
585       return NULL;
586     }
587   }
588   return f;
589 }
590
591 void tr_filter_free(TR_FILTER *filt)
592 {
593   talloc_free(filt);
594 }
595
596 void tr_filter_set_type(TR_FILTER *filt, TR_FILTER_TYPE type)
597 {
598   filt->type = type;
599 }
600
601 TR_FILTER_TYPE tr_filter_get_type(TR_FILTER *filt)
602 {
603   return filt->type;
604 }
605
606 /**
607  * Add a TR_FLINE to a filter
608  *
609  * Steals the line into its context on success
610  *
611  * @param filt
612  * @param line
613  * @return line, or null on failure
614  */
615 TR_FLINE *tr_filter_add_line(TR_FILTER *filt, TR_FLINE *line)
616 {
617   guint old_len = filt->lines->len;
618   g_ptr_array_add(filt->lines, line);
619   talloc_steal(filt, line); /* take this no matter what */
620   if (old_len == filt->lines->len)
621     return NULL; /* failed to add */
622   return line;
623 }
624
625 /**
626  * Iterator for TR_FLINES in a TR_FILTER
627  *
628  * @param mem_ctx
629  * @return
630  */
631 TR_FILTER_ITER *tr_filter_iter_new(TALLOC_CTX *mem_ctx)
632 {
633   TR_FILTER_ITER *iter = talloc(mem_ctx, TR_FILTER_ITER);
634   if (iter) {
635     iter->filter = NULL;
636   }
637   return iter;
638 }
639
640 void tr_filter_iter_free(TR_FILTER_ITER *iter)
641 {
642   talloc_free(iter);
643 }
644
645 TR_FLINE *tr_filter_iter_next(TR_FILTER_ITER *iter)
646 {
647   if (!iter)
648     return NULL;
649
650   if (iter->ii < iter->filter->lines->len)
651     return g_ptr_array_index(iter->filter->lines, iter->ii++);
652   return NULL;
653 }
654
655 TR_FLINE *tr_filter_iter_first(TR_FILTER_ITER *iter, TR_FILTER *filter)
656 {
657   if (!iter || !filter)
658     return NULL;
659
660   iter->filter = filter;
661   iter->ii = 0;
662   return tr_filter_iter_next(iter);
663 }
664
665 /**
666  * Check that a filter is valid, i.e., can be processed.
667  *
668  * @param filt Filter to verify
669  * @return 1 if the filter is valid, 0 otherwise
670  */
671 int tr_filter_validate(TR_FILTER *filt)
672 {
673   TALLOC_CTX *tmp_ctx = talloc_new(NULL);
674   size_t jj=0, kk=0;
675   TR_FILTER_ITER *filt_iter = tr_filter_iter_new(tmp_ctx);
676   TR_FLINE *this_fline = NULL;
677   
678   if (!filt) {
679     talloc_free(tmp_ctx);
680     return 0;
681   }
682
683   /* check that we recognize the type */
684   switch(filt->type) {
685     case TR_FILTER_TYPE_TID_INBOUND:
686     case TR_FILTER_TYPE_TRP_INBOUND:
687     case TR_FILTER_TYPE_TRP_OUTBOUND:
688       break;
689
690     default:
691       talloc_free(tmp_ctx);
692       return 0; /* if we get here, either TR_FILTER_TYPE_UNKNOWN or an invalid value was found */
693   }
694   
695   this_fline = tr_filter_iter_first(filt_iter, filt);
696   while(this_fline) {
697     /* check that we recognize the action */
698     switch(this_fline->action) {
699       case TR_FILTER_ACTION_ACCEPT:
700       case TR_FILTER_ACTION_REJECT:
701         break;
702
703       default:
704         /* if we get here, either TR_FILTER_ACTION_UNKNOWN or an invalid value was found */
705         talloc_free(tmp_ctx);
706         return 0;
707     }
708
709     for (jj=0; jj<TR_MAX_FILTER_SPECS; jj++) {
710       if (this_fline->specs[jj]==NULL)
711         continue; /* an empty filter spec is valid */
712
713       if (!tr_filter_validate_spec_field(filt->type, this_fline->specs[jj])) {
714         talloc_free(tmp_ctx);
715         return 0;
716       }
717
718       /* check that at least one match is non-null */
719       for (kk=0; kk<TR_MAX_FILTER_SPEC_MATCHES; kk++) {
720         if (this_fline->specs[jj]->match[kk]!=NULL)
721           break;
722       }
723       if (kk==TR_MAX_FILTER_SPEC_MATCHES) {
724         talloc_free(tmp_ctx);
725         return 0;
726       }
727     }
728     this_fline = tr_filter_iter_next(filt_iter);
729   }
730
731   /* We ran the gauntlet. Success! */
732   talloc_free(tmp_ctx);
733   return 1;
734 }
735
736 int tr_filter_validate_spec_field(TR_FILTER_TYPE ftype, TR_FSPEC *fspec)
737 {
738   if ((fspec==NULL) || (tr_filter_field_entry(ftype, fspec->field)==NULL))
739     return 0; /* unknown field */
740
741   return 1;
742 }
743
744 /**
745  * Allocate a new filter set.
746  *
747  * @param mem_ctx Talloc context for the new set
748  * @return Pointer to new set, or null on error
749  */
750 TR_FILTER_SET *tr_filter_set_new(TALLOC_CTX *mem_ctx)
751 {
752   TR_FILTER_SET *set=talloc(mem_ctx, TR_FILTER_SET);
753   if (set!=NULL) {
754     set->next=NULL;
755     set->this=NULL;
756   }
757   return set;
758 }
759
760 /**
761  * Free a filter set
762  *
763  * @param fs Filter set to free
764  */
765 void tr_filter_set_free(TR_FILTER_SET *fs)
766 {
767   talloc_free(fs);
768 }
769
770 /**
771  * Find the tail of the filter set linked list.
772  *
773  * @param set Set to find tail of
774  * @return Last element in the list
775  */
776 static TR_FILTER_SET *tr_filter_set_tail(TR_FILTER_SET *set)
777 {
778   while (set->next)
779     set=set->next;
780   return set;
781 }
782
783 /**
784  * Add new filter to filter set.
785  *
786  * @param set Filter set
787  * @param new New filter to add
788  * @return 0 on success, nonzero on error
789  */
790 int tr_filter_set_add(TR_FILTER_SET *set, TR_FILTER *new)
791 {
792   TR_FILTER_SET *tail=NULL;
793
794   if (set->this==NULL)
795     tail=set;
796   else {
797     tail=tr_filter_set_tail(set);
798     tail->next=tr_filter_set_new(set);
799     if (tail->next==NULL)
800       return 1;
801     tail=tail->next;
802   }
803   tail->this=new;
804   talloc_steal(tail, new);
805   return 0;
806 }
807
808 /**
809  * Find a filter of a given type in the filter set. If there are multiple, returns the first one.
810  *
811  * @param set Filter set to search
812  * @param type Type of filter to find
813  * @return Borrowed pointer to the filter, or null if no filter of that type is found
814  */
815 TR_FILTER *tr_filter_set_get(TR_FILTER_SET *set, TR_FILTER_TYPE type)
816 {
817   TR_FILTER_SET *cur=set;
818   while(cur!=NULL) {
819     if ((cur->this != NULL) && (cur->this->type == type))
820       return cur->this;
821     cur=cur->next;
822   }
823   return NULL;
824 }
825
826 TR_FILTER_TYPE filter_type[]={TR_FILTER_TYPE_TID_INBOUND,
827                               TR_FILTER_TYPE_TRP_INBOUND,
828                               TR_FILTER_TYPE_TRP_OUTBOUND};
829 const char *filter_label[]={"tid_inbound",
830                             "trp_inbound",
831                             "trp_outbound"};
832 size_t num_filter_types=sizeof(filter_type)/sizeof(filter_type[0]);
833
834 const char *tr_filter_type_to_string(TR_FILTER_TYPE ftype)
835 {
836   size_t ii=0;
837
838   for (ii=0; ii<num_filter_types; ii++) {
839     if (ftype==filter_type[ii])
840       return filter_label[ii];
841   }
842   return "unknown";
843 }
844
845 TR_FILTER_TYPE tr_filter_type_from_string(const char *s)
846 {
847   size_t ii=0;
848
849   for(ii=0; ii<num_filter_types; ii++) {
850     if (0==strcmp(s, filter_label[ii]))
851       return filter_type[ii];
852   }
853   return TR_FILTER_TYPE_UNKNOWN;
854 }
855