Merge branch 'debian' into debian-testing
authorJennifer Richards <jennifer@painless-security.com>
Thu, 29 Jun 2017 16:18:51 +0000 (12:18 -0400)
committerJennifer Richards <jennifer@painless-security.com>
Thu, 29 Jun 2017 16:18:51 +0000 (12:18 -0400)
36 files changed:
Makefile.am
common/t_constraint.c
common/tests/filt_test.c [new file with mode: 0644]
common/tests/name_test.c [new file with mode: 0644]
common/tests/test-filters/filt-inforec-1-msg.json [new file with mode: 0644]
common/tests/test-filters/filt-inforec-1.json [new file with mode: 0644]
common/tests/test-filters/filt-tidreq-1-msg.json [new file with mode: 0644]
common/tests/test-filters/filt-tidreq-1.json [new file with mode: 0644]
common/tests/test-filters/filter-tests.json [new file with mode: 0644]
common/tests/test-filters/invalid-filt-repeated-key.json [new file with mode: 0644]
common/tests/test-filters/invalid-filt-unknown-field.json [new file with mode: 0644]
common/tests/test-filters/valid-filt.json [new file with mode: 0644]
common/tr_comm.c
common/tr_config.c
common/tr_constraint.c
common/tr_filter.c
common/tr_msg.c
common/tr_name.c
common/tr_rp.c
include/tr_comm.h
include/tr_filter.h
include/tr_msg.h
include/tr_rp.h
include/trp_ptable.h
include/trust_router/tr_constraint.h
include/trust_router/tr_name.h
include/trust_router/trp.h
tid/example/tidc_main.c
tid/example/tids_main.c
tid/tid_req.c
tr/tr_main.c
tr/tr_tid.c
tr/tr_trp.c
trp/trp_ptable.c
trp/trp_upd.c
trp/trps.c

index 830f9b1..2254baf 100644 (file)
@@ -1,6 +1,8 @@
 DISTCHECK_CONFIGURE_FLAGS = \
        --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)
-bin_PROGRAMS= tr/trust_router tr/trpc tid/example/tidc tid/example/tids common/tests/tr_dh_test common/tests/mq_test common/tests/thread_test trp/msgtst trp/test/rtbl_test trp/test/ptbl_test common/tests/cfg_test common/tests/commtest
+bin_PROGRAMS= tr/trust_router tr/trpc tid/example/tidc tid/example/tids common/tests/tr_dh_test common/tests/mq_test \
+              common/tests/thread_test trp/msgtst trp/test/rtbl_test trp/test/ptbl_test common/tests/cfg_test \
+              common/tests/commtest common/tests/name_test common/tests/filt_test
 AM_CPPFLAGS=-I$(srcdir)/include $(GLIB_CFLAGS)
 AM_CFLAGS = -Wall -Werror=missing-prototypes -Werror -Wno-parentheses $(GLIB_CFLAGS)
 SUBDIRS = gsscon 
@@ -9,7 +11,7 @@ common_srcs = common/tr_name.c \
        common/jansson_iterators.h \
        common/tr_msg.c \
        common/tr_dh.c \
-        common/tr_debug.c \
+    common/tr_debug.c \
        common/tr_util.c \
        common/tr_apc.c \
        common/tr_comm.c \
@@ -35,6 +37,7 @@ common/tr_mq.c
 
 check_PROGRAMS = common/t_constraint
 TESTS = common/t_constraint
+TEST_CFLAGS = -Wno-missing-prototypes
 
 lib_LTLIBRARIES = libtr_tid.la
 
@@ -145,6 +148,22 @@ common_tests_commtest_LDFLAGS = $(AM_LDFLAGS) -ltalloc -pthread
 
 common_tests_thread_test_LDFLAGS = $(AM_LDFLAGS) -ltalloc -pthread
 
+common_tests_name_test_SOURCES = common/tests/name_test.c \
+              $(common_srcs) \
+              $(tid_srcs) \
+              $(trp_srcs)
+common_tests_name_test_LDADD = gsscon/libgsscon.la $(GLIB_LIBS)
+common_tests_name_test_LDFLAGS = $(AM_LDFLAGS) -ltalloc -pthread
+common_tests_name_test_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
+
+common_tests_filt_test_SOURCES = common/tests/filt_test.c \
+              $(common_srcs) \
+              $(tid_srcs) \
+              $(trp_srcs)
+common_tests_filt_test_LDADD = gsscon/libgsscon.la $(GLIB_LIBS)
+common_tests_filt_test_LDFLAGS = $(AM_LDFLAGS) -ltalloc -pthread
+common_tests_filt_test_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
+
 pkginclude_HEADERS = include/trust_router/tid.h include/trust_router/tr_name.h \
        include/tr_debug.h include/trust_router/trp.h \
        include/trust_router/tr_dh.h \
index 997abaf..cb7549d 100644 (file)
@@ -33,7 +33,9 @@
  */
 
 #include <jansson.h>
+#if JANSSON_VERSION_HEX < 0x020500
 #include "jansson_iterators.h"
+#endif
 #include <stdio.h>
 #include <assert.h>
 
diff --git a/common/tests/filt_test.c b/common/tests/filt_test.c
new file mode 100644 (file)
index 0000000..e86f1bb
--- /dev/null
@@ -0,0 +1,272 @@
+/*
+ * Copyright (c) 2017, JANET(UK)
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of JANET(UK) nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <string.h>
+#include <jansson.h>
+#if JANSSON_VERSION_HEX < 0x020500
+#include "../jansson_iterators.h"
+#endif
+#include <trp_internal.h>
+#include <tid_internal.h>
+#include <tr_filter.h>
+#include <tr_config.h>
+
+#define FILTER_PATH "./test-filters/"
+
+/**
+ * Load a JSON file containing filters and return the filters from the first rp_client.
+ *
+ * @param fname File to read
+ * @param filt_out Will point to the loaded filter on success
+ * @return Return value from tr_cfg_parse_one_config_file()
+ */
+int load_filter(const char *fname, TR_FILTER_SET **filts_out)
+{
+  TR_CFG *cfg=tr_cfg_new(NULL);
+  TR_CFG_RC rc=TR_CFG_ERROR;
+
+  assert(fname);
+  assert(filts_out);
+
+  rc=tr_cfg_parse_one_config_file(cfg, fname);
+  if (rc!=TR_CFG_SUCCESS)
+    goto cleanup;
+
+  /* Steal the filter from the first rp_client */
+  assert(cfg);
+  assert(cfg->rp_clients);
+  assert(cfg->rp_clients->filters);
+  *filts_out=cfg->rp_clients->filters;
+  cfg->rp_clients->filters=NULL; /* can't use the _set_filter() because that will free the filter */
+  talloc_steal(NULL, *filts_out);
+
+cleanup:
+  tr_cfg_free(cfg);
+  return rc;
+}
+
+/**
+ * Test that filters load / fail to load as expected.
+ *
+ * @return 1 if all tests pass
+ */
+int test_load_filter(void)
+{
+  TR_FILTER_SET *filts=NULL;
+
+  assert(TR_CFG_SUCCESS==load_filter(FILTER_PATH "valid-filt.json", &filts));
+  if (filts) tr_filter_set_free(filts);
+  filts=NULL;
+  assert(TR_CFG_NOPARSE==load_filter(FILTER_PATH "invalid-filt-repeated-key.json", &filts));
+  if (filts) tr_filter_set_free(filts);
+  filts=NULL;
+  assert(TR_CFG_ERROR==load_filter(FILTER_PATH "invalid-filt-unknown-field.json", &filts));
+  if (filts) tr_filter_set_free(filts);
+  filts=NULL;
+  return 1;
+}
+
+/**
+ * Read the first inforec from the TR_MSG encoded in JSON file named fname.
+ *
+ * @param fname Filename with path for TR_MSG JSON
+ * @return Pointer to the decoded inforec, or NULL on failure
+ */
+TRP_INFOREC *load_inforec(const char *fname)
+{
+  TR_MSG *msg=NULL;
+  TRP_UPD *upd=NULL;
+  TRP_INFOREC *inforec=NULL;
+  json_t *decoded=json_load_file(fname, JSON_REJECT_DUPLICATES|JSON_DISABLE_EOF_CHECK, NULL);
+  char *encoded=json_dumps(decoded, 0); /* silly way to read the file without mucking around */
+
+  assert(decoded);
+  json_decref(decoded);
+
+  assert(encoded);
+  assert(msg=tr_msg_decode(encoded, strlen(encoded)));
+  assert(upd=tr_msg_get_trp_upd(msg));
+  assert(inforec=trp_upd_get_inforec(upd));
+  /* now remove the inforec from the update context */
+  talloc_steal(NULL, inforec);
+  tr_msg_free_decoded(msg);
+  tr_msg_free_encoded(encoded);
+  return inforec;
+}
+
+/* make this bigger than your message file */
+#define MAX_FILE_SIZE 20000
+TID_REQ *load_tid_req(const char *fname)
+{
+  TID_REQ *out=NULL;
+  TR_MSG *msg=NULL;
+  FILE *f=NULL;
+  char *msgbuf=NULL;
+  size_t msglen=0;
+
+  msgbuf=malloc(MAX_FILE_SIZE);
+  assert(msgbuf);
+  f=fopen(fname, "r");
+  assert(f);
+  msglen=fread(msgbuf, 1, MAX_FILE_SIZE, f);
+  assert(msglen);
+  assert(feof(f));
+  msg=tr_msg_decode(msgbuf, msglen);
+  free(msgbuf);
+  msgbuf=NULL;
+
+  assert(msg);
+  assert(tr_msg_get_msg_type(msg)==TID_REQUEST);
+
+  /* take the tid req out of the msg */
+  out=tr_msg_get_req(msg);
+  tr_msg_set_req(msg, NULL);
+  assert(out);
+
+  tr_msg_free_decoded(msg);
+  return out;
+}
+
+/**
+ * Read a set of filters from a config JSON in filt_fname and test against the tid_req or inforec in target_fname.
+ * If expect==1, succeed if the target is accepted by the filter, otherwise succeed if it is rejected.
+ * Takes filters from the first rp_realm defined in the filter file and the first inforec or tid req from
+ * the target file.
+ *
+ * @param filt_fname Name of JSON file containing filters
+ * @param ftype Which type of filter to test
+ * @param target_fname  Name of JSON file containing inforec
+ * @param expected_match 1 if we expect a match, 0 otherwise
+ * @param expected_action Expected action if the filter matches
+ * @return 1 if expected result is obtained, 0 or does not return otherwise
+ */
+int test_one_filter(const char *filt_fname,
+                    TR_FILTER_TYPE ftype,
+                    const char *target_fname,
+                    int expected_match,
+                    TR_FILTER_ACTION expected_action)
+{
+  TR_FILTER_TARGET *target=NULL;
+  TR_FILTER_SET *filts=NULL;
+  TR_FILTER_ACTION action=TR_FILTER_ACTION_UNKNOWN;
+
+  /* load filter for first test */
+  assert(TR_CFG_SUCCESS==load_filter(filt_fname, &filts));
+
+  /* load the target req or inforec */
+  switch(ftype) {
+    case TR_FILTER_TYPE_TID_INBOUND:
+      target=tr_filter_target_tid_req(NULL, load_tid_req(target_fname));
+      break;
+
+    case TR_FILTER_TYPE_TRP_INBOUND:
+    case TR_FILTER_TYPE_TRP_OUTBOUND:
+      /* TODO: read realm and community */
+      target= tr_filter_target_trp_inforec(NULL, NULL, load_inforec(target_fname));
+      break;
+
+    default:
+      printf("Unknown filter type.\n");
+  }
+  assert(target);
+
+  assert(expected_match==tr_filter_apply(target, tr_filter_set_get(filts, ftype), NULL, &action));
+  if (expected_match==TR_FILTER_MATCH)
+    assert(action==expected_action);
+
+  tr_filter_set_free(filts);
+  switch(ftype) {
+    case TR_FILTER_TYPE_TID_INBOUND:
+      tid_req_free(target->tid_req);
+      break;
+
+    case TR_FILTER_TYPE_TRP_INBOUND:
+    case TR_FILTER_TYPE_TRP_OUTBOUND:
+      trp_inforec_free(target->trp_inforec);
+      if (target->trp_upd!=NULL)
+        trp_upd_free(target->trp_upd);
+      break;
+
+    default:
+      printf("Unknown filter type.\n");
+  }
+  tr_filter_target_free(target);
+  return 1;
+}
+
+int test_filter(void)
+{
+  json_t *test_list=json_load_file(FILTER_PATH "filter-tests.json", JSON_DISABLE_EOF_CHECK, NULL);
+  json_t *this;
+  size_t ii;
+  const char *filt_file, *target_file;
+  TR_FILTER_TYPE ftype;
+  int expect_match;
+  TR_FILTER_ACTION action;
+
+  json_array_foreach(test_list, ii, this) {
+    printf("Running filter test case: %s\n", json_string_value(json_object_get(this, "test label")));
+    fflush(stdout);
+
+    filt_file=json_string_value(json_object_get(this, "filter file"));
+    ftype=tr_filter_type_from_string(json_string_value(json_object_get(this, "filter type")));
+    target_file=json_string_value(json_object_get(this, "target file"));
+    if (0==strcmp("yes", json_string_value(json_object_get(this, "expect match"))))
+      expect_match=TR_FILTER_MATCH;
+    else
+      expect_match=TR_FILTER_NO_MATCH;
+
+    if (0==strcmp("accept", json_string_value(json_object_get(this, "action"))))
+      action=TR_FILTER_ACTION_ACCEPT;
+    else
+      action=TR_FILTER_ACTION_REJECT;
+
+    assert(test_one_filter(filt_file, ftype, target_file, expect_match, action));
+  }
+
+  return 1;
+}
+
+
+
+int main(void)
+{
+  assert(test_load_filter());
+  assert(test_filter());
+  printf("Success\n");
+  return 0;
+}
diff --git a/common/tests/name_test.c b/common/tests/name_test.c
new file mode 100644 (file)
index 0000000..ae47ebb
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2017, JANET(UK)
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of JANET(UK) nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include <trust_router/tr_name.h>
+
+/* returns 1 on success */
+int test_wildcard_prefix_match(const char *s, const char *wcs, int expect);
+
+int test_wildcards(void);
+
+int test_wildcards(void)
+{
+  /* various non-wildcard matches with mismatch in different places */
+  assert(test_wildcard_prefix_match("test", "test", 1));
+  assert(test_wildcard_prefix_match("test", "nest", 0));
+  assert(test_wildcard_prefix_match("test", "text", 0));
+  assert(test_wildcard_prefix_match("test", "tess", 0));
+  assert(test_wildcard_prefix_match("test", "tes", 0));
+  assert(test_wildcard_prefix_match("tes", "test", 0));
+  assert(test_wildcard_prefix_match("test", "tex", 0));
+  assert(test_wildcard_prefix_match("tex", "test", 0));
+
+  /* wildcard matches */
+  assert(test_wildcard_prefix_match("test", "*test", 1));
+  assert(test_wildcard_prefix_match("test", "*est", 1));
+  assert(test_wildcard_prefix_match("test", "*st", 1));
+  assert(test_wildcard_prefix_match("test", "*t", 1));
+  assert(test_wildcard_prefix_match("test", "*", 1));
+  assert(test_wildcard_prefix_match("test", "*text", 0));
+  assert(test_wildcard_prefix_match("test", "*ext", 0));
+  assert(test_wildcard_prefix_match("test", "*tests", 0));
+  assert(test_wildcard_prefix_match("test", "tes*", 0));
+  assert(test_wildcard_prefix_match("test", "test*", 0));
+  assert(test_wildcard_prefix_match("*", "*", 1));
+  assert(test_wildcard_prefix_match(" *", " *", 1));
+  assert(test_wildcard_prefix_match(" x", " *", 0));
+  assert(test_wildcard_prefix_match("*", "* ", 0));
+  assert(test_wildcard_prefix_match("test*", "*", 1));
+  assert(test_wildcard_prefix_match("test*", "**", 1));
+  assert(test_wildcard_prefix_match("testx", "**", 0));
+  return 1;
+
+}
+
+int test_wildcard_prefix_match(const char *s, const char *wcs, int expect)
+{
+  TR_NAME *str=tr_new_name(s);
+  TR_NAME *wc_str=tr_new_name(wcs);
+
+  assert(str);
+  assert(wc_str);
+
+  assert(expect==tr_name_prefix_wildcard_match(str, wc_str));
+
+  tr_free_name(str);
+  tr_free_name(wc_str);
+  return 1;
+}
+
+int main(void)
+{
+  assert(test_wildcards());
+
+  printf("Success.\n");
+  return 0;
+}
\ No newline at end of file
diff --git a/common/tests/test-filters/filt-inforec-1-msg.json b/common/tests/test-filters/filt-inforec-1-msg.json
new file mode 100644 (file)
index 0000000..94e97fb
--- /dev/null
@@ -0,0 +1,15 @@
+{
+  "msg_type": "trp_update",
+  "msg_body": {
+    "community": "my community",
+    "realm": "my realm",
+    "records": [
+      {
+        "record_type": "route",
+        "trust_router": "tr",
+        "metric": 27,
+        "interval": 11
+      }
+    ]
+  }
+}
\ No newline at end of file
diff --git a/common/tests/test-filters/filt-inforec-1.json b/common/tests/test-filters/filt-inforec-1.json
new file mode 100644 (file)
index 0000000..df5d1a1
--- /dev/null
@@ -0,0 +1,53 @@
+{
+  "local_organizations": [
+    { "organization_name": "inforec filter test 1",
+      "realms": [
+        { "realm": "realm",
+          "gss_names": ["gss"],
+          "filters": {
+            "tid_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "rp_realm",
+                    "match": [
+                      "a.realm",
+                      "*.a.realm"
+                    ]
+                  }
+                ]
+              }
+            ],
+            "trp_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["route"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ],
+            "trp_outbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["invalid value"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    }
+  ]
+}
diff --git a/common/tests/test-filters/filt-tidreq-1-msg.json b/common/tests/test-filters/filt-tidreq-1-msg.json
new file mode 100644 (file)
index 0000000..8497e83
--- /dev/null
@@ -0,0 +1,17 @@
+{
+  "msg_type": "tid_request",
+  "msg_body": {
+    "rp_realm": "my realm",
+    "target_realm": "your realm",
+    "community": "our community",
+    "orig_coi": "our aliased community",
+    "dh_info": {
+      "dh_p": "DEADBEEF",
+      "dh_g": "FEA57",
+      "dh_pub_key": "12345678"
+    },
+    "constraints": [{"constraint": ["value"]}],
+    "path": ["hop", "skip", "jump"],
+    "expiration_interval": 13
+  }
+}
\ No newline at end of file
diff --git a/common/tests/test-filters/filt-tidreq-1.json b/common/tests/test-filters/filt-tidreq-1.json
new file mode 100644 (file)
index 0000000..7325252
--- /dev/null
@@ -0,0 +1,53 @@
+{
+  "local_organizations": [
+    { "organization_name": "tidreq filter test 1",
+      "realms": [
+        { "realm": "realm",
+          "gss_names": ["gss"],
+          "filters": {
+            "tid_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "rp_realm",
+                    "match": [
+                      "my realm",
+                      "*.my realm"
+                    ]
+                  }
+                ]
+              }
+            ],
+            "trp_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["route"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ],
+            "trp_outbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["invalid value"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    }
+  ]
+}
diff --git a/common/tests/test-filters/filter-tests.json b/common/tests/test-filters/filter-tests.json
new file mode 100644 (file)
index 0000000..cca4a7d
--- /dev/null
@@ -0,0 +1,23 @@
+[
+  { "test label": "first TRP test",
+    "filter file": "test-filters/filt-inforec-1.json",
+    "filter type": "trp_inbound",
+    "target file": "test-filters/filt-inforec-1-msg.json",
+    "expect match": "yes",
+    "action": "accept"
+  },
+  { "test label": "second TRP test",
+    "filter file": "test-filters/filt-inforec-1.json",
+    "filter type": "trp_outbound",
+    "target file": "test-filters/filt-inforec-1-msg.json",
+    "expect match": "no",
+    "action": ""
+  },
+  { "test label": "first TID test",
+    "filter file": "test-filters/filt-tidreq-1.json",
+    "filter type": "tid_inbound",
+    "target file": "test-filters/filt-tidreq-1-msg.json",
+    "expect match": "yes",
+    "action": "accept"
+  }
+]
diff --git a/common/tests/test-filters/invalid-filt-repeated-key.json b/common/tests/test-filters/invalid-filt-repeated-key.json
new file mode 100644 (file)
index 0000000..5ff336f
--- /dev/null
@@ -0,0 +1,59 @@
+{
+  "local_organizations": [
+    { "organization_name": "invalid filter - repeated key",
+      "realms": [
+        { "realm": "realm",
+          "gss_names": ["gss"],
+          "filters": {
+            "tid_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "rp_realm",
+                    "match": [
+                      "a.realm",
+                      "*.a.realm"
+                    ]
+                  }
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ],
+            "tid_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["realm"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ],
+            "trp_outbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["realm"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    }
+  ]
+}
diff --git a/common/tests/test-filters/invalid-filt-unknown-field.json b/common/tests/test-filters/invalid-filt-unknown-field.json
new file mode 100644 (file)
index 0000000..92c56dd
--- /dev/null
@@ -0,0 +1,59 @@
+{
+  "local_organizations": [
+    { "organization_name": "invalid filter - unknown field",
+      "realms": [
+        { "realm": "realm",
+          "gss_names": ["gss"],
+          "filters": {
+            "tid_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "rp_realm",
+                    "match": [
+                      "a.realm",
+                      "*.a.realm"
+                    ]
+                  }
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ],
+            "trp_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "this is not a real field",
+                    "match": ["realm"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ],
+            "trp_outbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["realm"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    }
+  ]
+}
diff --git a/common/tests/test-filters/valid-filt.json b/common/tests/test-filters/valid-filt.json
new file mode 100644 (file)
index 0000000..b4fdfb3
--- /dev/null
@@ -0,0 +1,53 @@
+{
+  "local_organizations": [
+    { "organization_name": "valid filter test",
+      "realms": [
+        { "realm": "realm",
+          "gss_names": ["gss"],
+          "filters": {
+            "tid_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "rp_realm",
+                    "match": [
+                      "a.realm",
+                      "*.a.realm"
+                    ]
+                  }
+                ]
+              }
+            ],
+            "trp_inbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["realm"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ],
+            "trp_outbound": [
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["realm"]}
+                ]
+              },
+              { "action": "accept",
+                "specs": [
+                  { "field": "info_type",
+                    "match": ["community"]}
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    }
+  ]
+}
index 73c8023..3b177bb 100644 (file)
@@ -1411,40 +1411,76 @@ TR_REALM_ROLE tr_realm_role_from_str(const char *s)
   return TR_ROLE_UNKNOWN;
 }
 
-static void tr_comm_table_print_provenance(FILE *f, json_t *prov)
+static char *tr_comm_table_append_provenance(char *ctable_s, json_t *prov)
 {
   const char *s=NULL;
+  char *tmp=NULL;
   size_t ii=0;
 
   for (ii=0; ii<json_array_size(prov); ii++) {
     s=json_string_value(json_array_get(prov, ii));
-    if (s!=NULL)
-      fprintf(f, "%s%s", s, ((ii+1)==json_array_size(prov))?"":", ");
+    if (s!=NULL) {
+      tmp=talloc_asprintf_append(ctable_s, "%s%s", s, ((ii + 1) == json_array_size(prov)) ? "" : ", ");
+      if (tmp==NULL)
+        return NULL;
+      ctable_s=tmp;
+    }
   }
+  return ctable_s;
 }
 
-void tr_comm_table_print(FILE *f, TR_COMM_TABLE *ctab)
+char *tr_comm_table_to_str(TALLOC_CTX *mem_ctx, TR_COMM_TABLE *ctab)
 {
+  TALLOC_CTX *tmp_ctx=talloc_new(NULL);
+  char *ctable_s=NULL;
+  char *tmp=NULL;
+#define append_on_success_helper(tab,tmp,expr) if(NULL==((tmp)=(expr))){(tab)=NULL;goto cleanup;}(tab)=(tmp)
+
   TR_COMM_MEMB *p1=NULL; /* for walking the main list */
   TR_COMM_MEMB *p2=NULL; /* for walking the same-origin lists */
 
-  fprintf(f, ">> Membership table start <<\n");
+  ctable_s=talloc_asprintf(tmp_ctx, ">> Membership table start <<\n");
+  if (ctable_s==NULL)
+    goto cleanup;
+
   for (p1=ctab->memberships; p1!=NULL; p1=p1->next) {
-    fprintf(f, "* %s %s/%s\n  %s (%p) - prov: ",
-            tr_realm_role_to_str(tr_comm_memb_get_role(p1)),
-            tr_comm_memb_get_realm_id(p1)->buf,
-            tr_comm_get_id(tr_comm_memb_get_comm(p1))->buf,
-            (tr_comm_memb_get_origin(p1)==NULL)?"null origin":(tr_comm_memb_get_origin(p1)->buf),
-            p1);
-    tr_comm_table_print_provenance(f, p1->provenance);
-    fprintf(f, "\n");
+    append_on_success_helper(
+        ctable_s, tmp,
+        talloc_asprintf_append(ctable_s, "* %s %s/%s\n  %s (%p) - prov: ",
+                               tr_realm_role_to_str(tr_comm_memb_get_role(p1)),
+                               tr_comm_memb_get_realm_id(p1)->buf,
+                               tr_comm_get_id(tr_comm_memb_get_comm(p1))->buf,
+                               (tr_comm_memb_get_origin(p1)==NULL)?"null origin":(tr_comm_memb_get_origin(p1)->buf),
+                               p1));
+
+    append_on_success_helper(ctable_s, tmp, tr_comm_table_append_provenance(ctable_s, p1->provenance));
+
+    append_on_success_helper(ctable_s, tmp, talloc_strdup_append_buffer(ctable_s, "\n"));
+
     for (p2=p1->origin_next; p2!=NULL; p2=p2->origin_next) {
-      fprintf(f, "  %s (%p) - prov: ",
-              (tr_comm_memb_get_origin(p2)==NULL)?"null origin":(tr_comm_memb_get_origin(p2)->buf),
-              p2);
-      tr_comm_table_print_provenance(f, p2->provenance);
-      fprintf(f, "\n");
+      append_on_success_helper(
+          ctable_s, tmp,
+          talloc_asprintf_append(ctable_s, "  %s (%p) - prov: ",
+          (tr_comm_memb_get_origin(p2)==NULL)?"null origin":(tr_comm_memb_get_origin(p2)->buf),
+              p2));
+      append_on_success_helper(ctable_s, tmp, tr_comm_table_append_provenance(ctable_s, p2->provenance));
+      append_on_success_helper(ctable_s, tmp, talloc_strdup_append_buffer(ctable_s, "\n"));
     }
-    fprintf(f, "\n");
+    append_on_success_helper(ctable_s, tmp, talloc_strdup_append_buffer(ctable_s, "\n"));
   }
+
+cleanup:
+  if (ctable_s!=NULL)
+    talloc_steal(mem_ctx, ctable_s);
+
+  talloc_free(tmp_ctx);
+  return ctable_s;
 }
+
+void tr_comm_table_print(FILE *f, TR_COMM_TABLE *ctab)
+{
+  char *s=tr_comm_table_to_str(NULL, ctab);
+  if (s!=NULL)
+    fprintf(f, "%s", s);
+  talloc_free(s);
+}
\ No newline at end of file
index b451860..4fa6506 100644 (file)
 #include <tr.h>
 #include <trust_router/trp.h>
 
+#if JANSSON_VERSION_HEX < 0x020500
+#include "jansson_iterators.h"
+#endif
+
 void tr_print_config (TR_CFG *cfg) {
   tr_notice("tr_print_config: Logging running trust router configuration.");
   tr_print_comms(cfg->ctable);
@@ -412,28 +416,31 @@ static TR_CONSTRAINT *tr_cfg_parse_one_constraint(TALLOC_CTX *mem_ctx, char *cty
 
 static TR_FILTER *tr_cfg_parse_one_filter(TALLOC_CTX *mem_ctx, json_t *jfilt, TR_FILTER_TYPE ftype, TR_CFG_RC *rc)
 {
-  TALLOC_CTX *tmp_ctx=talloc_new(NULL);
-  TR_FILTER *filt=NULL;
-  json_t *jfaction=NULL;
-  json_t *jfspecs=NULL;
-  json_t *jffield=NULL;
-  json_t *jfmatch=NULL;
-  json_t *jrc=NULL;
-  json_t *jdc=NULL;
-  TR_NAME *name=NULL;
-  int i=0, j=0;
-
-  *rc=TR_CFG_ERROR;
-
-  if ((jfilt==NULL) || (rc==NULL)) {
+  TALLOC_CTX *tmp_ctx = talloc_new(NULL);
+  TR_FILTER *filt = NULL;
+  json_t *jfaction = NULL;
+  json_t *jfline = NULL;
+  json_t *jfspecs = NULL;
+  json_t *this_jfspec = NULL;
+  json_t *jfield = NULL;
+  json_t *jmatch = NULL;
+  json_t *jrc = NULL;
+  json_t *jdc = NULL;
+  json_t *this_jmatch = NULL;
+  TR_NAME *name = NULL;
+  size_t i = 0, j = 0, k = 0;
+
+  *rc = TR_CFG_ERROR;
+
+  if ((jfilt == NULL) || (rc == NULL)) {
     tr_err("tr_cfg_parse_one_filter: null argument");
-    *rc=TR_CFG_BAD_PARAMS;
+    *rc = TR_CFG_BAD_PARAMS;
     goto cleanup;
   }
-    
-  if (NULL==(filt=tr_filter_new(tmp_ctx))) {
+
+  if (NULL == (filt = tr_filter_new(tmp_ctx))) {
     tr_err("tr_cfg_parse_one_filter: Out of memory.");
-    *rc=TR_CFG_NOMEM;
+    *rc = TR_CFG_NOMEM;
     goto cleanup;
   }
   tr_filter_set_type(filt, ftype);
@@ -441,139 +448,169 @@ static TR_FILTER *tr_cfg_parse_one_filter(TALLOC_CTX *mem_ctx, json_t *jfilt, TR
   /* make sure we have space to represent the filter */
   if (json_array_size(jfilt) > TR_MAX_FILTER_LINES) {
     tr_err("tr_cfg_parse_one_filter: Filter has too many lines, maximum of %d.", TR_MAX_FILTER_LINES);
-    *rc=TR_CFG_NOPARSE;
+    *rc = TR_CFG_NOPARSE;
     goto cleanup;
   }
 
   /* For each entry in the filter... */
-  for (i=0; i < json_array_size(jfilt); i++) {
-    if ((NULL==(jfaction=json_object_get(json_array_get(jfilt, i), "action"))) ||
+  json_array_foreach(jfilt, i, jfline) {
+    if ((NULL == (jfaction = json_object_get(jfline, "action"))) ||
         (!json_is_string(jfaction))) {
       tr_debug("tr_cfg_parse_one_filter: Error parsing filter action.");
-      *rc=TR_CFG_NOPARSE;
+      *rc = TR_CFG_NOPARSE;
       goto cleanup;
     }
-    if ((NULL==(jfspecs=json_object_get(json_array_get(jfilt, i), "specs"))) ||
+
+    if ((NULL == (jfspecs = json_object_get(jfline, "specs"))) ||
         (!json_is_array(jfspecs)) ||
-        (0==json_array_size(jfspecs))) {
+        (0 == json_array_size(jfspecs))) {
       tr_debug("tr_cfg_parse_one_filter: Error parsing filter specs.");
-      *rc=TR_CFG_NOPARSE;
+      *rc = TR_CFG_NOPARSE;
       goto cleanup;
     }
-  
+
     if (TR_MAX_FILTER_SPECS < json_array_size(jfspecs)) {
       tr_debug("tr_cfg_parse_one_filter: Filter has too many specs, maximimum of %d.", TR_MAX_FILTER_SPECS);
-      *rc=TR_CFG_NOPARSE;
+      *rc = TR_CFG_NOPARSE;
       goto cleanup;
     }
 
-    if (NULL==(filt->lines[i]=tr_fline_new(filt))) {
-      tr_debug("tr_cfg_parse_one_filter: Out of memory allocating filter line %d.", i+1);
-      *rc=TR_CFG_NOMEM;
+    if (NULL == (filt->lines[i] = tr_fline_new(filt))) {
+      tr_debug("tr_cfg_parse_one_filter: Out of memory allocating filter line %d.", i + 1);
+      *rc = TR_CFG_NOMEM;
       goto cleanup;
     }
 
     if (!strcmp(json_string_value(jfaction), "accept")) {
-      filt->lines[i]->action=TR_FILTER_ACTION_ACCEPT;
-    }
-    else if (!strcmp(json_string_value(jfaction), "reject")) {
-      filt->lines[i]->action=TR_FILTER_ACTION_REJECT;
-    }
-    else {
-      tr_debug("tr_cfg_parse_one_filter: Error parsing filter action, unknown action' %s'.", json_string_value(jfaction));
-      *rc=TR_CFG_NOPARSE;
+      filt->lines[i]->action = TR_FILTER_ACTION_ACCEPT;
+    } else if (!strcmp(json_string_value(jfaction), "reject")) {
+      filt->lines[i]->action = TR_FILTER_ACTION_REJECT;
+    } else {
+      tr_debug("tr_cfg_parse_one_filter: Error parsing filter action, unknown action' %s'.",
+               json_string_value(jfaction));
+      *rc = TR_CFG_NOPARSE;
       goto cleanup;
     }
 
-    if (NULL!=(jrc=json_object_get(json_array_get(jfilt, i), "realm_constraints"))) {
+    if (NULL != (jrc = json_object_get(jfline, "realm_constraints"))) {
       if (!json_is_array(jrc)) {
         tr_err("tr_cfg_parse_one_filter: cannot parse realm_constraints, not an array.");
-        *rc=TR_CFG_NOPARSE;
+        *rc = TR_CFG_NOPARSE;
         goto cleanup;
-      } else if (json_array_size(jrc)>TR_MAX_CONST_MATCHES) {
+      } else if (json_array_size(jrc) > TR_MAX_CONST_MATCHES) {
         tr_err("tr_cfg_parse_one_filter: realm_constraints has too many entries, maximum of %d.",
                TR_MAX_CONST_MATCHES);
-        *rc=TR_CFG_NOPARSE;
+        *rc = TR_CFG_NOPARSE;
         goto cleanup;
-      } else if (json_array_size(jrc)>0) {
+      } else if (json_array_size(jrc) > 0) {
         /* ok we actually have entries to process */
-        if (NULL==(filt->lines[i]->realm_cons=tr_cfg_parse_one_constraint(filt->lines[i], "realm", jrc, rc))) {
+        if (NULL == (filt->lines[i]->realm_cons = tr_cfg_parse_one_constraint(filt->lines[i], "realm", jrc, rc))) {
           tr_debug("tr_cfg_parse_one_filter: Error parsing realm constraint");
-          *rc=TR_CFG_NOPARSE;
+          *rc = TR_CFG_NOPARSE;
           goto cleanup;
         }
       }
     }
 
-    if (NULL!=(jdc=json_object_get(json_array_get(jfilt, i), "domain_constraints"))) {
+    if (NULL != (jdc = json_object_get(jfline, "domain_constraints"))) {
       if (!json_is_array(jdc)) {
         tr_err("tr_cfg_parse_one_filter: cannot parse domain_constraints, not an array.");
-        *rc=TR_CFG_NOPARSE;
+        *rc = TR_CFG_NOPARSE;
         goto cleanup;
-      } else if (json_array_size(jdc)>TR_MAX_CONST_MATCHES) {
+      } else if (json_array_size(jdc) > TR_MAX_CONST_MATCHES) {
         tr_err("tr_cfg_parse_one_filter: domain_constraints has too many entries, maximum of %d.",
                TR_MAX_CONST_MATCHES);
-        *rc=TR_CFG_NOPARSE;
+        *rc = TR_CFG_NOPARSE;
         goto cleanup;
-      } else if (json_array_size(jdc)>0) {
-        if (NULL==(filt->lines[i]->domain_cons=tr_cfg_parse_one_constraint(filt->lines[i], "domain", jdc, rc))) {
+      } else if (json_array_size(jdc) > 0) {
+        if (NULL == (filt->lines[i]->domain_cons = tr_cfg_parse_one_constraint(filt->lines[i], "domain", jdc, rc))) {
           tr_debug("tr_cfg_parse_one_filter: Error parsing domain constraint");
-          *rc=TR_CFG_NOPARSE;
+          *rc = TR_CFG_NOPARSE;
           goto cleanup;
         }
       }
     }
 
     /*For each filter spec within the filter line... */
-    for (j=0; j <json_array_size(jfspecs); j++) {
-      if ((NULL==(jffield=json_object_get(json_array_get(jfspecs, j), "field"))) ||
-          (!json_is_string(jffield))) {
-        tr_debug("tr_cfg_parse_one_filter: Error parsing filter: missing field for filer spec %d, filter line %d.", i, j);
-        *rc=TR_CFG_NOPARSE;
+    json_array_foreach(jfspecs, j, this_jfspec) {
+      if ((NULL == (jfield = json_object_get(this_jfspec, "field"))) ||
+          (!json_is_string(jfield))) {
+        tr_debug("tr_cfg_parse_one_filter: Error parsing filter: missing field for filer spec %d, filter line %d.", i,
+                 j);
+        *rc = TR_CFG_NOPARSE;
         goto cleanup;
       }
 
       /* check that we have a match attribute */
-      if (NULL==(jfmatch=json_object_get(json_array_get(jfspecs, j), "match"))) {
-        tr_debug("tr_cfg_parse_one_filter: Error parsing filter: missing match for filer spec %d, filter line %d.", i, j);
-        *rc=TR_CFG_NOPARSE;
+      if (NULL == (jmatch = json_object_get(this_jfspec, "match"))) {
+        tr_debug("tr_cfg_parse_one_filter: Error parsing filter: missing match for filer spec %d, filter line %d.", i,
+                 j);
+        *rc = TR_CFG_NOPARSE;
         goto cleanup;
       }
 
-      /* check that match is a string */
-      if (!json_is_string(jfmatch)) {
-        tr_debug("tr_cfg_parse_one_filter: Error parsing filter: match not a string for filter spec %d, filter line %d.", i, j);
-        *rc=TR_CFG_NOPARSE;
+      /* check that match is a string or an array */
+      if ((!json_is_string(jmatch)) && (!json_is_array(jmatch))) {
+        tr_debug(
+            "tr_cfg_parse_one_filter: Error parsing filter: match not a string or array for filter spec %d, filter line %d.",
+            i, j);
+        *rc = TR_CFG_NOPARSE;
         goto cleanup;
       }
 
       /* allocate the filter spec */
-      if (NULL==(filt->lines[i]->specs[j]=tr_fspec_new(filt->lines[i]))) {
+      if (NULL == (filt->lines[i]->specs[j] = tr_fspec_new(filt->lines[i]))) {
         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
-        *rc=TR_CFG_NOMEM;
+        *rc = TR_CFG_NOMEM;
         goto cleanup;
       }
 
       /* fill in the field */
-      if (NULL==(filt->lines[i]->specs[j]->field=tr_new_name(json_string_value(jffield)))) {
+      if (NULL == (filt->lines[i]->specs[j]->field = tr_new_name(json_string_value(jfield)))) {
         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
-        *rc=TR_CFG_NOMEM;
+        *rc = TR_CFG_NOMEM;
         goto cleanup;
       }
 
       /* fill in the matches */
-      if (NULL==(name=tr_new_name(json_string_value(jfmatch)))) {
-        tr_debug("tr_cfg_parse_one_filter: Out of memory.");
-        *rc=TR_CFG_NOMEM;
+      if (json_is_string(jmatch)) {
+        if (NULL == (name = tr_new_name(json_string_value(jmatch)))) {
+          tr_debug("tr_cfg_parse_one_filter: Out of memory.");
+          *rc = TR_CFG_NOMEM;
+          goto cleanup;
+        }
+        tr_fspec_add_match(filt->lines[i]->specs[j], name);
+      } else {
+        /* jmatch is an array (we checked earlier) */
+        json_array_foreach(jmatch, k, this_jmatch) {
+          if (NULL == (name = tr_new_name(json_string_value(this_jmatch)))) {
+            tr_debug("tr_cfg_parse_one_filter: Out of memory.");
+            *rc = TR_CFG_NOMEM;
+            goto cleanup;
+          }
+          tr_fspec_add_match(filt->lines[i]->specs[j], name);
+        }
+      }
+      if (!tr_filter_validate_spec_field(ftype, filt->lines[i]->specs[j])){
+        tr_debug("tr_cfg_parse_one_filter: Invalid filter field \"%.*s\" for %s filter, spec %d, filter %d.",
+                 filt->lines[i]->specs[j]->field->len,
+                 filt->lines[i]->specs[j]->field->buf,
+                 tr_filter_type_to_string(filt->type),
+                 i, j);
+        *rc = TR_CFG_ERROR;
         goto cleanup;
       }
-      tr_fspec_set_match(filt->lines[i]->specs[j], name);
     }
   }
-  *rc=TR_CFG_SUCCESS;
-  talloc_steal(mem_ctx, filt);
-  
+
+  /* check that the filter is valid */
+  if (!tr_filter_validate(filt)) {
+    *rc = TR_CFG_ERROR;
+  } else {
+    *rc = TR_CFG_SUCCESS;
+    talloc_steal(mem_ctx, filt);
+  }
+
  cleanup:
   talloc_free(tmp_ctx);
   if (*rc!=TR_CFG_SUCCESS)
@@ -581,11 +618,14 @@ static TR_FILTER *tr_cfg_parse_one_filter(TALLOC_CTX *mem_ctx, json_t *jfilt, TR
   return filt;
 }
 
-static TR_FILTER *tr_cfg_parse_filters(TALLOC_CTX *mem_ctx, json_t *jfilts, TR_CFG_RC *rc)
+static TR_FILTER_SET *tr_cfg_parse_filters(TALLOC_CTX *mem_ctx, json_t *jfilts, TR_CFG_RC *rc)
 {
   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
   json_t *jfilt;
+  const char *filt_label=NULL;
   TR_FILTER *filt=NULL;
+  TR_FILTER_SET *filt_set=NULL;
+  TR_FILTER_TYPE filt_type=TR_FILTER_TYPE_UNKNOWN;
 
   *rc=TR_CFG_ERROR;
 
@@ -595,32 +635,52 @@ static TR_FILTER *tr_cfg_parse_filters(TALLOC_CTX *mem_ctx, json_t *jfilts, TR_C
     goto cleanup;
   }
 
-  jfilt=json_object_get(jfilts, "tid_inbound");
-  if (jfilt!=NULL) {
-    filt=tr_cfg_parse_one_filter(tmp_ctx, jfilt, TR_FILTER_TYPE_TID_INCOMING, rc);
-    if (*rc!=TR_CFG_SUCCESS) {
-      tr_debug("tr_cfg_parse_filters: Error parsing tid_inbound filter.");
-      *rc=TR_CFG_NOPARSE;
+  filt_set=tr_filter_set_new(tmp_ctx);
+  if (filt_set==NULL) {
+    tr_debug("tr_cfg_parse_filters: Unable to allocate filter set.");
+    *rc = TR_CFG_NOMEM;
+    goto cleanup;
+  }
+
+  json_object_foreach(jfilts, filt_label, jfilt) {
+    /* check that we got a filter */
+    if (jfilt == NULL) {
+      tr_debug("tr_cfg_parse_filters: Definition for %s filter is missing.", filt_label);
+      *rc = TR_CFG_NOPARSE;
+      goto cleanup;
+    }
+
+    /* check that we recognize the filter type */
+    filt_type=tr_filter_type_from_string(filt_label);
+    if (filt_type==TR_FILTER_TYPE_UNKNOWN) {
+      tr_debug("tr_cfg_parse_filters: Unrecognized filter (%s) defined.", filt_label);
+      *rc = TR_CFG_NOPARSE;
+      goto cleanup;
+    }
+
+    /* finally, parse the filter */
+    tr_debug("tr_cfg_parse_filters: Found %s filter.", filt_label);
+    filt = tr_cfg_parse_one_filter(tmp_ctx, jfilt, filt_type, rc);
+    tr_filter_set_add(filt_set, filt);
+    if (*rc != TR_CFG_SUCCESS) {
+      tr_debug("tr_cfg_parse_filters: Error parsing %s filter.", filt_label);
+      *rc = TR_CFG_NOPARSE;
       goto cleanup;
     }
-  } else {
-    tr_debug("tr_cfg_parse_filters: Unknown filter types in filter block.");
-    *rc=TR_CFG_NOPARSE;
-    goto cleanup;
   }
-  
+
   *rc=TR_CFG_SUCCESS;
 
  cleanup:
   if (*rc==TR_CFG_SUCCESS)
-    talloc_steal(mem_ctx, filt);
-  else if (filt!=NULL) {
-    talloc_free(filt);
-    filt=NULL;
+    talloc_steal(mem_ctx, filt_set);
+  else if (filt_set!=NULL) {
+    talloc_free(filt_set);
+    filt_set=NULL;
   }
 
   talloc_free(tmp_ctx);
-  return filt;
+  return filt_set;
 }
 
 static TR_AAA_SERVER *tr_cfg_parse_one_aaa_server(TALLOC_CTX *mem_ctx, json_t *jaddr, TR_CFG_RC *rc)
@@ -1091,10 +1151,11 @@ static TR_GSS_NAMES *tr_cfg_parse_gss_names(TALLOC_CTX *mem_ctx, json_t *jgss_na
 }
 
 /* default filter accepts realm and *.realm */
-static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_CFG_RC *rc)
+static TR_FILTER_SET *tr_cfg_default_filters(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_CFG_RC *rc)
 {
   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
   TR_FILTER *filt=NULL;
+  TR_FILTER_SET *filt_set=NULL;
   TR_CONSTRAINT *cons=NULL;
   TR_NAME *name=NULL;
   TR_NAME *n_prefix=tr_new_name("*.");
@@ -1105,7 +1166,7 @@ static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_
   
 
   if ((realm==NULL) || (rc==NULL)) {
-    tr_debug("tr_cfg_default_filter: invalid arguments.");
+    tr_debug("tr_cfg_default_filters: invalid arguments.");
     if (rc!=NULL)
       *rc=TR_CFG_BAD_PARAMS;
     goto cleanup;
@@ -1116,21 +1177,21 @@ static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_
       (n_rp_realm_2==NULL) ||
       (n_domain==NULL) ||
       (n_realm==NULL)) {
-    tr_debug("tr_cfg_default_filter: unable to allocate names.");
+    tr_debug("tr_cfg_default_filters: unable to allocate names.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
 
   filt=tr_filter_new(tmp_ctx);
   if (filt==NULL) {
-    tr_debug("tr_cfg_default_filter: could not allocate filter.");
+    tr_debug("tr_cfg_default_filters: could not allocate filter.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
-  tr_filter_set_type(filt, TR_FILTER_TYPE_TID_INCOMING);
+  tr_filter_set_type(filt, TR_FILTER_TYPE_TID_INBOUND);
   filt->lines[0]=tr_fline_new(filt);
   if (filt->lines[0]==NULL) {
-    tr_debug("tr_cfg_default_filter: could not allocate filter line.");
+    tr_debug("tr_cfg_default_filters: could not allocate filter line.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
@@ -1142,11 +1203,11 @@ static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_
 
   name=tr_dup_name(realm);
   if (name==NULL) {
-    tr_debug("tr_cfg_default_filter: could not allocate realm name.");
+    tr_debug("tr_cfg_default_filters: could not allocate realm name.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
-  tr_fspec_set_match(filt->lines[0]->specs[0], name);
+  tr_fspec_add_match(filt->lines[0]->specs[0], name);
   name=NULL; /* we no longer own the name */
 
   /* now do the wildcard name */
@@ -1155,17 +1216,17 @@ static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_
   n_rp_realm_2=NULL; /* we don't own this name any more */
 
   if (NULL==(name=tr_name_cat(n_prefix, realm))) {
-    tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name.");
+    tr_debug("tr_cfg_default_filters: could not allocate wildcard realm name.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
 
-  tr_fspec_set_match(filt->lines[0]->specs[1], name);
+  tr_fspec_add_match(filt->lines[0]->specs[1], name);
   name=NULL; /* we no longer own the name */
 
   /* domain constraint */
   if (NULL==(cons=tr_constraint_new(filt->lines[0]))) {
-    tr_debug("tr_cfg_default_filter: could not allocate domain constraint.");
+    tr_debug("tr_cfg_default_filters: could not allocate domain constraint.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
@@ -1174,14 +1235,14 @@ static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_
   n_domain=NULL; /* belongs to the constraint now */
   name=tr_dup_name(realm);
   if (name==NULL) {
-    tr_debug("tr_cfg_default_filter: could not allocate realm name for domain constraint.");
+    tr_debug("tr_cfg_default_filters: could not allocate realm name for domain constraint.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
   cons->matches[0]=name;
   name=tr_name_cat(n_prefix, realm);
   if (name==NULL) {
-    tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name for domain constraint.");
+    tr_debug("tr_cfg_default_filters: could not allocate wildcard realm name for domain constraint.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
@@ -1192,7 +1253,7 @@ static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_
 
   /* realm constraint */
   if (NULL==(cons=tr_constraint_new(filt->lines[0]))) {
-    tr_debug("tr_cfg_default_filter: could not allocate realm constraint.");
+    tr_debug("tr_cfg_default_filters: could not allocate realm constraint.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
@@ -1201,14 +1262,14 @@ static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_
   n_realm=NULL; /* belongs to the constraint now */
   name=tr_dup_name(realm);
   if (name==NULL) {
-    tr_debug("tr_cfg_default_filter: could not allocate realm name for realm constraint.");
+    tr_debug("tr_cfg_default_filters: could not allocate realm name for realm constraint.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
   cons->matches[0]=name;
   name=tr_name_cat(n_prefix, realm);
   if (name==NULL) {
-    tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name for realm constraint.");
+    tr_debug("tr_cfg_default_filters: could not allocate wildcard realm name for realm constraint.");
     *rc=TR_CFG_NOMEM;
     goto cleanup;
   }
@@ -1216,7 +1277,15 @@ static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_
   name=NULL;
   filt->lines[0]->realm_cons=cons;
 
-  talloc_steal(mem_ctx, filt);
+  /* put the filter in a set */
+  filt_set=tr_filter_set_new(tmp_ctx);
+  if ((filt_set==NULL)||(0!=tr_filter_set_add(filt_set, filt))) {
+    tr_debug("tr_cfg_default_filters: could not allocate filter set.");
+    *rc=TR_CFG_NOMEM;
+    goto cleanup;
+  }
+  talloc_steal(mem_ctx, filt_set);
+
 cleanup:
   talloc_free(tmp_ctx);
 
@@ -1236,7 +1305,7 @@ cleanup:
   if (name!=NULL)
     tr_free_name(name);
 
-  return filt;
+  return filt_set;
 }
 
 /* parses rp client */
@@ -1245,7 +1314,7 @@ static TR_RP_CLIENT *tr_cfg_parse_one_rp_client(TALLOC_CTX *mem_ctx, json_t *jre
   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
   TR_RP_CLIENT *client=NULL;
   TR_CFG_RC call_rc=TR_CFG_ERROR;
-  TR_FILTER *new_filt=NULL;
+  TR_FILTER_SET *new_filts=NULL;
   TR_NAME *realm=NULL;
   json_t *jfilt=NULL;
   json_t *jrealm_id=NULL;
@@ -1290,7 +1359,7 @@ static TR_RP_CLIENT *tr_cfg_parse_one_rp_client(TALLOC_CTX *mem_ctx, json_t *jre
   /* parse filters */
   jfilt=json_object_get(jrealm, "filters");
   if (jfilt!=NULL) {
-    new_filt=tr_cfg_parse_filters(tmp_ctx, jfilt, &call_rc);
+    new_filts=tr_cfg_parse_filters(tmp_ctx, jfilt, &call_rc);
     if (call_rc!=TR_CFG_SUCCESS) {
       tr_err("tr_cfg_parse_one_rp_client: could not parse filters.");
       *rc=TR_CFG_NOPARSE;
@@ -1298,7 +1367,7 @@ static TR_RP_CLIENT *tr_cfg_parse_one_rp_client(TALLOC_CTX *mem_ctx, json_t *jre
     }
   } else {
     tr_debug("tr_cfg_parse_one_rp_client: no filters specified, using default filters.");
-    new_filt=tr_cfg_default_filter(tmp_ctx, realm, &call_rc);
+    new_filts= tr_cfg_default_filters(tmp_ctx, realm, &call_rc);
     if (call_rc!=TR_CFG_SUCCESS) {
       tr_err("tr_cfg_parse_one_rp_client: could not set default filters.");
       *rc=TR_CFG_NOPARSE;
@@ -1306,24 +1375,24 @@ static TR_RP_CLIENT *tr_cfg_parse_one_rp_client(TALLOC_CTX *mem_ctx, json_t *jre
     }
   }
 
-  tr_rp_client_set_filter(client, new_filt);
+  tr_rp_client_set_filters(client, new_filts);
   *rc=TR_CFG_SUCCESS;
 
   cleanup:
   if (realm!=NULL)
     tr_free_name(realm);
 
-    if (*rc==TR_CFG_SUCCESS)
-      talloc_steal(mem_ctx, client);
-    else {
-      talloc_free(client);
-      client=NULL;
-    }
-
-    talloc_free(tmp_ctx);
-    return client;
+  if (*rc==TR_CFG_SUCCESS)
+    talloc_steal(mem_ctx, client);
+  else {
+    talloc_free(client);
+    client=NULL;
   }
 
+  talloc_free(tmp_ctx);
+  return client;
+}
+
   /* Determine whether the realm is an RP realm */
 static int tr_cfg_is_rp_realm(json_t *jrealm)
 {
@@ -1511,7 +1580,7 @@ cleanup:
 static TR_CFG_RC tr_cfg_parse_local_orgs(TR_CFG *trc, json_t *jcfg)
 {
   json_t *jlocorgs=NULL;
-  int ii=0;
+  size_t ii=0;
 
   jlocorgs=json_object_get(jcfg, "local_organizations");
   if (jlocorgs==NULL)
@@ -1538,13 +1607,16 @@ static TR_CFG_RC tr_cfg_parse_one_peer_org(TR_CFG *trc, json_t *jporg)
   json_t *jhost=NULL;
   json_t *jport=NULL;
   json_t *jgss=NULL;
+  json_t *jfilt=NULL;
   TRP_PEER *new_peer=NULL;
   TR_GSS_NAMES *names=NULL;
+  TR_FILTER_SET *filt_set=NULL;
   TR_CFG_RC rc=TR_CFG_ERROR;
 
   jhost=json_object_get(jporg, "hostname");
   jport=json_object_get(jporg, "port");
   jgss=json_object_get(jporg, "gss_names");
+  jfilt=json_object_get(jporg, "filters");
 
   if ((jhost==NULL) || (!json_is_string(jhost))) {
     tr_err("tr_cfg_parse_one_peer_org: hostname not specified or not a string.");
@@ -1558,13 +1630,19 @@ static TR_CFG_RC tr_cfg_parse_one_peer_org(TR_CFG *trc, json_t *jporg)
     rc=TR_CFG_NOPARSE;
     goto cleanup;
   }
-  
+
   if ((jgss==NULL) || (!json_is_array(jgss))) {
     tr_err("tr_cfg_parse_one_peer_org: gss_names not specified or not an array.");
     rc=TR_CFG_NOPARSE;
     goto cleanup;
   }
 
+  if ((jfilt!=NULL) && (!json_is_object(jfilt))) {
+    tr_err("tr_cfg_parse_one_peer_org: filters is not an object.");
+    rc=TR_CFG_NOPARSE;
+    goto cleanup;
+  }
+
   new_peer=trp_peer_new(tmp_ctx);
   if (new_peer==NULL) {
     tr_err("tr_cfg_parse_one_peer_org: could not allocate new peer.");
@@ -1586,6 +1664,16 @@ static TR_CFG_RC tr_cfg_parse_one_peer_org(TR_CFG *trc, json_t *jporg)
   }
   trp_peer_set_gss_names(new_peer, names);
 
+  if (jfilt) {
+    filt_set=tr_cfg_parse_filters(tmp_ctx, jfilt, &rc);
+    if (rc!=TR_CFG_SUCCESS) {
+      tr_err("tr_cfg_parse_one_peer_org: unable to parse filters.");
+      rc=TR_CFG_NOPARSE;
+      goto cleanup;
+    }
+    trp_peer_set_filters(new_peer, filt_set);
+  }
+
   /* success! */
   trp_ptable_add(trc->peers, new_peer);
   rc=TR_CFG_SUCCESS;
@@ -1654,7 +1742,9 @@ static TR_CFG_RC tr_cfg_parse_default_servers (TR_CFG *trc, json_t *jcfg)
 static void tr_cfg_parse_comm_idps(TR_CFG *trc, json_t *jidps, TR_COMM *comm, TR_CFG_RC *rc)
 {
   TR_IDP_REALM *found_idp=NULL;
-  int i = 0;
+  json_t *jidp_name=NULL;
+  TR_NAME *idp_name=NULL;
+  size_t ii = 0;
 
   if ((!trc) ||
       (!jidps) ||
@@ -1664,13 +1754,17 @@ static void tr_cfg_parse_comm_idps(TR_CFG *trc, json_t *jidps, TR_COMM *comm, TR
     return;
   }
 
-  for (i=0; i < json_array_size(jidps); i++) {
-    found_idp=tr_cfg_find_idp(trc, 
-                              tr_new_name((char *)json_string_value(json_array_get(jidps, i))), 
-                              rc);
+  json_array_foreach(jidps, ii, jidp_name) {
+    idp_name=tr_new_name(json_string_value(jidp_name));
+    if (idp_name==NULL) {
+      *rc = TR_CFG_NOMEM;
+      return;
+    }
+    found_idp=tr_cfg_find_idp(trc, idp_name, rc);
+    tr_free_name(idp_name);
+
     if ((found_idp==NULL) || (*rc!=TR_CFG_SUCCESS)) {
-      tr_debug("tr_cfg_parse_comm_idps: Unknown IDP %s.", 
-               (char *)json_string_value(json_array_get(jidps, i)));
+      tr_debug("tr_cfg_parse_comm_idps: Unknown IDP %s.", json_string_value(jidp_name));
       *rc=TR_CFG_ERROR;
       return;
     }
@@ -1830,16 +1924,26 @@ static TR_COMM *tr_cfg_parse_one_comm (TALLOC_CTX *mem_ctx, TR_CFG *trc, json_t
     json_t *jexpire  = json_object_get(jcomm, "expiration_interval");
     comm->expiration_interval = 43200; /*30 days*/
     if (jexpire) {
-       if (!json_is_integer(jexpire)) {
-         fprintf(stderr, "tr_parse_one_comm: expiration_interval is not an integer\n");
-    comm=NULL;
-    goto cleanup;
-       }
-       comm->expiration_interval = json_integer_value(jexpire);
-       if (comm->expiration_interval <= 10)
-         comm->expiration_interval = 11; /* Freeradius waits 10 minutes between successful TR queries*/
-       if (comm->expiration_interval > 129600) /* 90 days*/
-       comm->expiration_interval = 129600;
+      if (!json_is_integer(jexpire)) {
+        tr_err("tr_parse_one_comm: expiration_interval is not an integer for comm %.*s",
+                 tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
+        comm=NULL;
+        goto cleanup;
+      }
+      comm->expiration_interval = json_integer_value(jexpire);
+      if (comm->expiration_interval <= 10) {
+        comm->expiration_interval = 11; /* Freeradius waits 10 minutes between successful TR queries*/
+        tr_notice(
+            "tr_parse_one_comm: expiration interval for %.*s less than minimum of 11 minutes; using 11 minutes instead.",
+            tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
+      }
+      if (comm->expiration_interval > 129600) {
+        /* > 90 days*/
+        comm->expiration_interval = 129600;
+        tr_notice(
+            "tr_parse_one_comm: expiration interval for %.*s exceeds maximum of 90 days; using 90 days instead.",
+            tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
+      }
     }
   }
 
@@ -1937,7 +2041,7 @@ TR_CFG_RC tr_cfg_parse_one_config_file(TR_CFG *cfg, const char *file_with_path)
   json_error_t rc;
 
   if (NULL==(jcfg=json_load_file(file_with_path, 
-                                 JSON_DISABLE_EOF_CHECK, &rc))) {
+                                 JSON_DISABLE_EOF_CHECK|JSON_REJECT_DUPLICATES, &rc))) {
     tr_debug("tr_cfg_parse_one_config_file: Error parsing config file %s.", 
              file_with_path);
     tr_cfg_log_json_error("tr_cfg_parse_one_config_file", &rc);
index a155566..da5f42e 100644 (file)
  *
  */
 #include <jansson.h>
+#if JANSSON_VERSION_HEX < 0x020500
 #include "jansson_iterators.h"
+#endif
 #include <assert.h>
 #include <talloc.h>
 
-#include <tr_filter.h>
-#include <tr_debug.h>
-
 #include <trust_router/tr_constraint.h>
+#include <tr_filter.h>
 #include <tid_internal.h>
+#include <tr_debug.h>
 
 
 static int tr_constraint_destructor(void *obj)
 {
-  TR_CONSTRAINT *cons=talloc_get_type_abort(obj, TR_CONSTRAINT);
-  int ii=0;
+  TR_CONSTRAINT *cons = talloc_get_type_abort(obj, TR_CONSTRAINT);
+  int ii = 0;
 
-  if (cons->type!=NULL)
+  if (cons->type != NULL)
     tr_free_name(cons->type);
-  for (ii=0; ii<TR_MAX_CONST_MATCHES; ii++) {
-    if (cons->matches[ii]!=NULL)
+  for (ii = 0; ii < TR_MAX_CONST_MATCHES; ii++) {
+    if (cons->matches[ii] != NULL)
       tr_free_name(cons->matches[ii]);
   }
   return 0;
@@ -59,14 +60,14 @@ static int tr_constraint_destructor(void *obj)
 
 TR_CONSTRAINT *tr_constraint_new(TALLOC_CTX *mem_ctx)
 {
-  TR_CONSTRAINT *cons=talloc(mem_ctx, TR_CONSTRAINT);
-  int ii=0;
-
-  if (cons!=NULL) {
-    cons->type=NULL;
-    for (ii=0; ii<TR_MAX_CONST_MATCHES; ii++)
-      cons->matches[ii]=NULL;
-    talloc_set_destructor((void *)cons, tr_constraint_destructor);
+  TR_CONSTRAINT *cons = talloc(mem_ctx, TR_CONSTRAINT);
+  int ii = 0;
+
+  if (cons != NULL) {
+    cons->type = NULL;
+    for (ii = 0; ii < TR_MAX_CONST_MATCHES; ii++)
+      cons->matches[ii] = NULL;
+    talloc_set_destructor((void *) cons, tr_constraint_destructor);
   }
   return cons;
 }
@@ -78,20 +79,20 @@ void tr_constraint_free(TR_CONSTRAINT *cons)
 
 TR_CONSTRAINT *tr_constraint_dup(TALLOC_CTX *mem_ctx, TR_CONSTRAINT *cons)
 {
-  TALLOC_CTX *tmp_ctx=NULL;
-  TR_CONSTRAINT *new=NULL;
-  int ii=0;
+  TALLOC_CTX *tmp_ctx = NULL;
+  TR_CONSTRAINT *new = NULL;
+  int ii = 0;
 
-  if (cons==NULL)
+  if (cons == NULL)
     return NULL;
 
-  tmp_ctx=talloc_new(NULL);
-  new=tr_constraint_new(tmp_ctx);
+  tmp_ctx = talloc_new(NULL);
+  new = tr_constraint_new(tmp_ctx);
 
-  if (new!=NULL) {
-    new->type=tr_dup_name(cons->type);
-    for (ii=0; ii<TR_MAX_CONST_MATCHES; ii++)
-      new->matches[ii]=tr_dup_name(cons->matches[ii]);
+  if (new != NULL) {
+    new->type = tr_dup_name(cons->type);
+    for (ii = 0; ii < TR_MAX_CONST_MATCHES; ii++)
+      new->matches[ii] = tr_dup_name(cons->matches[ii]);
     talloc_steal(mem_ctx, new);
   }
 
@@ -99,9 +100,12 @@ TR_CONSTRAINT *tr_constraint_dup(TALLOC_CTX *mem_ctx, TR_CONSTRAINT *cons)
   return new;
 }
 
-/* Returns TRUE (1) if the the string (str) matchs the wildcard string (wc_str), FALSE (0) if not.
+/* Returns TRUE (1) if the the string (str) matches the wildcard string (wc_str), FALSE (0) if not.
+ * Allows for a single '*' as the wildcard character if it is the first character. Leading white
+ * space is significant.
  */
-int tr_prefix_wildcard_match (const char *str, const char *wc_str) {
+int tr_prefix_wildcard_match(const char *str, const char *wc_str)
+{
   const char *wc_post = wc_str;
   size_t len = 0;
   size_t wc_len = 0;
@@ -117,21 +121,22 @@ int tr_prefix_wildcard_match (const char *str, const char *wc_str) {
   if ('*' == wc_str[0]) {
     wc_post = &(wc_str[1]);
     wc_len--;
-  }else if (len != wc_len)
+  } else if (len != wc_len)
     return 0;
 
 
   if (wc_len > len)
     return 0;
-  
-  if (0 == strcmp(&(str[len-wc_len]), wc_post)) {
+
+  if (0 == strcmp(&(str[len - wc_len]), wc_post)) {
     return 1;
-  }
-  else
+  } else
     return 0;
-  }
+}
 
-TR_CONSTRAINT_SET *tr_constraint_set_from_fline (TR_FLINE *fline)
+/* This combines the two constraints in a filter line (TR_FLINE) into a single
+ * set with two constraints. */
+TR_CONSTRAINT_SET *tr_constraint_set_from_fline(TR_FLINE *fline)
 {
   json_t *cset = NULL;
 
@@ -139,10 +144,10 @@ TR_CONSTRAINT_SET *tr_constraint_set_from_fline (TR_FLINE *fline)
     return NULL;
 
   if (fline->realm_cons)
-    tr_constraint_add_to_set((TR_CONSTRAINT_SET **)&cset, fline->realm_cons);
+    tr_constraint_add_to_set((TR_CONSTRAINT_SET **) &cset, fline->realm_cons);
   if (fline->domain_cons)
-    tr_constraint_add_to_set((TR_CONSTRAINT_SET **)&cset, fline->domain_cons);
-  
+    tr_constraint_add_to_set((TR_CONSTRAINT_SET **) &cset, fline->domain_cons);
+
   return (TR_CONSTRAINT_SET *) cset;
 }
 
@@ -152,9 +157,11 @@ TR_CONSTRAINT_SET *tr_constraint_set_from_fline (TR_FLINE *fline)
  *
  *     {cset: [{domain: [a.com, b.co.uk]},
  *             {realm: [c.net, d.org]}]}
+ *
+ * This routine takes a TR_CONSTRAINT, converts it to its JSON representation,
+ * and adds that to the TR_CONSTRAINT_SET.
  */
-
-void tr_constraint_add_to_set (TR_CONSTRAINT_SET **cset, TR_CONSTRAINT *cons)
+void tr_constraint_add_to_set(TR_CONSTRAINT_SET **cset, TR_CONSTRAINT *cons)
 {
   json_t *jcons = NULL;
   json_t *jmatches = NULL;
@@ -176,17 +183,19 @@ void tr_constraint_add_to_set (TR_CONSTRAINT_SET **cset, TR_CONSTRAINT *cons)
   }
 
   json_object_set_new(jcons, cons->type->buf, jmatches);
-  
+
   /* Add the created object to the cset object */
   json_array_append_new((json_t *) *cset, jcons);
-} 
+}
 
- int tr_constraint_set_validate(TR_CONSTRAINT_SET *cset)
-{
+/* Test whether a JSON object has a valid structure
+ * to represent a constraint set.
+ */
+int tr_constraint_set_validate(TR_CONSTRAINT_SET *cset) {
   json_t *json = (json_t *) cset;
   size_t i;
   json_t *set_member;
-  if (!json_is_array(json)){
+  if (!json_is_array(json)) {
     tr_debug("Constraint_set is not an array");
     return 0;
   }
@@ -197,44 +206,50 @@ void tr_constraint_add_to_set (TR_CONSTRAINT_SET **cset, TR_CONSTRAINT *cons)
       tr_debug("Constraint member at %zu is not an object\n", i);
       return 0;
     }
-    json_object_foreach( set_member, key, value) {
+    json_object_foreach(set_member, key, value) {
       size_t inner_index;
       json_t *inner_value;
       if (!json_is_array(value)) {
-       tr_debug("Constraint type %s at index %zu in constraint set is not an array\n", key,
-                i);
-       return 0;
+        tr_debug("Constraint type %s at index %zu in constraint set is not an array\n", key,
+                 i);
+        return 0;
       }
       json_array_foreach(value, inner_index, inner_value) {
-       if (!json_is_string(inner_value)) {
-         tr_debug("Constraint type %s at index %zu in constraint set has non-string element %zu\n",
-                  key, i, inner_index);
-         return 0;
-       }
+        if (!json_is_string(inner_value)) {
+          tr_debug("Constraint type %s at index %zu in constraint set has non-string element %zu\n",
+                   key, i, inner_index);
+          return 0;
+        }
       }
-       }
+    }
   }
   return 1;
 }
 
 
-TR_CONSTRAINT_SET *tr_constraint_set_filter( TID_REQ *request,
-                                            TR_CONSTRAINT_SET *orig,
-                                            const char *constraint_type)
+/**
+ * Create a new constraint set containing all constraints from #orig
+ * with constraint_type #constraint_type and no others.  This constraint set is
+ * live until #request is freed.
+ */
+TR_CONSTRAINT_SET *tr_constraint_set_filter(TID_REQ *request,
+                                            TR_CONSTRAINT_SET *orig,
+                                            const char *constraint_type)
 {
-  json_t *orig_cset = (json_t*) orig;
-  json_t  *new_cs = NULL;
+  json_t *orig_cset = (json_t *) orig;
+  json_t *new_cs = NULL;
   size_t index;
   json_t *set_member;
-  if (!tr_constraint_set_validate( (TR_CONSTRAINT_SET *) orig_cset)) {
+  if (!tr_constraint_set_validate((TR_CONSTRAINT_SET *) orig_cset)) {
     tr_debug ("tr_constraint_set_filter: not a valid constraint set\n");
     return NULL;
   }
   assert (new_cs = json_array());
   json_array_foreach(orig_cset, index, set_member) {
-    if (json_object_get( set_member, constraint_type))
+    if (json_object_get(set_member, constraint_type))
       json_array_append(new_cs, set_member);
   }
+  tid_req_cleanup_json(request, new_cs);
   return (TR_CONSTRAINT_SET *) new_cs;
 }
 
@@ -255,40 +270,39 @@ static void merge_constraints(json_t *constraint, const char *key)
    */
   constraint_array = json_object_get(constraint, key);
   if (NULL == constraint_array)
-      return;
-  json_array_foreach( constraint_array, index_1, value_1)
-    json_array_foreach( constraint_array, index_2, value_2) {
-    if (index_2 <= index_1)
-      continue;
-    if ( tr_prefix_wildcard_match( json_string_value(value_2),
-                                  json_string_value(value_1))) {
-      json_array_remove(constraint_array, index_2);
-      index_2--;
-    }else if (tr_prefix_wildcard_match( json_string_value(value_1),
-                                       json_string_value(value_2))) {
-      json_array_set(constraint_array, index_1, value_2);
-      json_array_remove(constraint_array, index_2);
-      index_2--;
+    return;
+  json_array_foreach(constraint_array, index_1, value_1)json_array_foreach(constraint_array, index_2, value_2) {
+      if (index_2 <= index_1)
+        continue;
+      if (tr_prefix_wildcard_match(json_string_value(value_2),
+                                   json_string_value(value_1))) {
+        json_array_remove(constraint_array, index_2);
+        index_2--;
+      } else if (tr_prefix_wildcard_match(json_string_value(value_1),
+                                          json_string_value(value_2))) {
+        json_array_set(constraint_array, index_1, value_2);
+        json_array_remove(constraint_array, index_2);
+        index_2--;
+      }
     }
-  }
 }
 
 /**
  * Returns an array of constraint strings that is the intersection of
  * all constraints in the constraint_set of type #type
  */
-static json_t *constraint_intersect_internal( TR_CONSTRAINT_SET *constraints,
-                                             const char *constraint_type)
+static json_t *constraint_intersect_internal(TR_CONSTRAINT_SET *constraints,
+                                             const char *constraint_type)
 {
   json_t *constraint, *result = NULL;
   size_t i;
-  json_array_foreach( (json_t *) constraints, i, constraint) {
-    merge_constraints( constraint, constraint_type);
+  json_array_foreach((json_t *) constraints, i, constraint) {
+    merge_constraints(constraint, constraint_type);
     if (NULL == result) {
       result = json_object_get(constraint, constraint_type);
       if (NULL != result)
-       result = json_copy(result);
-    }    else {
+        result = json_copy(result);
+    } else {
       json_t *intersect, *value_1, *value_2;
       size_t index_1, index_2;
       intersect = json_object_get(constraint, constraint_type);
@@ -298,24 +312,25 @@ static json_t *constraint_intersect_internal( TR_CONSTRAINT_SET *constraints,
        *     constraint type we return empty (no access) rather than universal
        * access.*/
       if (!intersect)
-       continue;
-    result_loop:
+        continue;
+      result_loop:
       json_array_foreach(result, index_1, value_1) {
-       json_array_foreach(intersect, index_2, value_2) {
-         if (tr_prefix_wildcard_match( json_string_value(value_1),
-                                       json_string_value(value_2)))
-           goto result_acceptable;
-         else if (tr_prefix_wildcard_match(json_string_value( value_2),
-                                           json_string_value(value_1))) {
-           json_array_set(result, index_1, value_2);
-           goto result_acceptable;
-       }
-       }
-       json_array_remove(result, index_1);
-       if (index_1 == 0)
-         goto result_loop;
-       index_1--;
-      result_acceptable: continue;
+        json_array_foreach(intersect, index_2, value_2) {
+          if (tr_prefix_wildcard_match(json_string_value(value_1),
+                                       json_string_value(value_2)))
+            goto result_acceptable;
+          else if (tr_prefix_wildcard_match(json_string_value(value_2),
+                                            json_string_value(value_1))) {
+            json_array_set(result, index_1, value_2);
+            goto result_acceptable;
+          }
+        }
+        json_array_remove(result, index_1);
+        if (index_1 == 0)
+          goto result_loop;
+        index_1--;
+        result_acceptable:
+        continue;
       }
     }
   }
@@ -326,10 +341,10 @@ static json_t *constraint_intersect_internal( TR_CONSTRAINT_SET *constraints,
  * Return the intersection of domain and realm constraints.
  * Return is live until #request is freed.
  */
-TR_CONSTRAINT_SET *tr_constraint_set_intersect( TID_REQ *request,
-                                               TR_CONSTRAINT_SET *input)
+TR_CONSTRAINT_SET *tr_constraint_set_intersect(TID_REQ *request,
+                                               TR_CONSTRAINT_SET *input)
 {
-  json_t *domain=NULL, *realm=NULL;
+  json_t *domain = NULL, *realm = NULL;
   json_t *result = NULL, *result_array = NULL;
   if (tr_constraint_set_validate(input)) {
     domain = constraint_intersect_internal(input, "domain");
@@ -342,17 +357,21 @@ TR_CONSTRAINT_SET *tr_constraint_set_intersect( TID_REQ *request,
     json_object_set_new(result, "realm", realm);
   assert(result_array = json_array());
   json_array_append_new(result_array, result);
-  tid_req_cleanup_json( request, result_array);
+  tid_req_cleanup_json(request, result_array);
   return (TR_CONSTRAINT_SET *) result_array;
 }
 
-
-int tr_constraint_set_get_match_strings(
-                                       TID_REQ *request,
-                                       TR_CONSTRAINT_SET *constraints,
-                                       const char *constraint_type,
-                                       tr_const_string **output,
-                                       size_t *output_len)
+/** Get the set of wildcard strings that matches a fully intersected
+ * constraint set.  Requires that the constraint set only have one
+ * constraint in it, but the constraint may have multiple matches for
+ * a given type.  Returns true on success false on failure.  The
+ * output is live as long as the request is live.
+ */
+int tr_constraint_set_get_match_strings(TID_REQ *request,
+                                        TR_CONSTRAINT_SET *constraints,
+                                        const char *constraint_type,
+                                        tr_const_string **output,
+                                        size_t *output_len)
 {
   json_t *cset = (json_t *) constraints;
   json_t *member, *matches, *value;;
@@ -372,8 +391,7 @@ int tr_constraint_set_get_match_strings(
   if (array_size == 0)
     return -1;
   *output = talloc_array_ptrtype(request, *output, array_size);
-  json_array_foreach( matches, index, value)
-    (*output)[index] = json_string_value(value);
+  json_array_foreach(matches, index, value)(*output)[index] = json_string_value(value);
   *output_len = array_size;
   return 0;
 }
index e1ab4f2..52dffb4 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <talloc.h>
+#include <assert.h>
 
 #include <tr_filter.h>
+#include <trp_internal.h>
+#include <tid_internal.h>
+#include <tr_debug.h>
 
+/* Function types for handling filter fields generally. All target values
+ * are represented as strings in a TR_NAME.
+ */
+
+/* CMP functions return values like strcmp: 0 on match, <0 on target<val, >0 on target>val */
+typedef int (*TR_FILTER_FIELD_CMP)(TR_FILTER_TARGET *target, TR_NAME *val);
+/* get functions return TR_NAME format of the field value. Caller must free it. */
+typedef TR_NAME *(*TR_FILTER_FIELD_GET)(TR_FILTER_TARGET *target);
+
+static TR_FILTER_TARGET *tr_filter_target_new(TALLOC_CTX *mem_ctx)
+{
+  TR_FILTER_TARGET *target=talloc(mem_ctx, TR_FILTER_TARGET);
+  if (target) {
+    target->trp_inforec=NULL;
+    target->trp_upd=NULL;
+    target->tid_req=NULL;
+  }
+  return target;
+}
+void tr_filter_target_free(TR_FILTER_TARGET *target)
+{
+  talloc_free(target);
+}
 
-int tr_filter_process_rp_permitted (TR_NAME *rp_realm, TR_FILTER *rpp_filter, TR_CONSTRAINT_SET *in_constraints, TR_CONSTRAINT_SET **out_constraints, int *out_action) 
+/**
+ * Create a filter target for a TID request. Does not change the context of the request,
+ * so this is only valid until that is freed.
+ *
+ * @param mem_ctx talloc context for the object
+ * @param req TID request object
+ * @return pointer to a TR_FILTER_TARGET structure, or null on allocation failure
+ */
+TR_FILTER_TARGET *tr_filter_target_tid_req(TALLOC_CTX *mem_ctx, TID_REQ *req)
+{
+  TR_FILTER_TARGET *target=tr_filter_target_new(mem_ctx);
+  if (target)
+    target->tid_req=req; /* borrowed, not adding to our context */
+  return target;
+}
+
+/**
+ * Create a filter target for a TRP inforec. Does not change the context of the inforec or duplicate TR_NAMEs,
+ * so this is only valid until those are freed.
+ *
+ * @param mem_ctx talloc context for the object
+ * @param upd Update containing the TRP inforec
+ * @param inforec TRP inforec
+ * @return pointer to a TR_FILTER_TARGET structure, or null on allocation failure
+ */
+TR_FILTER_TARGET *tr_filter_target_trp_inforec(TALLOC_CTX *mem_ctx, TRP_UPD *upd, TRP_INFOREC *inforec)
 {
-  int i = 0, j = 0;
+  TR_FILTER_TARGET *target=tr_filter_target_new(mem_ctx);
+  if (target) {
+    target->trp_inforec = inforec; /* borrowed, not adding to our context */
+    target->trp_upd=upd;
+  }
+  return target;
+}
+
+/** Handler functions for TID RP_REALM field */
+static int tr_ff_cmp_tid_rp_realm(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(tid_req_get_rp_realm(target->tid_req), val);
+}
+
+static TR_NAME *tr_ff_get_tid_rp_realm(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(tid_req_get_rp_realm(target->tid_req));
+}
+
+/** Handler functions for TRP info_type field */
+static int tr_ff_cmp_trp_info_type(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  TRP_INFOREC *inforec=target->trp_inforec;
+  char *valstr=NULL;
+  int val_type=0;
+
+  assert(val);
+  assert(inforec);
+
+  /* nothing matches unknown */
+  if (inforec->type==TRP_INFOREC_TYPE_UNKNOWN)
+    return 0;
+
+  valstr = tr_name_strdup(val); /* get this as an official null-terminated string */
+  val_type = trp_inforec_type_from_string(valstr);
+  free(valstr);
+
+  /* we do not define an ordering of info types */
+  return (val_type==inforec->type);
+}
+
+static TR_NAME *tr_ff_get_trp_info_type(TR_FILTER_TARGET *target)
+{
+  TRP_INFOREC *inforec=target->trp_inforec;
+  return tr_new_name(trp_inforec_type_to_string(inforec->type));
+}
+
+/** Handlers for TRP realm field */
+static int tr_ff_cmp_trp_realm(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(trp_upd_get_realm(target->trp_upd), val);
+}
+
+static TR_NAME *tr_ff_get_trp_realm(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(trp_upd_get_realm(target->trp_upd));
+}
+
+/** Handlers for TID realm field */
+static int tr_ff_cmp_tid_realm(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(tid_req_get_realm(target->tid_req), val);
+}
+
+static TR_NAME *tr_ff_get_tid_realm(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(tid_req_get_realm(target->tid_req));
+}
+
+/** Handlers for TRP community field */
+static int tr_ff_cmp_trp_comm(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(trp_upd_get_comm(target->trp_upd), val);
+}
+
+static TR_NAME *tr_ff_get_trp_comm(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(trp_upd_get_comm(target->trp_upd));
+}
+
+/** Handlers for TID community field */
+static int tr_ff_cmp_tid_comm(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(tid_req_get_comm(target->tid_req), val);
+}
+
+static TR_NAME *tr_ff_get_tid_comm(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(tid_req_get_comm(target->tid_req));
+}
+
+/** Handlers for TRP community_type field */
+static TR_NAME *tr_ff_get_trp_comm_type(TR_FILTER_TARGET *target)
+{
+  TR_NAME *type=NULL;
+
+  switch(trp_inforec_get_comm_type(target->trp_inforec)) {
+    case TR_COMM_APC:
+      type=tr_new_name("apc");
+      break;
+    case TR_COMM_COI:
+      type=tr_new_name("coi");
+      break;
+    default:
+      type=NULL;
+      break; /* unknown types always fail */
+  }
+
+  return type;
+}
+
+static int tr_ff_cmp_trp_comm_type(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  TR_NAME *type=tr_ff_get_trp_comm_type(target);
+  int retval=0;
+
+  if (type==NULL)
+    retval=1;
+  else {
+    retval = tr_name_cmp(val, type);
+    tr_free_name(type);
+  }
+  return retval;
+}
+
+/** Handlers for TRP realm_role field */
+static TR_NAME *tr_ff_get_trp_realm_role(TR_FILTER_TARGET *target)
+{
+  TR_NAME *type=NULL;
+
+  switch(trp_inforec_get_role(target->trp_inforec)) {
+    case TR_ROLE_IDP:
+      type=tr_new_name("idp");
+      break;
+    case TR_ROLE_RP:
+      type=tr_new_name("rp");
+      break;
+    default:
+      type=NULL;
+      break; /* unknown types always fail */
+  }
+
+  return type;
+}
+
+static int tr_ff_cmp_trp_realm_role(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  TR_NAME *type=tr_ff_get_trp_realm_role(target);
+  int retval=0;
+
+  if (type==NULL)
+    retval=1;
+  else {
+    retval = tr_name_cmp(val, type);
+    tr_free_name(type);
+  }
+  return retval;
+}
+
+/** Handlers for TRP apc field */
+/* TODO: Handle multiple APCs, not just the first */
+static int tr_ff_cmp_trp_apc(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(tr_apc_get_id(trp_inforec_get_apcs(target->trp_inforec)), val);
+}
+
+static TR_NAME *tr_ff_get_trp_apc(TR_FILTER_TARGET *target)
+{
+  TR_APC *apc=trp_inforec_get_apcs(target->trp_inforec);
+  if (apc==NULL)
+    return NULL;
+
+  return tr_dup_name(tr_apc_get_id(apc));
+}
+
+/** Handlers for TRP owner_realm field */
+static int tr_ff_cmp_trp_owner_realm(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(trp_inforec_get_owner_realm(target->trp_inforec), val);
+}
+
+static TR_NAME *tr_ff_get_trp_owner_realm(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(trp_inforec_get_owner_realm(target->trp_inforec));
+}
+
+/** Handlers for TRP trust_router field */
+static int tr_ff_cmp_trp_trust_router(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(trp_inforec_get_trust_router(target->trp_inforec), val);
+}
+
+static TR_NAME *tr_ff_get_trp_trust_router(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(trp_inforec_get_trust_router(target->trp_inforec));
+}
+
+/** Handlers for TRP owner_contact field */
+static int tr_ff_cmp_trp_owner_contact(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(trp_inforec_get_owner_contact(target->trp_inforec), val);
+}
+
+static TR_NAME *tr_ff_get_trp_owner_contact(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(trp_inforec_get_owner_contact(target->trp_inforec));
+}
+
+/** Handlers for TID req original_coi field */
+static int tr_ff_cmp_tid_orig_coi(TR_FILTER_TARGET *target, TR_NAME *val)
+{
+  return tr_name_cmp(tid_req_get_orig_coi(target->tid_req), val);
+}
+
+static TR_NAME *tr_ff_get_tid_orig_coi(TR_FILTER_TARGET *target)
+{
+  return tr_dup_name(tid_req_get_orig_coi(target->tid_req));
+}
+
+/**
+ * Filter field handler table
+ */
+struct tr_filter_field_entry {
+  TR_FILTER_TYPE filter_type;
+  const char *name;
+  TR_FILTER_FIELD_CMP cmp;
+  TR_FILTER_FIELD_GET get;
+};
+static struct tr_filter_field_entry tr_filter_field_table[] = {
+    /* realm */
+    {TR_FILTER_TYPE_TID_INBOUND, "realm", tr_ff_cmp_tid_realm, tr_ff_get_tid_realm},
+    {TR_FILTER_TYPE_TRP_INBOUND, "realm", tr_ff_cmp_trp_realm, tr_ff_get_trp_realm},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "realm", tr_ff_cmp_trp_realm, tr_ff_get_trp_realm},
+
+    /* community */
+    {TR_FILTER_TYPE_TID_INBOUND, "comm", tr_ff_cmp_tid_comm, tr_ff_get_tid_comm},
+    {TR_FILTER_TYPE_TRP_INBOUND, "comm", tr_ff_cmp_trp_comm, tr_ff_get_trp_comm},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "comm", tr_ff_cmp_trp_comm, tr_ff_get_trp_comm},
 
+    /* community type */
+    {TR_FILTER_TYPE_TRP_INBOUND, "comm_type", tr_ff_cmp_trp_comm_type, tr_ff_get_trp_comm_type},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "comm_type", tr_ff_cmp_trp_comm_type, tr_ff_get_trp_comm_type},
+
+    /* realm role */
+    {TR_FILTER_TYPE_TRP_INBOUND, "realm_role", tr_ff_cmp_trp_realm_role, tr_ff_get_trp_realm_role},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "realm_role", tr_ff_cmp_trp_realm_role, tr_ff_get_trp_realm_role},
+
+    /* apc */
+    {TR_FILTER_TYPE_TRP_INBOUND, "apc", tr_ff_cmp_trp_apc, tr_ff_get_trp_apc},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "apc", tr_ff_cmp_trp_apc, tr_ff_get_trp_apc},
+
+    /* trust_router */
+    {TR_FILTER_TYPE_TRP_INBOUND, "trust_router", tr_ff_cmp_trp_trust_router, tr_ff_get_trp_trust_router},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "trust_router", tr_ff_cmp_trp_trust_router, tr_ff_get_trp_trust_router},
+
+    /* owner_realm */
+    {TR_FILTER_TYPE_TRP_INBOUND, "owner_realm", tr_ff_cmp_trp_owner_realm, tr_ff_get_trp_owner_realm},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "owner_realm", tr_ff_cmp_trp_owner_realm, tr_ff_get_trp_owner_realm},
+
+    /* owner_contact */
+    {TR_FILTER_TYPE_TRP_INBOUND, "owner_contact", tr_ff_cmp_trp_owner_contact, tr_ff_get_trp_owner_contact},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "owner_contact", tr_ff_cmp_trp_owner_contact, tr_ff_get_trp_owner_contact},
+
+    /* rp_realm */
+    {TR_FILTER_TYPE_TID_INBOUND, "rp_realm", tr_ff_cmp_tid_rp_realm, tr_ff_get_tid_rp_realm},
+
+    /* original coi */
+    {TR_FILTER_TYPE_TID_INBOUND, "original_coi", tr_ff_cmp_tid_orig_coi, tr_ff_get_tid_orig_coi},
+
+    /* info_type */
+    {TR_FILTER_TYPE_TRP_INBOUND, "info_type", tr_ff_cmp_trp_info_type, tr_ff_get_trp_info_type},
+    {TR_FILTER_TYPE_TRP_OUTBOUND, "info_type", tr_ff_cmp_trp_info_type, tr_ff_get_trp_info_type},
+
+    /* Unknown */
+    {TR_FILTER_TYPE_UNKNOWN, NULL } /* This must be the final entry */
+};
+
+/* TODO: support TRP metric field (requires > < comparison instead of wildcard match) */
+
+static struct tr_filter_field_entry *tr_filter_field_entry(TR_FILTER_TYPE filter_type, TR_NAME *field_name)
+{
+  unsigned int ii;
+
+  for (ii=0; tr_filter_field_table[ii].filter_type!=TR_FILTER_TYPE_UNKNOWN; ii++) {
+    if ((tr_filter_field_table[ii].filter_type==filter_type)
+        && (tr_name_cmp_str(field_name, tr_filter_field_table[ii].name)==0)) {
+      return tr_filter_field_table+ii;
+    }
+  }
+  return NULL;
+}
+
+/**
+ * Apply a filter to a target record or TID request.
+ *
+ * If one of the filter lines matches, out_action is set to the applicable action. If constraints
+ * is not NULL, the constraints from the matching filter line will be added to the constraint set
+ * *constraints, or to a new one if *constraints is NULL. In this case, TR_FILTER_MATCH will be
+ * returned.
+ *
+ * If there is no match, returns TR_FILTER_NO_MATCH, out_action is undefined, and constraints
+ * will not be changed.
+ *
+ * @param target Record or request to which the filter is applied
+ * @param filt Filter to apply
+ * @param constraints Pointer to existing set of constraints (NULL if not tracking constraints)
+ * @param out_action Action to be carried out (output)
+ * @return TR_FILTER_MATCH or TR_FILTER_NO_MATCH
+ */
+int tr_filter_apply(TR_FILTER_TARGET *target,
+                    TR_FILTER *filt,
+                    TR_CONSTRAINT_SET **constraints,
+                    TR_FILTER_ACTION *out_action)
+{
+  unsigned int ii=0, jj=0;
+  int retval=TR_FILTER_NO_MATCH;
+
+  /* Default action is reject */
   *out_action = TR_FILTER_ACTION_REJECT;
-  *out_constraints = NULL;
 
-  /* If this isn't a valid rp_permitted filter, return no match. */
-  if ((!rpp_filter) ||
-      (TR_FILTER_TYPE_RP_PERMITTED != rpp_filter->type)) {
+  /* Validate filter */
+  if ((filt==NULL) || (filt->type==TR_FILTER_TYPE_UNKNOWN))
     return TR_FILTER_NO_MATCH;
-  }
-  
-  /* Check if there is a match for this filter. */
-  for (i = 0; i < TR_MAX_FILTER_LINES; i++) {
-    for (j = 0; j < TR_MAX_FILTER_SPECS; j++) {
-
-      if ((rpp_filter->lines[i]) && 
-         (rpp_filter->lines[i]->specs[j]) && 
-         (tr_fspec_matches(rpp_filter->lines[i]->specs[j], rp_realm))) {
-       *out_action = rpp_filter->lines[i]->action;
-       *out_constraints = in_constraints;
-       if (rpp_filter->lines[i]->realm_cons)
-         tr_constraint_add_to_set(out_constraints, 
-                                  rpp_filter->lines[i]->realm_cons);
-       if (rpp_filter->lines[i]->domain_cons)
-         tr_constraint_add_to_set(out_constraints, 
-                                  rpp_filter->lines[i]->domain_cons);
-
-       return TR_FILTER_MATCH;
+
+  /* Step through filter lines looking for a match. If a line matches, retval
+   * will be set to TR_FILTER_MATCH, so stop then. */
+  for (ii=0, retval=TR_FILTER_NO_MATCH;
+       ii<TR_MAX_FILTER_LINES;
+       ii++) {
+    /* skip empty lines (these shouldn't really happen) */
+    if (filt->lines[ii]==NULL)
+      continue;
+
+    /* Assume we are going to succeed. If any specs fail to match, we'll set
+     * this to TR_FILTER_NO_MATCH. */
+    retval=TR_FILTER_MATCH;
+    for (jj=0; jj<TR_MAX_FILTER_SPECS; jj++) {
+      /* skip empty specs (these shouldn't really happen either) */
+      if (filt->lines[ii]->specs[jj]==NULL)
+        continue;
+
+      if (!tr_fspec_matches(filt->lines[ii]->specs[jj], filt->type, target)) {
+        retval=TR_FILTER_NO_MATCH; /* set this in case this is the last filter line */
+        break; /* give up on this filter line */
       }
     }
+
+    if (retval==TR_FILTER_MATCH)
+      break;
+  }
+
+  if (retval==TR_FILTER_MATCH) {
+    /* Matched line ii. Grab its action and constraints. */
+    *out_action = filt->lines[ii]->action;
+    if (constraints!=NULL) {
+      /* if either constraint is missing, these are no-ops */
+      tr_constraint_add_to_set(constraints, filt->lines[ii]->realm_cons);
+      tr_constraint_add_to_set(constraints, filt->lines[ii]->domain_cons);
+    }
   }
-  /* If there is no match, indicate that. */
-  return TR_FILTER_NO_MATCH;
+
+  return retval;
 }
 
 void tr_fspec_free(TR_FSPEC *fspec)
@@ -84,39 +465,92 @@ void tr_fspec_free(TR_FSPEC *fspec)
 
 static int tr_fspec_destructor(void *obj)
 {
-  TR_FSPEC *fspec=talloc_get_type_abort(obj, TR_FSPEC);
+  TR_FSPEC *fspec = talloc_get_type_abort(obj, TR_FSPEC);
+  size_t ii;
 
-  if (fspec->field!=NULL)
+  if (fspec->field != NULL)
     tr_free_name(fspec->field);
-  if (fspec->match!=NULL)
-    tr_free_name(fspec->match);
+  for (ii=0; ii<TR_MAX_FILTER_SPEC_MATCHES; ii++) {
+    if (fspec->match[ii] != NULL)
+      tr_free_name(fspec->match[ii]);
+  }
   return 0;
 }
 
 TR_FSPEC *tr_fspec_new(TALLOC_CTX *mem_ctx)
 {
-  TR_FSPEC *fspec=talloc(mem_ctx, TR_FSPEC);
+  TR_FSPEC *fspec = talloc(mem_ctx, TR_FSPEC);
+  size_t ii=0;
+
+  if (fspec != NULL) {
+    fspec->field = NULL;
+    for (ii=0; ii<TR_MAX_FILTER_SPEC_MATCHES; ii++)
+      fspec->match[ii] = NULL;
 
-  if (fspec!=NULL) {
-    fspec->field=NULL;
-    fspec->match=NULL;
     talloc_set_destructor((void *)fspec, tr_fspec_destructor);
   }
   return fspec;
 }
 
-void tr_fspec_set_match(TR_FSPEC *fspec, TR_NAME *match)
+void tr_fspec_add_match(TR_FSPEC *fspec, TR_NAME *match)
 {
-  if (fspec->match!=NULL)
-    tr_free_name(fspec->match);
-  fspec->match=match;
+  size_t ii;
+  for (ii=0; ii<TR_MAX_FILTER_SPEC_MATCHES; ii++) {
+    if (fspec->match[ii]==NULL) {
+      fspec->match[ii]=match;
+      break;
+    }
+  }
+  /* TODO: handle case that adding the match failed */
 }
 
 /* returns 1 if the spec matches */
-int tr_fspec_matches(TR_FSPEC *fspec, TR_NAME *name)
+int tr_fspec_matches(TR_FSPEC *fspec, TR_FILTER_TYPE ftype, TR_FILTER_TARGET *target)
 {
-  return ((fspec->match!=NULL) &&
-          (0!=tr_prefix_wildcard_match(name->buf, fspec->match->buf)));
+  struct tr_filter_field_entry *field=NULL;
+  TR_NAME *name=NULL;
+  int retval=0;
+
+  size_t ii=0;
+
+  if (fspec==NULL)
+    return 0;
+
+  /* Look up how to handle the requested field */
+  field = tr_filter_field_entry(ftype, fspec->field);
+  if (field==NULL) {
+    tr_err("tr_fspec_matches: No entry to handle field %.*s for %*s filter.",
+           fspec->field->len, fspec->field->buf,
+           tr_filter_type_to_string(ftype));
+    return 0;
+  }
+
+  name=field->get(target);
+  if (name==NULL)
+    return 0; /* if there's no value, there's no match */
+
+  for (ii=0; ii<TR_MAX_FILTER_SPEC_MATCHES; ii++) {
+    if (fspec->match[ii]!=NULL) {
+      if (tr_name_prefix_wildcard_match(name, fspec->match[ii])) {
+        retval=1;
+        tr_debug("tr_fspec_matches: Field %.*s value \"%.*s\" matches \"%.*s\" for %s filter.",
+                 fspec->field->len, fspec->field->buf,
+                 name->len, name->buf,
+                 fspec->match[ii]->len, fspec->match[ii]->buf,
+                 tr_filter_type_to_string(ftype));
+        break;
+      }
+    }
+  }
+
+  if (!retval) {
+        tr_debug("tr_fspec_matches: Field %.*s value \"%.*s\" does not match for %s filter.",
+                 fspec->field->len, fspec->field->buf,
+                 name->len, name->buf,
+                 tr_filter_type_to_string(ftype));
+  }
+  tr_free_name(name);
+  return retval;
 }
 
 void tr_fline_free(TR_FLINE *fline)
@@ -126,28 +560,28 @@ void tr_fline_free(TR_FLINE *fline)
 
 TR_FLINE *tr_fline_new(TALLOC_CTX *mem_ctx)
 {
-  TR_FLINE *fl=talloc(mem_ctx, TR_FLINE);
-  int ii=0;
+  TR_FLINE *fl = talloc(mem_ctx, TR_FLINE);
+  int ii = 0;
 
-  if (fl!=NULL) {
-    fl->action=TR_FILTER_ACTION_UNKNOWN;
-    fl->realm_cons=NULL;
-    fl->domain_cons=NULL;
-    for (ii=0; ii<TR_MAX_FILTER_SPECS; ii++)
-      fl->specs[ii]=NULL;
+  if (fl != NULL) {
+    fl->action = TR_FILTER_ACTION_UNKNOWN;
+    fl->realm_cons = NULL;
+    fl->domain_cons = NULL;
+    for (ii = 0; ii < TR_MAX_FILTER_SPECS; ii++)
+      fl->specs[ii] = NULL;
   }
   return fl;
 }
 
 TR_FILTER *tr_filter_new(TALLOC_CTX *mem_ctx)
 {
-  TR_FILTER *f=talloc(mem_ctx, TR_FILTER);
-  int ii=0;
+  TR_FILTER *f = talloc(mem_ctx, TR_FILTER);
+  int ii = 0;
 
-  if (f!=NULL) {
-    f->type=TR_FILTER_TYPE_UNKNOWN;
-    for (ii=0; ii<TR_MAX_FILTER_LINES; ii++)
-      f->lines[ii]=NULL;
+  if (f != NULL) {
+    f->type = TR_FILTER_TYPE_UNKNOWN;
+    for (ii = 0; ii < TR_MAX_FILTER_LINES; ii++)
+      f->lines[ii] = NULL;
   }
   return f;
 }
@@ -159,10 +593,190 @@ void tr_filter_free(TR_FILTER *filt)
 
 void tr_filter_set_type(TR_FILTER *filt, TR_FILTER_TYPE type)
 {
-  filt->type=type;
+  filt->type = type;
 }
 
 TR_FILTER_TYPE tr_filter_get_type(TR_FILTER *filt)
 {
   return filt->type;
 }
+
+/**
+ * Check that a filter is valid, i.e., can be processed.
+ *
+ * @param filt Filter to verify
+ * @return 1 if the filter is valid, 0 otherwise
+ */
+int tr_filter_validate(TR_FILTER *filt)
+{
+  size_t ii=0, jj=0, kk=0;
+
+  if (!filt)
+    return 0;
+
+  /* check that we recognize the type */
+  switch(filt->type) {
+    case TR_FILTER_TYPE_TID_INBOUND:
+    case TR_FILTER_TYPE_TRP_INBOUND:
+    case TR_FILTER_TYPE_TRP_OUTBOUND:
+      break;
+
+    default:
+      return 0; /* if we get here, either TR_FILTER_TYPE_UNKNOWN or an invalid value was found */
+  }
+  for (ii=0; ii<TR_MAX_FILTER_LINES; ii++) {
+    if (filt->lines[ii]==NULL)
+      continue; /* an empty filter line is valid */
+
+    /* check that we recognize the action */
+    switch(filt->lines[ii]->action) {
+      case TR_FILTER_ACTION_ACCEPT:
+      case TR_FILTER_ACTION_REJECT:
+        break;
+
+      default:
+        /* if we get here, either TR_FILTER_ACTION_UNKNOWN or an invalid value was found */
+        return 0;
+    }
+
+    for (jj=0; jj<TR_MAX_FILTER_SPECS; jj++) {
+      if (filt->lines[ii]->specs[jj]==NULL)
+        continue; /* an empty filter spec is valid */
+
+      if (!tr_filter_validate_spec_field(filt->type, filt->lines[ii]->specs[jj]))
+        return 0;
+
+      /* check that at least one match is non-null */
+      for (kk=0; kk<TR_MAX_FILTER_SPEC_MATCHES; kk++) {
+        if (filt->lines[ii]->specs[jj]->match[kk]!=NULL)
+          break;
+      }
+      if (kk==TR_MAX_FILTER_SPEC_MATCHES)
+        return 0;
+    }
+  }
+
+  /* We ran the gauntlet. Success! */
+  return 1;
+}
+
+int tr_filter_validate_spec_field(TR_FILTER_TYPE ftype, TR_FSPEC *fspec)
+{
+  if ((fspec==NULL) || (tr_filter_field_entry(ftype, fspec->field)==NULL))
+    return 0; /* unknown field */
+
+  return 1;
+}
+
+/**
+ * Allocate a new filter set.
+ *
+ * @param mem_ctx Talloc context for the new set
+ * @return Pointer to new set, or null on error
+ */
+TR_FILTER_SET *tr_filter_set_new(TALLOC_CTX *mem_ctx)
+{
+  TR_FILTER_SET *set=talloc(mem_ctx, TR_FILTER_SET);
+  if (set!=NULL) {
+    set->next=NULL;
+    set->this=NULL;
+  }
+  return set;
+}
+
+/**
+ * Free a filter set
+ *
+ * @param fs Filter set to free
+ */
+void tr_filter_set_free(TR_FILTER_SET *fs)
+{
+  talloc_free(fs);
+}
+
+/**
+ * Find the tail of the filter set linked list.
+ *
+ * @param set Set to find tail of
+ * @return Last element in the list
+ */
+static TR_FILTER_SET *tr_filter_set_tail(TR_FILTER_SET *set)
+{
+  while (set->next)
+    set=set->next;
+  return set;
+}
+
+/**
+ * Add new filter to filter set.
+ *
+ * @param set Filter set
+ * @param new New filter to add
+ * @return 0 on success, nonzero on error
+ */
+int tr_filter_set_add(TR_FILTER_SET *set, TR_FILTER *new)
+{
+  TR_FILTER_SET *tail=NULL;
+
+  if (set->this==NULL)
+    tail=set;
+  else {
+    tail=tr_filter_set_tail(set);
+    tail->next=tr_filter_set_new(set);
+    if (tail->next==NULL)
+      return 1;
+    tail=tail->next;
+  }
+  tail->this=new;
+  talloc_steal(tail, new);
+  return 0;
+}
+
+/**
+ * Find a filter of a given type in the filter set. If there are multiple, returns the first one.
+ *
+ * @param set Filter set to search
+ * @param type Type of filter to find
+ * @return Borrowed pointer to the filter, or null if no filter of that type is found
+ */
+TR_FILTER *tr_filter_set_get(TR_FILTER_SET *set, TR_FILTER_TYPE type)
+{
+  TR_FILTER_SET *cur=set;
+  while(cur!=NULL) {
+    if ((cur->this != NULL) && (cur->this->type == type))
+      return cur->this;
+    cur=cur->next;
+  }
+  return NULL;
+}
+
+TR_FILTER_TYPE filter_type[]={TR_FILTER_TYPE_TID_INBOUND,
+                              TR_FILTER_TYPE_TRP_INBOUND,
+                              TR_FILTER_TYPE_TRP_OUTBOUND};
+const char *filter_label[]={"tid_inbound",
+                            "trp_inbound",
+                            "trp_outbound"};
+size_t num_filter_types=sizeof(filter_type)/sizeof(filter_type[0]);
+
+const char *tr_filter_type_to_string(TR_FILTER_TYPE ftype)
+{
+  size_t ii=0;
+
+  for (ii=0; ii<num_filter_types; ii++) {
+    if (ftype==filter_type[ii])
+      return filter_label[ii];
+  }
+  return "unknown";
+}
+
+TR_FILTER_TYPE tr_filter_type_from_string(const char *s)
+{
+  size_t ii=0;
+
+  for(ii=0; ii<num_filter_types; ii++) {
+    if (0==strcmp(s, filter_label[ii]))
+      return filter_type[ii];
+  }
+  return TR_FILTER_TYPE_UNKNOWN;
+}
+
index 9b205d3..043fa97 100644 (file)
@@ -218,17 +218,17 @@ static json_t * tr_msg_encode_tidreq(TID_REQ *req)
 
   assert(jreq = json_object());
 
-  jstr = json_string(req->rp_realm->buf);
+  jstr = tr_name_to_json_string(req->rp_realm);
   json_object_set_new(jreq, "rp_realm", jstr);
 
-  jstr = json_string(req->realm->buf);
+  jstr = tr_name_to_json_string(req->realm);
   json_object_set_new(jreq, "target_realm", jstr);
 
-  jstr = json_string(req->comm->buf);
+  jstr = tr_name_to_json_string(req->comm);
   json_object_set_new(jreq, "community", jstr);
   
   if (req->orig_coi) {
-    jstr = json_string(req->orig_coi->buf);
+    jstr = tr_name_to_json_string(req->orig_coi);
     json_object_set_new(jreq, "orig_coi", jstr);
   }
 
@@ -329,7 +329,7 @@ static json_t *tr_msg_encode_one_server(TID_SRVR_BLK *srvr)
                      "key_expiration", json_string(time_str));
   g_free(time_str);
   /* Server DH Block */
-  jstr = json_string(srvr->key_name->buf);
+  jstr = tr_name_to_json_string(srvr->key_name);
   json_object_set_new(jsrvr, "key_name", jstr);
   json_object_set_new(jsrvr, "server_dh", tr_msg_encode_dh(srvr->aaa_server_dh));
   if (srvr->path)
@@ -446,7 +446,7 @@ static json_t * tr_msg_encode_tidresp(TID_RESP *resp)
     jstr = json_string("error");
     json_object_set_new(jresp, "result", jstr);
     if (resp->err_msg) {
-      jstr = json_string(resp->err_msg->buf);
+      jstr = tr_name_to_json_string(resp->err_msg);
       json_object_set_new(jresp, "err_msg", jstr);
     }
   }
@@ -455,17 +455,17 @@ static json_t * tr_msg_encode_tidresp(TID_RESP *resp)
     json_object_set_new(jresp, "result", jstr);
   }
 
-  jstr = json_string(resp->rp_realm->buf);
+  jstr = tr_name_to_json_string(resp->rp_realm);
   json_object_set_new(jresp, "rp_realm", jstr);
 
-  jstr = json_string(resp->realm->buf);
+  jstr = tr_name_to_json_string(resp->realm);
   json_object_set_new(jresp, "target_realm", jstr);
 
-  jstr = json_string(resp->comm->buf);
+  jstr = tr_name_to_json_string(resp->comm);
   json_object_set_new(jresp, "comm", jstr);
 
   if (resp->orig_coi) {
-    jstr = json_string(resp->orig_coi->buf);
+    jstr = tr_name_to_json_string(resp->orig_coi);
     json_object_set_new(jresp, "orig_coi", jstr);
   }
 
@@ -1198,7 +1198,7 @@ char *tr_msg_encode(TR_MSG *msg)
   return encoded;
 }
 
-TR_MSG *tr_msg_decode(char *jbuf, size_t buflen)
+TR_MSG *tr_msg_decode(const char *jbuf, size_t buflen)
 {
   TR_MSG *msg=NULL;
   json_t *jmsg = NULL;
@@ -1265,20 +1265,22 @@ void tr_msg_free_encoded(char *jmsg)
 void tr_msg_free_decoded(TR_MSG *msg)
 {
   if (msg) {
-    switch (msg->msg_type) {
-    case TID_REQUEST:
-      tid_req_free(tr_msg_get_req(msg));
-      break;
-    case TID_RESPONSE:
-      tid_resp_free(tr_msg_get_resp(msg));
-      break;
-    case TRP_UPDATE:
-      trp_upd_free(tr_msg_get_trp_upd(msg));
-      break;
-    case TRP_REQUEST:
-      trp_req_free(tr_msg_get_trp_req(msg));
-    default:
-      break;
+    if (msg->msg_rep!=NULL) {
+      switch (msg->msg_type) {
+        case TID_REQUEST:
+          tid_req_free(tr_msg_get_req(msg));
+          break;
+        case TID_RESPONSE:
+          tid_resp_free(tr_msg_get_resp(msg));
+          break;
+        case TRP_UPDATE:
+          trp_upd_free(tr_msg_get_trp_upd(msg));
+          break;
+        case TRP_REQUEST:
+          trp_req_free(tr_msg_get_trp_req(msg));
+        default:
+          break;
+      }
     }
     free (msg);
   }
index eacef63..83d1db0 100644 (file)
@@ -48,7 +48,7 @@ void tr_free_name (TR_NAME *name)
   free(name);
 }
 
-TR_NAME *tr_new_name (const char *name) 
+TR_NAME *tr_new_name (const char *name)
 {
   TR_NAME *new;
 
@@ -102,6 +102,64 @@ int tr_name_cmp(TR_NAME *one, TR_NAME *two)
   return cmp;
 }
 
+/**
+ * Compare a TR_NAME with a null-terminated string.
+ *
+ * @param one TR_NAME to compare
+ * @param two_str Ordinary C null-terminated string
+ * @return 0 on match, <0 if one precedes two, >0 if two precedes one
+ */
+int tr_name_cmp_str(TR_NAME *one, const char *two_str)
+{
+  TR_NAME *two=tr_new_name(two_str);
+  int cmp=tr_name_cmp(one, two);
+  tr_free_name(two);
+  return cmp;
+}
+
+/**
+ * Compare strings, allowing one to have a single '*' as the wildcard character if it is the first character.
+ * Leading whitespace is significant.
+ *
+ * @param str Fixed string to compare
+ * @param wc_str Wildcard string to compare
+ * @return 1 if the the string (str) matches the wildcard string (wc_str), 0 if not.
+ *
+ */
+int tr_name_prefix_wildcard_match(TR_NAME *str, TR_NAME *wc_str)
+{
+  const char *wc_post=NULL;
+  size_t wc_len = 0;
+
+  if ((!str) || (!wc_str))
+    return 0;
+
+  if (0 == (wc_len = wc_str->len))
+    return 0;
+
+  if ('*' == wc_str->buf[0]) {
+    /* Wildcard, so the actual compare will start at the second character of wc_str */
+    wc_post = wc_str->buf + 1;
+    wc_len--;
+  } else if (str->len == wc_len) {
+    /* No wildcard, but the strings are the same length so may match.
+     * Compare the full strings. */
+    wc_post=wc_str->buf;
+    wc_len=wc_str->len;
+  } else {
+    /* No wildcard and strings are different length, so no match */
+    return 0;
+  }
+
+  /* A match is not possible if the fixed part of the wildcard string is longer than
+   * the string to match it against. */
+  if (wc_len > str->len)
+    return 0;
+
+  /* Now we compare the last wc_len characters of str against wc_post */
+  return (0 == strncmp(str->buf + str->len - wc_len, wc_post, wc_len));
+}
+
 void tr_name_strlcat(char *dest, const TR_NAME *src, size_t len)
 {
   size_t used_len;
@@ -113,7 +171,7 @@ void tr_name_strlcat(char *dest, const TR_NAME *src, size_t len)
   else dest[0] = '\0';
 }
 
-  
+
 char * tr_name_strdup(TR_NAME *src)
 {
   char *s = calloc(src->len+1, 1);
index 94a6360..35c2714 100644 (file)
@@ -54,7 +54,7 @@ TR_RP_CLIENT *tr_rp_client_new(TALLOC_CTX *mem_ctx)
     client->next=NULL;
     client->comm_next=NULL;
     client->gss_names=NULL;
-    client->filter=NULL;
+    client->filters=NULL;
     talloc_set_destructor((void *)client, tr_rp_client_destructor);
   }
   return client;
@@ -96,12 +96,12 @@ int tr_rp_client_add_gss_name(TR_RP_CLIENT *rp_client, TR_NAME *gss_name)
   return tr_gss_names_add(rp_client->gss_names, gss_name);
 }
 
-int tr_rp_client_set_filter(TR_RP_CLIENT *client, TR_FILTER *filt)
+int tr_rp_client_set_filters(TR_RP_CLIENT *client, TR_FILTER_SET *filts)
 {
-  if (client->filter!=NULL)
-    tr_filter_free(client->filter);
-  client->filter=filt;
-  talloc_steal(client, filt);
+  if (client->filters!=NULL)
+    tr_filter_set_free(client->filters);
+  client->filters=filts;
+  talloc_steal(client, filts);
   return 0; /* success */
 }
 
index 5f4b4ae..5a770b8 100644 (file)
@@ -131,6 +131,7 @@ TR_COMM_MEMB *tr_comm_table_find_idp_memb_origin(TR_COMM_TABLE *ctab, TR_NAME *i
 TR_COMM_MEMB *tr_comm_table_find_idp_memb(TR_COMM_TABLE *ctab, TR_NAME *idp_realm, TR_NAME *comm);
 TR_COMM *tr_comm_table_find_comm(TR_COMM_TABLE *ctab, TR_NAME *comm_id);
 size_t tr_comm_table_size(TR_COMM_TABLE *ctab);
+char *tr_comm_table_to_str(TALLOC_CTX *mem_ctx, TR_COMM_TABLE *ctab);
 void tr_comm_table_print(FILE *f, TR_COMM_TABLE *ctab);
 
 TR_COMM_MEMB *tr_comm_memb_new(TALLOC_CTX *mem_ctx);
index 46f5024..9e556f4 100644 (file)
 
 #include <trust_router/tr_name.h>
 #include <trust_router/tr_constraint.h>
+#include <trust_router/tid.h>
+#include <trust_router/trp.h>
 
-#define TR_MAX_FILTERS 5
+#define TR_MAX_FILTERS  5
 #define TR_MAX_FILTER_LINES 8
 #define TR_MAX_FILTER_SPECS 8
+#define TR_MAX_FILTER_SPEC_MATCHES 8
 
 /* Filter actions */
 typedef enum {
-  TR_FILTER_ACTION_REJECT=0,
+  TR_FILTER_ACTION_REJECT = 0,
   TR_FILTER_ACTION_ACCEPT,
   TR_FILTER_ACTION_UNKNOWN
 } TR_FILTER_ACTION;
@@ -58,16 +61,15 @@ typedef enum {
 
 /* Filter types */
 typedef enum {
-  TR_FILTER_TYPE_TID_INCOMING=0,
+  TR_FILTER_TYPE_TID_INBOUND = 0,
+  TR_FILTER_TYPE_TRP_INBOUND,
+  TR_FILTER_TYPE_TRP_OUTBOUND,
   TR_FILTER_TYPE_UNKNOWN
 } TR_FILTER_TYPE;
-/* #define for backward compatibility, TODO: get rid of this -jlr */
-#define TR_FILTER_TYPE_RP_PERMITTED TR_FILTER_TYPE_TID_INCOMING
-
 
 typedef struct tr_fspec {
   TR_NAME *field;
-  TR_NAME *match;
+  TR_NAME *match[TR_MAX_FILTER_SPEC_MATCHES];
 } TR_FSPEC;
 
 typedef struct tr_fline {
@@ -76,27 +78,70 @@ typedef struct tr_fline {
   TR_CONSTRAINT *realm_cons;
   TR_CONSTRAINT *domain_cons;
 } TR_FLINE;
-  
+
 typedef struct tr_filter {
   TR_FILTER_TYPE type;
   TR_FLINE *lines[TR_MAX_FILTER_LINES];
 } TR_FILTER;
 
+
+typedef struct tr_filter_set TR_FILTER_SET;
+struct tr_filter_set {
+  TR_FILTER *this;
+  TR_FILTER_SET *next;
+};
+
+/**
+ * Structure to hold information needed to filter different targets.
+ */
+typedef struct tr_filter_target {
+  /* An inforec also needs realm and community information */
+  TRP_INFOREC *trp_inforec;
+  TRP_UPD *trp_upd;
+
+  /* a TID request has all the data it needs to be filtered */
+  TID_REQ *tid_req;
+} TR_FILTER_TARGET;
+
+TR_FILTER_SET *tr_filter_set_new(TALLOC_CTX *mem_ctx);
+void tr_filter_set_free(TR_FILTER_SET *fs);
+int tr_filter_set_add(TR_FILTER_SET *set, TR_FILTER *new);
+TR_FILTER *tr_filter_set_get(TR_FILTER_SET *set, TR_FILTER_TYPE type);
+
 TR_FILTER *tr_filter_new(TALLOC_CTX *mem_ctx);
+
 void tr_filter_free(TR_FILTER *filt);
+
 void tr_filter_set_type(TR_FILTER *filt, TR_FILTER_TYPE type);
+
 TR_FILTER_TYPE tr_filter_get_type(TR_FILTER *filt);
 
 TR_FLINE *tr_fline_new(TALLOC_CTX *mem_ctx);
+
 void tr_fline_free(TR_FLINE *fline);
+
 TR_FSPEC *tr_fspec_new(TALLOC_CTX *mem_ctx);
+
 void tr_fspec_free(TR_FSPEC *fspec);
-void tr_fspec_set_match(TR_FSPEC *fspec, TR_NAME *match);
-int tr_fspec_matches(TR_FSPEC *fspec, TR_NAME *name);
+
+void tr_fspec_add_match(TR_FSPEC *fspec, TR_NAME *match);
+
+int tr_fspec_matches(TR_FSPEC *fspec, TR_FILTER_TYPE ftype, TR_FILTER_TARGET *target);
 
 
 /*In tr_constraint.c and exported, but not really a public symbol; needed by tr_filter.c and by tr_constraint.c*/
-int TR_EXPORT tr_prefix_wildcard_match (const char *str, const char *wc_str);
-int tr_filter_process_rp_permitted (TR_NAME *rp_realm, TR_FILTER *rpp_filter, TR_CONSTRAINT_SET *in_constraints, TR_CONSTRAINT_SET **out_constraints, int *out_action);
-TR_CONSTRAINT_SET *tr_constraint_set_from_fline (TR_FLINE *fline);
+int TR_EXPORT tr_prefix_wildcard_match(const char *str, const char *wc_str);
+
+int tr_filter_apply(TR_FILTER_TARGET *target, TR_FILTER *filt, TR_CONSTRAINT_SET **constraints, TR_FILTER_ACTION *out_action);
+void tr_filter_target_free(TR_FILTER_TARGET *target);
+TR_FILTER_TARGET *tr_filter_target_tid_req(TALLOC_CTX *mem_ctx, TID_REQ *req);
+TR_FILTER_TARGET *tr_filter_target_trp_inforec(TALLOC_CTX *mem_ctx, TRP_UPD *upd, TRP_INFOREC *inforec);
+
+TR_CONSTRAINT_SET *tr_constraint_set_from_fline(TR_FLINE *fline);
+
+int tr_filter_validate(TR_FILTER *filt);
+int tr_filter_validate_spec_field(TR_FILTER_TYPE ftype, TR_FSPEC *fspec);
+const char *tr_filter_type_to_string(TR_FILTER_TYPE ftype);
+TR_FILTER_TYPE tr_filter_type_from_string(const char *s);
+
 #endif
index 0a9096f..e10fd1a 100644 (file)
@@ -69,7 +69,7 @@ void tr_msg_set_trp_req(TR_MSG *msg, TRP_REQ *req);
 
 /* Encoders/Decoders */
 char *tr_msg_encode(TR_MSG *msg);
-TR_MSG *tr_msg_decode(char *jmsg, size_t len);
+TR_MSG *tr_msg_decode(const char *jmsg, size_t len);
 void tr_msg_free_encoded(char *jmsg);
 void tr_msg_free_decoded(TR_MSG *msg);
 
index 7e8f8f0..e150f9a 100644 (file)
@@ -44,7 +44,7 @@ typedef struct tr_rp_client {
   struct tr_rp_client *next;
   struct tr_rp_client *comm_next;
   TR_GSS_NAMES *gss_names;
-  TR_FILTER *filter;
+  TR_FILTER_SET *filters;
 } TR_RP_CLIENT;
 
 /* Structure to make a linked list of RP realms by name for community config */
@@ -60,7 +60,7 @@ void tr_rp_client_free(TR_RP_CLIENT *client);
 TR_RP_CLIENT *tr_rp_client_add_func(TR_RP_CLIENT *clients, TR_RP_CLIENT *new);
 #define tr_rp_client_add(clients,new) ((clients)=tr_rp_client_add_func((clients),(new)))
 int tr_rp_client_add_gss_name(TR_RP_CLIENT *client, TR_NAME *name);
-int tr_rp_client_set_filter(TR_RP_CLIENT *client, TR_FILTER *filt);
+int tr_rp_client_set_filters(TR_RP_CLIENT *client, TR_FILTER_SET *filts);
 TR_RP_CLIENT *tr_rp_client_lookup(TR_RP_CLIENT *rp_clients, TR_NAME *gss_name);
 
 TR_RP_REALM *tr_rp_realm_new(TALLOC_CTX *mem_ctx);
index a0d17b3..7171952 100644 (file)
@@ -41,6 +41,7 @@
 #include <trust_router/tr_name.h>
 #include <tr_gss.h>
 #include <trust_router/trp.h>
+#include <tr_filter.h>
 
 typedef enum trp_peer_conn_status {
   PEER_DISCONNECTED=0,
@@ -61,6 +62,7 @@ struct trp_peer {
   TRP_PEER_CONN_STATUS incoming_status;
   void (*conn_status_cb)(TRP_PEER *, void *); /* callback for connected status change */
   void *conn_status_cookie;
+  TR_FILTER_SET *filters;
 };
 
 typedef struct trp_ptable {
@@ -106,6 +108,8 @@ void trp_peer_set_incoming_status(TRP_PEER *peer, TRP_PEER_CONN_STATUS status);
 int trp_peer_is_connected(TRP_PEER *peer);
 void trp_peer_set_linkcost(TRP_PEER *peer, unsigned int linkcost);
 void trp_peer_set_conn_status_cb(TRP_PEER *peer, void (*cb)(TRP_PEER *, void *), void *cookie);
+void trp_peer_set_filters(TRP_PEER *peer, TR_FILTER_SET *filts);
+TR_FILTER *trp_peer_get_filter(TRP_PEER *peer, TR_FILTER_TYPE ftype);
 char *trp_peer_to_str(TALLOC_CTX *memctx, TRP_PEER *peer, const char *sep);
 
 #endif /* _TRP_PTABLE_H_ */
index 9f76047..2594b36 100644 (file)
@@ -45,8 +45,8 @@
 
 
 typedef struct tr_constraint {
-  TR_NAME *type;
-  TR_NAME *matches[TR_MAX_CONST_MATCHES];
+    TR_NAME *type;
+    TR_NAME *matches[TR_MAX_CONST_MATCHES];
 } TR_CONSTRAINT;
 
 TR_CONSTRAINT *tr_constraint_new(TALLOC_CTX *mem_ctx);
@@ -54,32 +54,17 @@ void tr_constraint_free(TR_CONSTRAINT *cons);
 TR_CONSTRAINT *tr_constraint_dup(TALLOC_CTX *mem_ctx, TR_CONSTRAINT *cons);
 
 void TR_EXPORT tr_constraint_add_to_set (TR_CONSTRAINT_SET **cs, TR_CONSTRAINT *c);
-
 int TR_EXPORT tr_constraint_set_validate( TR_CONSTRAINT_SET *);
-/**
- * Create a new constraint set containing all constraints from #orig
- * with constraint_type #constraint_type and no others.  This constraint set is
- * live until #request is freed.
- */
 TR_EXPORT TR_CONSTRAINT_SET *tr_constraint_set_filter(TID_REQ *request,
-                                  TR_CONSTRAINT_SET *orig,
-                                  const char * constraint_type);
-
-TR_EXPORT TR_CONSTRAINT_SET
-*tr_constraint_set_intersect(TID_REQ *request,
-                            TR_CONSTRAINT_SET *input);
-
-/** Get the set of wildcard strings that matches a fully intersected
- * constraint set.  Requires that the constraint set only have one
- * constraint in it, but the constraint may have multiple matches for
- * a given type.  Returns true on success false on failure.  The
- * output is live as long as the request is live.
- */
+                                                      TR_CONSTRAINT_SET *orig,
+                                                      const char * constraint_type);
+TR_EXPORT TR_CONSTRAINT_SET *tr_constraint_set_intersect(TID_REQ *request,
+                                                         TR_CONSTRAINT_SET *input);
 int TR_EXPORT tr_constraint_set_get_match_strings(TID_REQ *,
-                                           TR_CONSTRAINT_SET *,
-                                                 const char * constraint_type,
-                                                 tr_const_string **output,
-                                           size_t *output_len);
+                                                  TR_CONSTRAINT_SET *,
+                                                  const char * constraint_type,
+                                                  tr_const_string **output,
+                                                  size_t *output_len);
+
 
 #endif
index 7e86003..1f392a8 100644 (file)
@@ -49,6 +49,8 @@ TR_EXPORT TR_NAME *tr_new_name (const char *name);
 TR_EXPORT TR_NAME *tr_dup_name (TR_NAME *from);
 TR_EXPORT void tr_free_name (TR_NAME *name);
 TR_EXPORT int tr_name_cmp (TR_NAME *one, TR_NAME *two);
+int tr_name_cmp_str(TR_NAME *one, const char *two_str);
+int tr_name_prefix_wildcard_match(TR_NAME *str, TR_NAME *wc_str);
 TR_EXPORT void tr_name_strlcat(char *dest, const TR_NAME *src, size_t len);
 TR_EXPORT char *tr_name_strdup(TR_NAME *);
 TR_EXPORT json_t *tr_name_to_json_string(TR_NAME *src);
index 7e524af..1c8e193 100644 (file)
@@ -79,6 +79,8 @@ void trp_upd_free(TRP_UPD *update);
 TR_EXPORT TRP_INFOREC *trp_upd_get_inforec(TRP_UPD *upd);
 void trp_upd_set_inforec(TRP_UPD *upd, TRP_INFOREC *rec);
 void trp_upd_add_inforec(TRP_UPD *upd, TRP_INFOREC *rec);
+void trp_upd_remove_inforec(TRP_UPD *upd, TRP_INFOREC *rec);
+size_t trp_upd_num_inforecs(TRP_UPD *upd);
 TR_EXPORT TR_NAME *trp_upd_get_realm(TRP_UPD *upd);
 TR_NAME *trp_upd_dup_realm(TRP_UPD *upd);
 void trp_upd_set_realm(TRP_UPD *upd, TR_NAME *realm);
index 96e1d07..8697ece 100644 (file)
@@ -83,19 +83,25 @@ static void tidc_resp_handler (TIDC_INSTANCE * tidc,
 }
 
 
+static void print_version_info(void)
+{
+  printf("Moonshot TID Client %s\n\n", PACKAGE_VERSION);
+}
+
 /* command-line option setup */
 
 /* argp global parameters */
 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
 
 /* doc strings */
-static const char doc[]=PACKAGE_NAME " - TID Client";
+static const char doc[]=PACKAGE_NAME " - Moonshot TID Client " PACKAGE_VERSION;
 static const char arg_doc[]="<server> <RP-realm> <target-realm> <community> [<port>]"; /* string describing arguments, if any */
 
 /* define the options here. Fields are:
  * { long-name, short-name, variable name, options, help description } */
 static const struct argp_option cmdline_options[] = {
-  { NULL }
+    { "version", 'v', NULL, 0, "Print version information and exit"},
+    { NULL }
 };
 
 /* structure for communicating with option parser */
@@ -149,6 +155,10 @@ static error_t parse_option(int key, char *arg, struct argp_state *state)
     }
     break;
 
+  case 'v':
+    print_version_info();
+    exit(0);
+
   default:
     return ARGP_ERR_UNKNOWN;
   }
@@ -179,6 +189,8 @@ int main (int argc,
   argp_parse(&argp, argc, argv, 0, 0, &opts);
   /* TBD -- validity checking, dealing with quotes, etc. */
 
+  print_version_info();
+
   /* Use standalone logging */
   tr_log_open();
 
index 7b58840..8673cdd 100644 (file)
@@ -278,18 +278,24 @@ static int auth_handler(gss_name_t gss_name, TR_NAME *client,
   return result;
 }
 
+static void print_version_info(void)
+{
+  printf("Moonshot TID Server %s\n\n", PACKAGE_VERSION);
+}
+
 /* command-line option setup */
 
 /* argp global parameters */
 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
 
 /* doc strings */
-static const char doc[]=PACKAGE_NAME " - TID Server";
+static const char doc[]=PACKAGE_NAME " - Moonshot TID Server " PACKAGE_VERSION;
 static const char arg_doc[]="<ip-address> <gss-name> <hostname> <database-name>"; /* string describing arguments, if any */
 
 /* define the options here. Fields are:
  * { long-name, short-name, variable name, options, help description } */
 static const struct argp_option cmdline_options[] = {
+  { "version", 'v', NULL, 0, "Print version information and exit"},
   { NULL }
 };
 
@@ -339,6 +345,10 @@ static error_t parse_option(int key, char *arg, struct argp_state *state)
     }
     break;
 
+  case 'v':
+    print_version_info();
+    exit(0);
+
   default:
     return ARGP_ERR_UNKNOWN;
   }
@@ -354,11 +364,13 @@ int main (int argc,
 {
   TIDS_INSTANCE *tids;
   TR_NAME *gssname = NULL;
-  struct cmdline_args opts={NULL};
+  struct cmdline_args opts={0};
 
   /* parse the command line*/
   argp_parse(&argp, argc, argv, 0, 0, &opts);
 
+  print_version_info();
+
   talloc_set_log_stderr();
 
   /* Use standalone logging */
index c3f1a27..db87adf 100644 (file)
@@ -220,6 +220,9 @@ TID_REQ *tid_dup_req (TID_REQ *orig_req)
 }
 
 
+/* Adds the JSON object ref to req's list of objects to release when the
+ * req is freed.
+ */
 void tid_req_cleanup_json( TID_REQ *req, json_t *ref)
 {
   (void) json_array_append_new(req->json_references, ref);
index 1f2e2de..a03ef4b 100644 (file)
 
 /***** command-line option handling / setup *****/
 
+static void print_version_info(void)
+{
+  printf("Moonshot Trust Router %s\n\n", PACKAGE_VERSION);
+}
+
 /* Strip trailing / from a path name.*/
 static void remove_trailing_slash(char *s) {
   size_t n;
@@ -69,19 +74,21 @@ static void remove_trailing_slash(char *s) {
 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
 
 /* doc strings */
-static const char doc[]=PACKAGE_NAME " - Moonshot Trust Router";
+static const char doc[]=PACKAGE_NAME " - Moonshot Trust Router " PACKAGE_VERSION;
 static const char arg_doc[]=""; /* string describing arguments, if any */
 
 /* define the options here. Fields are:
  * { long-name, short-name, variable name, options, help description } */
 static const struct argp_option cmdline_options[] = {
     { "config-dir", 'c', "DIR", 0, "Specify configuration file location (default is current directory)"},
+    { "version", 'v', NULL, 0, "Print version information and exit"},
     { NULL }
 };
 
 /* structure for communicating with option parser */
 struct cmdline_args {
-  char *config_dir;
+    int version_requested;
+    char *config_dir;
 };
 
 /* parser for individual options - fills in a struct cmdline_args */
@@ -91,16 +98,20 @@ static error_t parse_option(int key, char *arg, struct argp_state *state)
   struct cmdline_args *arguments=state->input;
 
   switch (key) {
-  case 'c':
-    if (arg == NULL) {
-      /* somehow we got called without an argument */
+    case 'c':
+      if (arg == NULL) {
+        /* somehow we got called without an argument */
+        return ARGP_ERR_UNKNOWN;
+      }
+      arguments->config_dir=arg;
+      break;
+
+    case 'v':
+      arguments->version_requested=1;
+      break;
+
+    default:
       return ARGP_ERR_UNKNOWN;
-    }
-    arguments->config_dir=arg;
-    break;
-
-  default:
-    return ARGP_ERR_UNKNOWN;
   }
 
   return 0; /* success */
@@ -159,6 +170,7 @@ int main(int argc, char *argv[])
 
   /***** parse command-line arguments *****/
   /* set defaults */
+  opts.version_requested=0;
   opts.config_dir=".";
 
   /* parse the command line*/
@@ -167,6 +179,12 @@ int main(int argc, char *argv[])
   /* process options */
   remove_trailing_slash(opts.config_dir);
 
+
+  /***** Print version info *****/
+  print_version_info();
+  if (opts.version_requested)
+    return 0; /* requested that we print version and exit */
+
   /***** create a Trust Router instance *****/
   if (NULL == (tr = tr_create(main_ctx))) {
     tr_crit("Unable to create Trust Router instance, exiting.");
index 64c0a16..37ee89f 100644 (file)
@@ -247,7 +247,7 @@ static int tr_tids_req_handler(TIDS_INSTANCE *tids,
   TID_REQ *fwd_req = NULL;
   TR_COMM *cfg_comm = NULL;
   TR_COMM *cfg_apc = NULL;
-  int oaction = TR_FILTER_ACTION_REJECT;
+  TR_FILTER_ACTION oaction = TR_FILTER_ACTION_REJECT;
   time_t expiration_interval=0;
   struct tr_tids_event_cookie *cookie=talloc_get_type_abort(cookie_in, struct tr_tids_event_cookie);
   TR_CFG_MGR *cfg_mgr=cookie->cfg_mgr;
@@ -261,6 +261,7 @@ static int tr_tids_req_handler(TIDS_INSTANCE *tids,
   unsigned int resp_frac_numer=cfg_mgr->active->internal->tid_resp_numer;
   unsigned int resp_frac_denom=cfg_mgr->active->internal->tid_resp_denom;
   TR_RESP_COOKIE *payload=NULL;
+  TR_FILTER_TARGET *target=NULL;
   int ii=0;
   int retval=-1;
 
@@ -295,21 +296,31 @@ static int tr_tids_req_handler(TIDS_INSTANCE *tids,
    * the TIDS handler subprocess. */
 
   if ((!tids->rp_gss) || 
-      (!tids->rp_gss->filter)) {
+      (!tids->rp_gss->filters)) {
     tr_notice("tr_tids_req_handler: No GSS name for incoming request.");
     tids_send_err_response(tids, orig_req, "No GSS name for request");
     retval=-1;
     goto cleanup;
   }
 
-  if ((TR_FILTER_NO_MATCH == tr_filter_process_rp_permitted(orig_req->rp_realm,
-                                                            tids->rp_gss->filter,
-                                                            orig_req->cons,
-                                                           &fwd_req->cons,
-                                                           &oaction)) ||
-      (TR_FILTER_ACTION_REJECT == oaction)) {
-    tr_notice("tr_tids_req_handler: RP realm (%s) does not match RP Realm filter for GSS name", orig_req->rp_realm->buf);
-    tids_send_err_response(tids, orig_req, "RP Realm filter error");
+  /* Keep original constraints, may add more from the filter. These will be added to orig_req as
+   * well. Need to verify that this is acceptable behavior, but it's what we've always done. */
+  fwd_req->cons=orig_req->cons;
+
+  target=tr_filter_target_tid_req(tmp_ctx, orig_req);
+  if (target==NULL) {
+    /* TODO: signal that filtering failed. Until then, just filter everything and give an error message. */
+    tr_crit("tid_req_handler: Unable to allocate filter target, cannot apply filter!");
+  }
+  if ((target==NULL)
+      || (TR_FILTER_NO_MATCH == tr_filter_apply(target,
+                                                tr_filter_set_get(tids->rp_gss->filters,
+                                                                  TR_FILTER_TYPE_TID_INBOUND),
+                                                &(fwd_req->cons),
+                                                &oaction))
+      || (TR_FILTER_ACTION_ACCEPT != oaction)) {
+    tr_notice("tr_tids_req_handler: Incoming TID request rejected by filter for GSS name", orig_req->rp_realm->buf);
+    tids_send_err_response(tids, orig_req, "Incoming TID request filter error");
     retval=-1;
     goto cleanup;
   }
index 2b93969..2ee5a45 100644 (file)
@@ -237,6 +237,26 @@ static void tr_trps_print_route_table(TRPS_INSTANCE *trps, FILE *f)
   }
 }
 
+static void tr_trps_print_comm_table(TRPS_INSTANCE *trps, FILE *f)
+{
+  char *table=tr_comm_table_to_str(NULL, trps->ctable);
+  if (table==NULL)
+    fprintf(f, "Unable to print community table.\n");
+  else {
+    fprintf(f, "%s\n", table);
+    talloc_free(table);
+  }
+}
+
+/**
+ * Event handler to process TRP messages from connection threads. These
+ * are added to the message queue (mq) in tr_trps_msg_handler(), which
+ * runs in the other threads.
+ *
+ * @param socket Ignored
+ * @param event Ignored
+ * @param arg Pointer to the TRPS_INSTANCE
+ */
 static void tr_trps_process_mq(int socket, short event, void *arg)
 {
   TRPS_INSTANCE *trps=talloc_get_type_abort(arg, TRPS_INSTANCE);
@@ -298,6 +318,7 @@ static void tr_trps_process_mq(int socket, short event, void *arg)
         tr_notice("tr_trps_process_mq: error handling message.");
       else {
         tr_trps_print_route_table(trps, stderr);
+        tr_trps_print_comm_table(trps, stderr);
       }
     }
     else
@@ -331,6 +352,7 @@ static void tr_trps_sweep(int listener, short event, void *arg)
   tr_debug("tr_trps_sweep: sweeping communities.");
   trps_sweep_ctable(trps);
   tr_trps_print_route_table(trps, stderr);
+  tr_trps_print_comm_table(trps, stderr);
   /* schedule the event to run again */
   event_add(ev, &(trps->sweep_interval));
 }
@@ -849,5 +871,6 @@ void tr_config_changed(TR_CFG *new_cfg, void *cookie)
   trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
   tr_print_config(new_cfg);
   tr_trps_print_route_table(trps, stderr);
+  tr_trps_print_comm_table(trps, stderr);
 }
 
index f5ea1fb..b954584 100644 (file)
@@ -66,6 +66,7 @@ TRP_PEER *trp_peer_new(TALLOC_CTX *memctx)
     peer->incoming_status=PEER_DISCONNECTED;
     peer->conn_status_cb=NULL;
     peer->conn_status_cookie=NULL;
+    peer->filters=NULL;
     talloc_set_destructor((void *)peer, trp_peer_destructor);
   }
   return peer;
@@ -147,7 +148,7 @@ void trp_peer_add_gss_name(TRP_PEER *peer, TR_NAME *gss_name)
 void trp_peer_set_gss_names(TRP_PEER *peer, TR_GSS_NAMES *gss_names)
 {
   if (peer->gss_names!=NULL)
-    talloc_free(peer->gss_names);
+    tr_gss_names_free(peer->gss_names);
 
   peer->gss_names=gss_names;
   talloc_steal(peer, gss_names);
@@ -206,6 +207,27 @@ void trp_peer_set_conn_status_cb(TRP_PEER *peer, void (*cb)(TRP_PEER *, void *),
   peer->conn_status_cookie=cookie;
 }
 
+/**
+ * Set the filter associated with this peer. Any existing filter will be freed. Takes responsibility for
+ * freeing the new filter.
+ *
+ * @param peer Peer to modify
+ * @param filts New filter to attach to the peer
+ */
+void trp_peer_set_filters(TRP_PEER *peer, TR_FILTER_SET *filts)
+{
+  if (peer->filters!=NULL)
+    tr_filter_set_free(peer->filters);
+
+  peer->filters=filts;
+  talloc_steal(peer, filts);
+}
+
+TR_FILTER *trp_peer_get_filter(TRP_PEER *peer, TR_FILTER_TYPE ftype)
+{
+  return tr_filter_set_get(peer->filters, ftype);
+}
+
 struct timespec *trp_peer_get_last_conn_attempt(TRP_PEER *peer)
 {
   return &(peer->last_conn_attempt);
index 98898ff..9b39f2c 100644 (file)
@@ -32,6 +32,7 @@
  *
  */
 
+#include <strings.h>
 #include <jansson.h>
 #include <talloc.h>
 
@@ -80,7 +81,7 @@ TRP_INFOREC_TYPE trp_inforec_type_from_string(const char *s)
   struct trp_inforec_type_entry *entry=trp_inforec_type_table;
 
   while ((entry->type != TRP_INFOREC_TYPE_UNKNOWN)
-        && (strcmp(s, entry->name)!=0)) {
+        && (strcasecmp(s, entry->name)!=0)) {
     entry++;
   }
   return entry->type;
@@ -677,6 +678,45 @@ void trp_upd_add_inforec(TRP_UPD *upd, TRP_INFOREC *rec)
   talloc_steal(upd, rec);
 }
 
+/**
+ * Removes and frees the selected inforec.
+ *
+ * @param upd Update to remove from
+ * @param rec Inforec to remove
+ */
+void trp_upd_remove_inforec(TRP_UPD *upd, TRP_INFOREC *rec)
+{
+  TRP_INFOREC *this=upd->records;
+
+  /* special case for the first element */
+  if (this==rec) {
+    upd->records=upd->records->next;
+    trp_inforec_free(this);
+    return;
+  }
+
+  while (this->next!=NULL) {
+    if (this->next==rec) {
+      this->next=this->next->next; /* this->next is not null */
+      trp_inforec_free(rec);
+    }
+    this=this->next;
+  }
+}
+
+size_t trp_upd_num_inforecs(TRP_UPD *upd)
+{
+  size_t count=0;
+  TRP_INFOREC *this=upd->records;
+
+  while (this != NULL) {
+    count++;
+    this=this->next;
+  }
+  return count;
+}
+
+
 TR_NAME *trp_upd_get_realm(TRP_UPD *upd)
 {
   return upd->realm;
index c706f72..1dd1f6c 100644 (file)
@@ -1003,6 +1003,56 @@ cleanup:
   return rc;
 }
 
+/**
+ * Apply applicable TRP_INBOUND filters to an inforec. Rejects everything if peer has no filters.
+ *
+ * @param trps Active TRPS instance
+ * @param upd TRP_UPD that contains the inforec to filter
+ * @param rec Inforec to filter
+ * @return 1 if accepted by the filter, 0 otherwise
+ */
+static int trps_filter_inbound_inforec(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
+{
+  TRP_PEER *peer=NULL;
+  TR_NAME *peer_name=NULL;
+  TR_FILTER_ACTION action=TR_FILTER_ACTION_REJECT;
+  TR_FILTER_TARGET *target=NULL;
+  int retval=0;
+
+  /* Look up the peer. For inbound messages, the peer is identified by its GSS name */
+  peer_name=trp_upd_get_peer(upd);
+  peer=trps_get_peer_by_gssname(trps, peer_name);
+  if (peer==NULL) {
+    tr_err("trps_filter_inbound_inforec: received inforec from unknown peer (%.*s), rejecting.",
+           peer_name->len,
+           peer_name->buf);
+    return 0;
+  }
+
+  /* tr_filter_apply() and tr_filter_set_get() handle null filter sets/filters by rejecting */
+  target= tr_filter_target_trp_inforec(NULL, upd, rec);
+  if (target==NULL) {
+    /* TODO: signal that filtering failed. Until then, just filter everything and give an error message. */
+    tr_crit("trps_filter_inbound_inforec: Unable to allocate filter target, cannot apply filter!");
+  }
+  if ((target==NULL)
+      || (TR_FILTER_NO_MATCH==tr_filter_apply(target,
+                                              tr_filter_set_get(peer->filters, TR_FILTER_TYPE_TRP_INBOUND),
+                                              NULL,
+                                              &action))
+      || (action!=TR_FILTER_ACTION_ACCEPT)) {
+    /* either the filter did not match or it matched a reject rule or allocating the target failed */
+    retval=0;
+  } else
+    retval=1;
+  if (target!=NULL)
+    tr_filter_target_free(target);
+
+  /* filter matched an accept rule */
+  return retval;
+}
+
+
 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
 {
   TRP_INFOREC *rec=NULL;
@@ -1021,6 +1071,11 @@ static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
   }
 
   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
+    if (!trps_filter_inbound_inforec(trps, upd, rec)) {
+      tr_debug("trps_handle_update: inforec rejected by filter.");
+      continue; /* just go on to the next record */
+    }
+
     switch (trp_inforec_get_type(rec)) {
     case TRP_INFOREC_TYPE_ROUTE:
       tr_debug("trps_handle_update: handling route inforec.");
@@ -1610,6 +1665,57 @@ cleanup:
   return rc;
 }
 
+/**
+ * Filter the inforecs in a single update
+ *
+ * @param filt The filter to apply
+ * @param upd The update to filter
+ */
+static void trps_filter_one_outbound_update(TR_FILTER *filt, TRP_UPD *upd)
+{
+  TRP_INFOREC *this=NULL, *next=NULL;
+  TR_FILTER_ACTION action=TR_FILTER_ACTION_REJECT;
+  TR_FILTER_TARGET *target=NULL;
+
+  for(this=trp_upd_get_inforec(upd); this!=NULL; this=next) {
+    next=this->next;
+    target= tr_filter_target_trp_inforec(NULL, upd, this);
+    if (target==NULL) {
+      /* TODO: signal that filtering failed. Until then, just filter everything and give an error message. */
+      tr_crit("trps_filter_one_outbound_update: Unable to allocate filter target, cannot apply filter!");
+    }
+    if ((target==NULL)
+        || (TR_FILTER_NO_MATCH==tr_filter_apply(target, filt, NULL, &action))
+        || (action!=TR_FILTER_ACTION_ACCEPT)) {
+      /* Either no filter matched or one matched and rejected this record.
+       * Also filter out record if we were unable to allocate a target. */
+      trp_upd_remove_inforec(upd, this); /* "this" is now invalid */
+    }
+    if (target!=NULL)
+      tr_filter_target_free(target);
+  }
+}
+
+/**
+ * May shuffle the update list.
+ *
+ * @param filters The filter set for the relevant TRP peer
+ * @param updates GPtrArray of updates to filter
+ */
+static void trps_filter_outbound_updates(TR_FILTER_SET *filters, GPtrArray *updates)
+{
+  TRP_UPD *upd=NULL;
+  guint ii=0;
+
+  /* walk backward through the array so we can remove elements */
+  for (ii=updates->len-1; ii>=0; ii--) {
+    upd=g_ptr_array_index(updates, ii);
+    trps_filter_one_outbound_update(tr_filter_set_get(filters, TR_FILTER_TYPE_TRP_OUTBOUND), upd);
+    /* see if we removed all the records from this update */
+    if (trp_upd_num_inforecs(upd)==0)
+      g_ptr_array_remove_index_fast(updates, ii); /* does not preserve order at index ii or higher */
+  }
+}
 
 /* helper for trps_update_one_peer. Frees the TRP_UPD pointed to by a GPtrArray element */
 static void trps_trp_upd_destroy(gpointer data)
@@ -1621,8 +1727,8 @@ static void trps_trp_upd_destroy(gpointer data)
 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
                                    TRP_PEER *peer,
                                    TRP_UPDATE_TYPE update_type,
-                                   TR_NAME *comm,
-                                   TR_NAME *realm)
+                                   TR_NAME *realm,
+                                   TR_NAME *comm)
 {
   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
   TR_MSG msg; /* not a pointer! */
@@ -1703,26 +1809,33 @@ static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
   if (updates->len<=0)
     tr_debug("trps_update_one_peer: no updates for %.*s", peer_label->len, peer_label->buf);
   else {
-    tr_debug("trps_update_one_peer: sending %d update messages.", updates->len);
-    for (ii=0; ii<updates->len; ii++) {
-      upd=(TRP_UPD *)g_ptr_array_index(updates, ii);
-      /* now encode the update message */
-      tr_msg_set_trp_upd(&msg, upd);
-      encoded=tr_msg_encode(&msg);
-      if (encoded==NULL) {
-        tr_err("trps_update_one_peer: error encoding update.");
-        rc=TRP_ERROR;
-        goto cleanup;
-      }
+    /* Apply outbound TRP filters for this peer */
+    trps_filter_outbound_updates(peer->filters, updates);
 
-      tr_debug("trps_update_one_peer: adding message to queue.");
-      if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
-        tr_err("trps_update_one_peer: error queueing update.");
-      else
-        tr_debug("trps_update_one_peer: update queued successfully.");
+    if (updates->len<=0)
+      tr_debug("trps_update_one_peer: no updates for %.*s after filtering.", peer_label->len, peer_label->buf);
+    else {
+      tr_debug("trps_update_one_peer: sending %d update messages.", updates->len);
+      for (ii=0; ii<updates->len; ii++) {
+        upd = (TRP_UPD *) g_ptr_array_index(updates, ii);
+        /* now encode the update message */
+        tr_msg_set_trp_upd(&msg, upd);
+        encoded = tr_msg_encode(&msg);
+        if (encoded == NULL) {
+          tr_err("trps_update_one_peer: error encoding update.");
+          rc = TRP_ERROR;
+          goto cleanup;
+        }
 
-      tr_msg_free_encoded(encoded);
-      encoded=NULL;
+        tr_debug("trps_update_one_peer: adding message to queue.");
+        if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
+          tr_err("trps_update_one_peer: error queueing update.");
+        else
+          tr_debug("trps_update_one_peer: update queued successfully.");
+
+        tr_msg_free_encoded(encoded);
+        encoded = NULL;
+      }
     }
   }
 
@@ -1842,8 +1955,8 @@ static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
   return trps_update_one_peer(trps,
                               trps_get_peer_by_gssname(trps, trp_req_get_peer(req)),
                               TRP_UPDATE_REQUESTED,
-                              comm,
-                              realm);
+                              realm,
+                              comm);
 }