/// <summary> /// Create namespace-pod mapping /// hash of namespace as key, 'bitvector' of pods as value. /// </summary> /// <param name="pods">all pods.</param> /// <returns>namespace-pod mapping.</returns> public static Zen <IDictionary <int, IList <bool> > > CreateNSMatrix(Zen <Pod>[] pods) { var n = pods.Length; // create original data. Dictionary <int, bool[]> originalData = new Dictionary <int, bool[]>(); for (int i = 0; i < n; ++i) { var ns = pods[i].GetNS(); var hash = ns.GetHashCode(); if (!originalData.ContainsKey(hash)) { originalData[hash] = new bool[n]; } originalData[hash][i] = true; } // create zen data. Zen <IDictionary <int, IList <bool> > > nsMap = Language.EmptyDict <int, IList <bool> >(); foreach (var kv in originalData) { nsMap = nsMap.Add(kv.Key, kv.Value); } return(nsMap); }
private static T Interpret <T>(Zen <T> expression, ImmutableDictionary <string, object> arguments) { var environment = new ExpressionEvaluatorEnvironment(arguments); var interpreter = new ExpressionEvaluator(); return((T)expression.Accept(interpreter, environment)); }
/// <summary> /// Create user-pod mapping /// hash of user as key, 'bitvector' of pods as value /// assuming all pods have the user label. /// </summary> /// <param name="pods">all pods.</param> /// <param name="userKey">key of 'user label'.</param> /// <returns>user-pod mapping.</returns> public static Zen <IDictionary <int, IList <bool> > > GetUserHash(Zen <Pod>[] pods, Zen <string> userKey) { var n = pods.Length; Dictionary <int, bool[]> originalData = new Dictionary <int, bool[]>(); for (int i = 0; i < n; ++i) { var labelValue = pods[i].LabelValue(userKey); if (labelValue == null) { continue; } var hash = labelValue.GetHashCode(); if (!originalData.ContainsKey(hash)) { originalData[hash] = new bool[n]; } originalData[hash][i] = true; } // create zen data. Zen <IDictionary <int, IList <bool> > > userHashMap = EmptyDict <int, IList <bool> >(); foreach (var kv in originalData) { userHashMap = userHashMap.Add(kv.Key, kv.Value); } return(userHashMap); }
public void ReachabilityMatrix_OneDirectionOnly() { Zen <Pod>[] pods = new Zen <Pod>[] { Pod.Create("default", EmptyDict <string, string>().Add("k0", "v0"), EmptyList <string>().AddBack("k0")), Pod.Create("ns1", EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1")), }; Zen <Namespace>[] namespaces = new Zen <Namespace>[] { Namespace.Create("default", EmptyDict <string, string>().Add("k0", "v0"), EmptyList <string>().AddBack("k0")), Namespace.Create("ns1", EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1")) }; Zen <Policy>[] policies = new Zen <Policy>[] { // only one side allows ingress traffic Policy.Create("default", EmptyDict <string, string>().Add("k0", "v0"), EmptyDict <string, string>(), EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k0"), EmptyList <string>(), EmptyList <string>().AddBack("k1")), Policy.Create("ns1", EmptyDict <string, string>().Add("k1", "v1"), EmptyDict <string, string>(), EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1"), EmptyList <string>(), EmptyList <string>().AddBack("k1"), False(), False()), }; var output = Algorithms.CreateReachMatrix(pods, policies, namespaces).ingressMatrix; var r0 = EmptyList <bool>().AddBack(true).AddBack(false); var r1 = EmptyList <bool>().AddBack(false).AddBack(true); TestHelper.AssertMatrixEqual(output, new Zen <IList <bool> >[] { r0, r1 }, "Reachability Matrix, one direction only"); }
public Zen <bool> Build_Network(Zen <IList <int> > costs) { Zen <bool> network_expr = True(); foreach (KeyValuePair <int, HashSet <int> > kvp in node2neighbors) { // costs.At(1).Value() == Min(costs.At(0).Value() + 1, costs.At(2).Value() + 1), Zen <ushort> i = (Zen <ushort>)kvp.Key; // this is just i, but it doesn't allow me to cast -_- if (kvp.Key == dst_node) { continue; } Console.Write(kvp.Key + ": ["); Zen <bool> lower_limit_expr = True(); foreach (Zen <ushort> j in kvp.Value) { Console.Write(j + ", "); lower_limit_expr = And(lower_limit_expr, costs.At(i).Value() <= costs.At(j).Value() + 1); } Zen <bool> upper_limit_expr = False(); foreach (Zen <ushort> j in kvp.Value) { upper_limit_expr = Or(upper_limit_expr, costs.At(i).Value() >= costs.At(j).Value() + 1); } Console.WriteLine("]"); network_expr = And(network_expr, And(lower_limit_expr, upper_limit_expr)); } Console.WriteLine("physical edges" + physicalEdges.Count); Console.WriteLine("Network Expression " + network_expr); return(network_expr); }
public void SystemIsolationCheckTest() { var matrix = new Zen <IList <bool> >[] { EmptyList <bool>().AddBack(true).AddBack(true).AddBack(false).AddBack(false).AddBack(false), EmptyList <bool>().AddBack(false).AddBack(true).AddBack(true).AddBack(false).AddBack(false), EmptyList <bool>().AddBack(true).AddBack(false).AddBack(true).AddBack(false).AddBack(true), EmptyList <bool>().AddBack(false).AddBack(false).AddBack(false).AddBack(true).AddBack(false), EmptyList <bool>().AddBack(true).AddBack(true).AddBack(true).AddBack(true).AddBack(true), }; var expecteds = new Zen <IList <ushort> >[] { EmptyList <ushort>().AddBack(2).AddBack(3).AddBack(4), EmptyList <ushort>().AddBack(0).AddBack(3).AddBack(4), EmptyList <ushort>().AddBack(1).AddBack(3), EmptyList <ushort>().AddBack(0).AddBack(1).AddBack(2).AddBack(4), EmptyList <ushort>(), }; for (int i = 0; i < 5; ++i) { var output = Verifier.SystemIsolationCheck(matrix, (ushort)i); Assert.IsTrue(output.ToString().Equals(expecteds[i].ToString()), "SystemIsolatedCheckTest: pod{0} has wrong result.\nExpected: {1}\nGot: {2}", i, expecteds[i].ToString(), output.ToString()); } }
public static Zen <SimplePacket> Create( Zen <Ip> dstIp, Zen <Ip> srcIp) { return(Language.Create <SimplePacket>( ("DstIp", dstIp), ("SrcIp", srcIp))); }
public Zen <bool> Matches(Zen <IpHeader> hdr) { Zen <bool> dstLowMatch = hdr.GetDstIp().GetValue() >= this.DstIpLow.Value; Zen <bool> dstHighMatch = hdr.GetDstIp().GetValue() <= this.DstIpHigh.Value; return(And(dstLowMatch, dstHighMatch)); }
/// <summary> /// Model check an expression to find inputs that lead to it being false. /// </summary> /// <param name="expression">The expression.</param> /// <returns> /// Assignment to zen arbitrary variables that make the expression false. /// Null if no such assignment exists. /// </returns> public Dictionary <object, object> ModelCheck(Zen <bool> expression) { var symbolicEvaluator = new SymbolicEvaluationVisitor <TModel, TVar, TBool, TInt>(solver); var env = new SymbolicEvaluationEnvironment <TModel, TVar, TBool, TInt>(); var symbolicResult = (SymbolicBool <TModel, TVar, TBool, TInt>)expression.Accept(symbolicEvaluator, env); // Console.WriteLine($"[time] model checking: {watch.ElapsedMilliseconds}ms"); // watch.Restart(); var possibleModel = solver.Satisfiable(symbolicResult.Value); // Console.WriteLine($"[time] get sat: {watch.ElapsedMilliseconds}ms"); if (!possibleModel.HasValue) { return(null); } var model = possibleModel.Value; // compute the input given the assignment var arbitraryAssignment = new Dictionary <object, object>(); foreach (var kv in symbolicEvaluator.ArbitraryVariables) { var expr = kv.Key; var variable = kv.Value; arbitraryAssignment.Add(expr, this.solver.Get(model, variable)); } return(arbitraryAssignment); }
/// <summary> /// Processes an event and updates the current state. /// </summary> /// <param name="e">The event to process.</param> /// <param name="currentState">The current watchdog state.</param> /// <returns>The new watchdog state.</returns> private static Zen <SwitchState> ProcessEvent(Zen <Event> e, Zen <SwitchState> currentState) { var switchState = currentState; var burstEvent = Event.EventTypeAsByte(EventType.PacketBurstEvent); var stormStartEvent = Event.EventTypeAsByte(EventType.PfcStormStartEvent); var stormEndEvent = Event.EventTypeAsByte(EventType.PfcStormEndEvent); // update the watchdog state based on detection var conservativeDetectionTime = (ushort)(2 * detectionInterval); var conservativeRestorationTime = (ushort)(2 * restorationInterval); var isDetectionEvent1 = And( switchState.GetStormStartedTime1() > switchState.GetStormEndedTime1(), e.GetTimeStamp() - switchState.GetStormStartedTime1() >= conservativeDetectionTime); var isDetectionEvent2 = And( switchState.GetStormStartedTime2() > switchState.GetStormEndedTime2(), e.GetTimeStamp() - switchState.GetStormStartedTime2() >= conservativeDetectionTime); var isRestorationEvent1 = And( switchState.GetStormEndedTime1() > switchState.GetStormStartedTime1(), e.GetTimeStamp() - switchState.GetWatchdogStartDropTime1() >= conservativeRestorationTime); var isRestorationEvent2 = And( switchState.GetStormEndedTime2() > switchState.GetStormStartedTime2(), e.GetTimeStamp() - switchState.GetWatchdogStartDropTime2() >= conservativeRestorationTime); switchState = If(isRestorationEvent1, switchState.SetWatchdogDropPackets1(false), switchState); switchState = If(isRestorationEvent2, switchState.SetWatchdogDropPackets2(false), switchState); switchState = If(isDetectionEvent1, switchState.SetWatchdogStartDropTime1(e.GetTimeStamp()).SetWatchdogDropPackets1(true), switchState); switchState = If(isDetectionEvent2, switchState.SetWatchdogStartDropTime2(e.GetTimeStamp()).SetWatchdogDropPackets2(true), switchState); // update the watchdog state var isBurstOn1 = And(e.GetEventType() == burstEvent, e.GetPriorityClass() == 0); var isBurstOn2 = And(e.GetEventType() == burstEvent, e.GetPriorityClass() == 1); var stateBurst1 = switchState.AddPacket(Pair(e.GetTimeStamp(), Pair <byte, bool>(0, currentState.GetWatchdogDropPackets1()))); var stateBurst2 = switchState.AddPacket(Pair(e.GetTimeStamp(), Pair <byte, bool>(1, currentState.GetWatchdogDropPackets1()))); var isStormStartOn1 = And(e.GetEventType() == stormStartEvent, e.GetPriorityClass() == 0); var isStormStartOn2 = And(e.GetEventType() == stormStartEvent, e.GetPriorityClass() == 1); var stateStormStartOn1 = switchState.SetStormStartedTime1(e.GetTimeStamp()); var stateStormStartOn2 = switchState.SetStormStartedTime2(e.GetTimeStamp()); var isStormEndOn1 = And(e.GetEventType() == stormEndEvent, e.GetPriorityClass() == 0); var isStormEndOn2 = And(e.GetEventType() == stormEndEvent, e.GetPriorityClass() == 1); var stateStormEndOn1 = switchState.SetStormEndedTime1(e.GetTimeStamp()); var stateStormEndOn2 = switchState.SetStormEndedTime2(e.GetTimeStamp()); return(Cases(switchState, (isStormStartOn1, stateStormStartOn1), (isStormStartOn2, stateStormStartOn2), (isStormEndOn1, stateStormEndOn1), (isStormEndOn2, stateStormEndOn2), (isBurstOn1, stateBurst1), (isBurstOn2, stateBurst2))); }
private static Zen <TReturn> ApplyOrderedRules <TInput, TReturn, TRule>( Zen <TInput> input, Zen <TReturn> deflt, Func <TRule, Zen <TInput>, int, Zen <bool> > ruleMatch, Func <TRule, Zen <TInput>, int, Zen <TInput> > ruleAction, Func <TRule, Zen <TInput>, int, Zen <Option <TReturn> > > ruleReturn, TRule[] rules, int i) { if (i == rules.Length) { return(deflt); } var rule = rules[i]; // whether the current rule is a match var match = ruleMatch(rule, input, i + 1); // get the new value after modifications var modifiedInput = If(match, ruleAction(rule, input, i + 1), input); // whether or not we should return here var ret = ruleReturn(rule, modifiedInput, i + 1); var applyRest = ApplyOrderedRules(modifiedInput, deflt, ruleMatch, ruleAction, ruleReturn, rules, i + 1); return(If(And(match, ret.HasValue()), ret.Value(), applyRest)); }
/// <summary> /// Or operation of two Zen List of bool. /// </summary> /// <param name="ma">list a.</param> /// <param name="mb">list b.</param> /// <returns>list of a or b.</returns> public static Zen <IList <bool> > Or(this Zen <IList <bool> > ma, Zen <IList <bool> > mb) { var index = mb.Length(); var ret = ma.Select(_ => Language.Or(ma.At(index -= 1).Value(), mb.At(index).Value())); return(ret); }
/// <summary> /// Create label-ns mapping /// hash of label as key, 'bitvector' of ns as value. /// </summary> /// <param name="namespaces">all namespaces.</param> /// <returns>label-ns mapping.</returns> public static Zen <IDictionary <int, IList <bool> > > CreateNSLabelMatrix(Zen <Namespace>[] namespaces) { var n = namespaces.Length; Dictionary <int, bool[]> labelHash = new Dictionary <int, bool[]>(); for (int i = 0; i < n; ++i) { var keys = namespaces[i].GetLabelKeys(); var k = keys.Length(); // iterate over Zen<List> to traverse all keys for (k -= 1; !k.EqualToNumber(ushort.MaxValue); k -= 1) { var keyHash = keys.At(k).Value().GetHashCode(); if (!labelHash.ContainsKey(keyHash)) { labelHash[keyHash] = new bool[n]; } labelHash[keyHash][i] = true; } } // create zen data. Zen <IDictionary <int, IList <bool> > > mx = Language.EmptyDict <int, IList <bool> >(); foreach (var kv in labelHash) { mx = mx.Add(kv.Key, kv.Value); } return(mx); }
/// <summary> /// Find pods can only be reached from pods of same user. /// </summary> /// <param name="matrix">ingress reachability matrix.</param> /// <param name="userHashmap">user-pod mapping.</param> /// <param name="pods">all pods.</param> /// <param name="userKey">key of user label.</param> /// <returns>list of pods can only be reached from pods of same user.</returns> public static Zen <IList <ushort> > UserCrossCheck( Zen <IList <bool> >[] matrix, Zen <IDictionary <int, IList <bool> > > userHashmap, Zen <Pod>[] pods, Zen <string> userKey) { var n = pods.Length; Zen <IList <ushort> > podList = EmptyList <ushort>(); for (int i = 0; i < n; ++i) { var userString = pods[i].LabelValue(userKey); if (userString == null) { continue; } var veriSet = userHashmap.Get(userString.GetHashCode()).Value(); veriSet = veriSet.Not().And(matrix[i]); var c = If <ushort>(veriSet.All(r => r.Equals(False())), (ushort)i, ushort.MaxValue); // if this pod can only be reached from same user's pods, add it to list if (!c.EqualToNumber(ushort.MaxValue)) { podList = podList.AddBack(c); } } return(podList); }
/// <summary> /// Create a Zen packet from headers. /// </summary> /// <param name="overlayHeader">Overlay header.</param> /// <param name="underlayHeader">Underlay header.</param> /// <returns>Zen packet.</returns> public static Zen <Packet> Create( Zen <IpHeader> overlayHeader, Zen <Option <IpHeader> > underlayHeader) { return(Language.Create <Packet>( ("OverlayHeader", overlayHeader), ("UnderlayHeader", underlayHeader))); }
/// <summary> /// A pairwise invariant for a list of elements. /// </summary> /// <param name="list">The list.</param> /// <param name="f">The pairwise invariant.</param> /// <returns>A zen value for the invariant.</returns> internal static Zen <bool> PairwiseInvariant <T>(Zen <IList <T> > list, Func <Zen <T>, Zen <T>, Zen <bool> > f) { return(list.Case( empty: true, cons: (hd1, tl1) => tl1.Case( empty: true, cons: (hd2, tl2) => And(f(hd1, hd2), PairwiseInvariant(tl1, f))))); }
/// <summary> /// Get if this policy allows all traffic. /// </summary> /// <param name="policy">policy.</param> /// <returns>if it is an allow-all policy.</returns> public static bool GetAllowAll(this Zen <Policy> policy) { var labelKeys = policy.GetAllowKeys().Length(); var nsKeys = policy.GetAllowNSKeys().Length(); var denyAll = policy.GetDenyAll(); return(labelKeys.EqualToNumber(0) && nsKeys.EqualToNumber(0) && denyAll.Equals(False())); }
public void PolicyShadowTest() { Zen <Pod>[] pods = new Zen <Pod>[] { Pod.Create("default", EmptyDict <string, string>().Add("k0", "v0").Add("k1", "v1"), EmptyList <string>().AddBack("k0").AddBack("k1")), Pod.Create("default", EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1")), Pod.Create("ns1", EmptyDict <string, string>().Add("k2", "v2"), EmptyList <string>().AddBack("k2")), Pod.Create("ns1", EmptyDict <string, string>().Add("k3", "v3"), EmptyList <string>().AddBack("k3")) }; Zen <Namespace>[] namespaces = new Zen <Namespace>[] { Namespace.Create("default", EmptyDict <string, string>().Add("k0", "v0"), EmptyList <string>().AddBack("k0")), Namespace.Create("ns1", EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1")) }; Zen <Policy>[] policies = new Zen <Policy>[] { Policy.Create("default", EmptyDict <string, string>().Add("k0", "v0").Add("k1", "v1"), EmptyDict <string, string>().Add("k2", "v2"), EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k0").AddBack("k1"), EmptyList <string>().AddBack("k2"), EmptyList <string>().AddBack("k1")), Policy.Create("default", EmptyDict <string, string>().Add("k1", "v1"), EmptyDict <string, string>(), EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1"), EmptyList <string>(), EmptyList <string>().AddBack("k1")), Policy.Create("ns1", EmptyDict <string, string>().Add("k3", "v3"), EmptyDict <string, string>().Add("k2", "v2"), EmptyDict <string, string>().Add("k0", "v0"), EmptyList <string>().AddBack("k3"), EmptyList <string>().AddBack("k2"), EmptyList <string>().AddBack("k0")), }; var podPolMx = Algorithms.CreateReachMatrix(pods, policies, namespaces).podPolMatrix; var r0 = EmptyList <bool>().AddBack(true).AddBack(true).AddBack(false); var r1 = EmptyList <bool>().AddBack(false).AddBack(true).AddBack(false); var r2 = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(false); var r3 = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(true); TestHelper.AssertMatrixEqual(podPolMx, new Zen <IList <bool> >[] { r0, r1, r2, r3 }, "PolicyShadowTest: PodPolMatrix"); var polPodAllowedMx = Algorithms.CreateReachMatrix(pods, policies, namespaces).polPodAllowedMatrix; r0 = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(true).AddBack(false); r1 = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(true).AddBack(true); r2 = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(false).AddBack(false); TestHelper.AssertMatrixEqual(polPodAllowedMx, new Zen <IList <bool> >[] { r0, r1, r2 }, "PolicyShadowTest: PolPodAllowedMatrix"); var polPodSelectedMx = Algorithms.CreateReachMatrix(pods, policies, namespaces).polPodSelectedMatrix; r0 = EmptyList <bool>().AddBack(true).AddBack(false).AddBack(false).AddBack(false); r1 = EmptyList <bool>().AddBack(true).AddBack(true).AddBack(false).AddBack(false); r2 = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(false).AddBack(true); TestHelper.AssertMatrixEqual(polPodSelectedMx, new Zen <IList <bool> >[] { r0, r1, r2 }, "PolicyShadowTest: PolPodSelectedMatrix"); var shadowedPair = Verifier.PolicyShadowCheck(podPolMx, polPodAllowedMx, polPodSelectedMx); Assert.IsTrue(shadowedPair.Length().EqualToNumber(1)); var expected = EmptyList <Tuple <int, int> >().AddBack(Tuple <int, int>(1, 0)); Assert.IsTrue(shadowedPair.ToString().Equals(expected.ToString()), "PolicyShadowTest: shadow pairs are not correct.\nExpected: {0}\nGot: {1}", expected.ToString(), shadowedPair.ToString()); }
/// <summary> /// Create a model checker. /// </summary> /// <param name="backend">The backend to use.</param> /// <param name="expression">The expression to evaluate.</param> /// <returns>A new model checker.</returns> internal static IModelChecker CreateModelChecker(Backend backend, Zen <bool> expression) { if (backend == Backend.DecisionDiagrams) { return(CreateModelCheckerDD(expression)); } return(CreateModelCheckerZ3()); }
public static void Main() { Maruthi m = new Maruthi(); m = new Esteem(); //upcasting m.Display(); m = new Zen(); //upcasting m.Display(); }
/// <summary> /// Create a model checker based on decision diagrams. /// </summary> /// <param name="expression"></param> /// <returns></returns> private static IModelChecker CreateModelCheckerDD(Zen <bool> expression) { var heuristic = new InterleavingHeuristic(); var mustInterleave = heuristic.Compute(expression); var manager = new DDManager <BDDNode>(new BDDNodeFactory()); var solver = new SolverDD <BDDNode>(manager, mustInterleave); solver.Init(); return(new ModelChecker <Assignment <BDDNode>, Variable <BDDNode>, DD, BitVector <BDDNode>, Unit>(solver)); }
/// <summary> /// Match a packet with this acl. /// </summary> /// <param name="packet">The packet.</param> /// <returns>Whether accepted.</returns> public Zen <bool> Match(Zen <Packet> packet) { var dstIp = packet.GetDstIp(); var srcIp = packet.GetSrcIp(); return(And(dstIp >= this.DstIpLow, dstIp <= this.DstIpHigh, srcIp >= this.SrcIpLow, srcIp <= this.SrcIpHigh)); }
/// <summary> /// Match a packet and get the line number of the match. /// </summary> /// <param name="packet">The packet.</param> /// <returns>Whether accepting and the line number of the match.</returns> public Zen <Tuple <bool, ushort> > MatchProvenance(Zen <Packet> packet) { return(TestHelper.ApplyOrderedRules( input: packet, deflt: Tuple <bool, ushort>(false, this.Lines.Length + 1), ruleMatch: (l, pkt, i) => l.Match(pkt), ruleAction: (l, pkt, i) => pkt, ruleReturn: (l, pkt, i) => Some(Tuple <bool, ushort>(l.Permitted, i)), rules: this.Lines)); }
/// <summary> /// Apply a collection or rules in order. /// </summary> /// <typeparam name="TInput">Input type.</typeparam> /// <typeparam name="TReturn">Return type.</typeparam> /// <typeparam name="TRule">Rule type.</typeparam> /// <param name="input">Initial input.</param> /// <param name="deflt">Default return.</param> /// <param name="ruleMatch">Whether a rule matches.</param> /// <param name="ruleAction">What action to apply if a match.</param> /// <param name="ruleReturn">Whether and what to return at a rule.</param> /// <param name="rules">The collection of rules.</param> /// <returns></returns> public static Zen <TReturn> ApplyOrderedRules <TInput, TReturn, TRule>( Zen <TInput> input, Zen <TReturn> deflt, Func <TRule, Zen <TInput>, int, Zen <bool> > ruleMatch, Func <TRule, Zen <TInput>, int, Zen <TInput> > ruleAction, Func <TRule, Zen <TInput>, int, Zen <Option <TReturn> > > ruleReturn, TRule[] rules) { return(ApplyOrderedRules(input, deflt, ruleMatch, ruleAction, ruleReturn, rules, 0)); }
public Zen <Option <SimplePacket> > ForwardInAndOut(Zen <SimplePacket> p, Zen <Ip> nextHop) { Zen <bool> hasPath = False(); foreach (Route r in RoutingTable) { hasPath = Or(r.NextHop == nextHop, hasPath); } return(If(hasPath, Some(p), Null <SimplePacket>())); }
/// <summary> /// Checks if a given packet matches this rule. /// </summary> /// <param name="packet">The packet to test.</param> /// <returns>True if the packet matches; otherwise false.</returns> public Zen <bool> Matches(Zen <Packet> packet) { // TODO: If ports are zero, do NOT include in predicate (zero implies "ANY") return(And(packet.GetDstIp() >= this.DstIpLow, packet.GetDstIp() <= this.DstIpHigh, packet.GetDstPort() == this.DstPort, packet.GetSrcIp() >= this.SrcIpLow, packet.GetSrcIp() <= this.SrcIpHigh, packet.GetSrcPort() == this.SrcPort)); }
public Zen <Boolean> Forward(Zen <SimplePacket> p, Zen <IList <Tuple <int, int> > > failedLinks) { // path generation HashSet <List <int> > pathSet = new HashSet <List <int> >(); for (int i = 0; i < nodes.Count; i++) { for (int j = 0; j < nodes.Count; j++) { var nextHopIp = nodes[i].getNextHop(nodes[j].Address); if (nextHopIp.Value != GlobalVar.NULL_IP.Value) { // there is a route List <int> currRoute = new List <int>(); currRoute.Add(i); var currCost = 0; while (nextHopIp.Value != GlobalVar.NULL_IP.Value && nextHopIp.Value != nodes[j].Address.Value) { currRoute.Add((int)nextHopIp.Value); nextHopIp = nodes[(int)nextHopIp.Value].getNextHop(nodes[j].Address); currCost += 1; } currRoute.Add(j); if (currCost < this.maxCost && !currRoute.Contains((int)this.intermediateNode.Value)) { pathSet.Add(currRoute); // Console.WriteLine("Adding path " + nodes[i].Address + " " + nodes[j].Address); } } } } //var a = new List<int>() { 1, 2 }; //pathSet.Add(a); // forwarding w/ Zen Zen <Boolean> forwardSuccess = False(); foreach (List <int> path in pathSet) { var startNode = nodes[path[0]]; var endNode = nodes[path[path.Count - 1]]; forwardSuccess = If(And(p.GetSrcIp() == startNode.Address, p.GetDstIp() == endNode.Address), Forward(path.ToArray(), p, failedLinks).HasValue(), forwardSuccess); } //Console.WriteLine("Final Expression:"); //Console.WriteLine(forwardSuccess); //Console.WriteLine(); return(forwardSuccess); }
private Zen <LocatedPacket> StepMany(Zen <LocatedPacket> initial, int k) { if (k == 0) { return(initial); } var newLp = StepOnce(initial); return(If(newLp.HasValue(), StepMany(newLp.Value(), k - 1), initial)); }
private Zen <Option <LocatedPacket> > StepOnce(Zen <LocatedPacket> lp) { var location = lp.GetNode(); var packet = lp.GetHeader(); return(If(location == 0, Some(LocatedPacketHelper.Create(1, packet)), If(location == 1, Some(LocatedPacketHelper.Create(2, packet)), Null <LocatedPacket>()))); }
/// <summary> /// Process a header on an acl. /// </summary> /// <param name="hdr">The header.</param> /// <param name="i">The line number.</param> /// <returns>Whether permitted.</returns> public Zen <bool> Process(Zen <IpHeader> hdr, int i) { if (i == this.Lines.Length) { return(false); } var line = this.Lines[i]; return(If(line.Matches(hdr), line.Permitted, Process(hdr, i + 1))); }