[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n*.test\n*.prof\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: golang\n\ngo:\n  - 1.8.x\n  - 1.9.x\n  - 1.10.x\n  - 1.11.x\n\nscript:\n  - go test -v ./throttler/...\n"
  },
  {
    "path": "LICENSE",
    "content": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n"
  },
  {
    "path": "Makefile",
    "content": "BINARY=\"comcast\"\nVERSION=1.0.0\nBUILD=`date +%FT%T%z`\nDIR=bin\n\nPACKAGES=`go list ./... | grep -v /vendor/`\nVETPACKAGES=`go list ./... | grep -v /vendor/ | grep -v /examples/`\nGOFILES=`find . -name \"*.go\" -type f -not -path \"./vendor/*\"`\n\ndefault:\n\t@mkdir ${DIR}\n\t@go build -o ${DIR}/${BINARY} -tags=jsoniter\n\nlist:\n\t@echo ${PACKAGES}\n\t@echo ${VETPACKAGES}\n\t@echo ${GOFILES}\n\nfmt:\n\t@gofmt -s -w ${GOFILES}\n\nfmt-check:\n\t@diff=?(gofmt -s -d $(GOFILES)); \\\n\tif [ -n \"$$diff\" ]; then \\\n\t\techo \"Please run 'make fmt' and commit the result:\"; \\\n\t\techo \"$${diff}\"; \\\n\t\texit 1; \\\n\tfi;\n\ninstall:\n\t@govendor sync -v\n\ntest:\n\t@go test -cpu=1,2,4 -v -tags integration ./...\n\nvet:\n\t@go vet $(VETPACKAGES)\n\n\nclean:\n\t@if [ -f${DIR}/${BINARY} ] ; then rm -rf ${DIR} ; fi\n\n.PHONY: default fmt fmt-check install test vet docker clean\n\n\n"
  },
  {
    "path": "README.md",
    "content": "# Comcast\n\nTesting distributed systems under hard failures like network partitions and instance termination is critical, but it's also important we test them under [less catastrophic conditions](http://www.bravenewgeek.com/sometimes-kill-9-isnt-enough/) because this is what they most often experience. Comcast is a tool designed to simulate common network problems like latency, bandwidth restrictions, and dropped/reordered/corrupted packets.\n\nIt works by wrapping up some system tools in a portable(ish) way. On BSD-derived systems such as OSX, we use tools like `ipfw` and `pfctl` to inject failure. On Linux, we use `iptables` and `tc`. Comcast is merely a thin wrapper around these controls. Windows support may be possible with `wipfw` or even the native network stack, but this has not yet been implemented in Comcast and may be at a later date.\n\n## Installation\n\n```\n$ go install github.com/tylertreat/comcast@latest\n```\n\n### Path addition may be needed\n\nIn unix-like systems, after installing comcast with go, it may be needed to add it to the `PATH`. Go installs by default in `$HOME/go/bin`.\n```\n$ export PATH=$PATH:$HOME/go/bin\n```\n\n## Usage\n\nOn Linux, Comcast supports several options: device, latency, target/default bandwidth, packet loss, protocol, and port number.\n\n```\n$ comcast --device=eth0 --latency=250 --target-bw=1000 --default-bw=1000000 --packet-loss=10% --target-addr=8.8.8.8,10.0.0.0/24 --target-proto=tcp,udp,icmp --target-port=80,22,1000:2000\n```\n\nOn OSX, Comcast will check for `pfctl` support (as of Yosemite), which supports the same options as above. If `pfctl` is not available, it will use `ipfw` instead, which supports device, latency, target bandwidth, and packet-loss options.\n\nOn BSD (with `ipfw`), Comcast currently supports only: device, latency, target bandwidth, and packet loss. \n\n```\n$ comcast --device=eth0 --latency=250 --target-bw=1000 --packet-loss=10%\n```\n\nThis will add 250ms of latency, limit bandwidth to 1Mbps, and drop 10% of packets to the targetted (on Linux) destination addresses using the specified protocols on the specified port numbers (slow lane). The default bandwidth specified will apply to all egress traffic (fast lane). To turn this off, run the following:\n\n```\n$ comcast --stop\n```\n\nBy default, comcast will determine the system commands to execute, log them to stdout, and execute them. The `--dry-run` flag will skip execution.\n\n## I don't trust you, this code sucks, I hate Go, etc.\n\nIf you don't like running code that executes shell commands for you (despite it being open source, so you can read it and change the code) or want finer-grained control, you can run them directly instead. Read the man pages on these things for more details.\n\n### Linux\n\nOn Linux, you can use `iptables` to drop incoming and outgoing packets.\n\n```\n$ iptables -A INPUT -m statistic --mode random --probability 0.1 -j DROP\n$ iptables -A OUTPUT -m statistic --mode random --probability 0.1 -j DROP\n```\n\nAlternatively, you can use `tc` which supports some additional options.\n\n```\n$ tc qdisc add dev eth0 root netem delay 50ms 20ms distribution normal\n$ tc qdisc change dev eth0 root netem reorder 0.02 duplicate 0.05 corrupt 0.01\n```\n\nTo reset:\n\n```\n$ tc qdisc del dev eth0 root netem\n```\n\n### BSD/OSX\n\nTo shape traffic in BSD-derived systems, create an `ipfw` pipe and configure it. You can control incoming and outgoing traffic separately for any specific host or network.\n\n```\n$ ipfw add 1 pipe 1 ip from me to any\n$ ipfw add 2 pipe 1 ip from any to me\n$ ipfw pipe 1 config delay 500ms bw 1Mbit/s plr 0.1\n```\n\nTo reset:\n\n```\n$ ipfw delete 1\n```\n\n*Note: `ipfw` was removed in OSX Yosemite in favor of `pfctl`.*\n\n## Network Condition Profiles\n\nHere's a list of network conditions with values that you can plug into Comcast. Please add any more that you may come across.\n\nName | Latency | Bandwidth | Packet-loss\n:-- | --: | --: | --:\nGPRS (good) | 500 | 50 | 2\nEDGE (good) | 300 | 250 | 1.5\n3G/HSDPA (good) | 250 | 750 | 1.5\nDIAL-UP (good) | 185 | 40 | 2\nDSL (poor) | 70 | 2000 | 2\nDSL (good) | 40 | 8000 | 0.5\nWIFI (good) | 40 | 30000 | 0.2\nStarlink | 20 | - | 2.5\n"
  },
  {
    "path": "comcast.go",
    "content": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/tylertreat/comcast/throttler\"\n)\n\nconst version = \"1.0.0\"\n\nfunc main() {\n\t// TODO: Add support for other options like packet reordering, duplication, etc.\n\tvar (\n\t\tdevice      = flag.String(\"device\", \"\", \"Interface (device) to use (defaults to eth0 where applicable)\")\n\t\tstop        = flag.Bool(\"stop\", false, \"Stop packet controls\")\n\t\tlatency     = flag.Int(\"latency\", -1, \"Latency to add in ms\")\n\t\ttargetbw    = flag.Int(\"target-bw\", -1, \"Target bandwidth limit in kbit/s (slow-lane)\")\n\t\tdefaultbw   = flag.Int(\"default-bw\", -1, \"Default bandwidth limit in kbit/s (fast-lane)\")\n\t\tpacketLoss  = flag.String(\"packet-loss\", \"0\", \"Packet loss percentage (e.g. 0.1%)\")\n\t\ttargetaddr  = flag.String(\"target-addr\", \"\", \"Target addresses, (e.g. 10.0.0.1 or 10.0.0.0/24 or 10.0.0.1,192.168.0.0/24 or 2001:db8:a::123)\")\n\t\ttargetport  = flag.String(\"target-port\", \"\", \"Target port(s) (e.g. 80 or 1:65535 or 22,80,443,1000:1010)\")\n\t\ttargetproto = flag.String(\"target-proto\", \"tcp,udp,icmp\", \"Target protocol TCP/UDP (e.g. tcp or tcp,udp or icmp)\")\n\t\tdryrun      = flag.Bool(\"dry-run\", false, \"Specifies whether or not to actually commit the rule changes\")\n\t\t//icmptype  = flag.String(\"icmp-type\", \"\", \"icmp message type (e.g. reply or reply,request)\") //TODO: Maybe later :3\n\t\tvers = flag.Bool(\"version\", false, \"Print Comcast's version\")\n\t)\n\tflag.Parse()\n\n\tif *vers {\n\t\tfmt.Printf(\"Comcast version %s\\n\", version)\n\t\treturn\n\t}\n\n\ttargetIPv4, targetIPv6 := parseAddrs(*targetaddr)\n\n\tthrottler.Run(&throttler.Config{\n\t\tDevice:           *device,\n\t\tStop:             *stop,\n\t\tLatency:          *latency,\n\t\tTargetBandwidth:  *targetbw,\n\t\tDefaultBandwidth: *defaultbw,\n\t\tPacketLoss:       parseLoss(*packetLoss),\n\t\tTargetIps:        targetIPv4,\n\t\tTargetIps6:       targetIPv6,\n\t\tTargetPorts:      parsePorts(*targetport),\n\t\tTargetProtos:     parseProtos(*targetproto),\n\t\tDryRun:           *dryrun,\n\t})\n}\n\nfunc parseLoss(loss string) float64 {\n\tval := loss\n\tif strings.Contains(loss, \"%\") {\n\t\tval = loss[:len(loss)-1]\n\t}\n\tl, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\tfmt.Println(\"Incorrectly specified packet loss:\", loss)\n\t\tos.Exit(1)\n\t}\n\treturn l\n}\n\nfunc parseAddrs(addrs string) ([]string, []string) {\n\tadrs := strings.Split(addrs, \",\")\n\tparsedIPv4 := []string{}\n\tparsedIPv6 := []string{}\n\n\tif addrs != \"\" {\n\t\tfor _, adr := range adrs {\n\t\t\tip := net.ParseIP(adr)\n\t\t\tif ip != nil {\n\t\t\t\tif ip.To4() != nil {\n\t\t\t\t\tparsedIPv4 = append(parsedIPv4, adr)\n\t\t\t\t} else {\n\t\t\t\t\tparsedIPv6 = append(parsedIPv6, adr)\n\t\t\t\t}\n\t\t\t} else { //Not a valid single IP, could it be a CIDR?\n\t\t\t\tparsedIP, net, err := net.ParseCIDR(adr)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif parsedIP.To4() != nil {\n\t\t\t\t\t\tparsedIPv4 = append(parsedIPv4, net.String())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparsedIPv6 = append(parsedIPv6, net.String())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Incorrectly specified target IP or CIDR:\", adr)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parsedIPv4, parsedIPv6\n}\n\nfunc parsePorts(ports string) []string {\n\tprts := strings.Split(ports, \",\")\n\tparsed := []string{}\n\n\tif ports != \"\" {\n\t\tfor _, prt := range prts {\n\t\t\tif strings.Contains(prt, \":\") {\n\t\t\t\tif validRange(prt) {\n\t\t\t\t\tparsed = append(parsed, prt)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Incorrectly specified port range:\", prt)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t} else { //Isn't a range, check if just a single port\n\t\t\t\tif validPort(prt) {\n\t\t\t\t\tparsed = append(parsed, prt)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Incorrectly specified port:\", prt)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parsed\n}\n\nfunc parsePort(port string) int {\n\tprt, err := strconv.Atoi(port)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn prt\n}\n\nfunc validPort(port string) bool {\n\tprt := parsePort(port)\n\treturn prt > 0 && prt < 65536\n}\n\nfunc validRange(ports string) bool {\n\tpr := strings.Split(ports, \":\")\n\n\tif len(pr) == 2 {\n\t\tif !validPort(pr[0]) || !validPort(pr[1]) {\n\t\t\treturn false\n\t\t}\n\n\t\tif portHigher(pr[0], pr[1]) {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc portHigher(prt1, prt2 string) bool {\n\tp1 := parsePort(prt1)\n\tp2 := parsePort(prt2)\n\n\treturn p1 > p2\n}\n\nfunc parseProtos(protos string) []string {\n\tptcs := strings.Split(protos, \",\")\n\tparsed := []string{}\n\n\tif protos != \"\" {\n\t\tfor _, ptc := range ptcs {\n\t\t\tp := strings.ToLower(ptc)\n\t\t\tif p == \"udp\" ||\n\t\t\t\tp == \"tcp\" ||\n\t\t\t\tp == \"icmp\" {\n\t\t\t\tparsed = append(parsed, p)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Incorrectly specified protocol:\", p)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parsed\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/tylertreat/comcast\n\ngo 1.15\n\nrequire github.com/tylertreat/comcast v1.0.1\n"
  },
  {
    "path": "throttler/ipfw.go",
    "content": "package throttler\n\nimport (\n\t\"strconv\"\n)\n\nconst (\n\tipfwAddPipe  = `sudo ipfw add 1 pipe 1 ip from any to any via `\n\tipfwTeardown = `sudo ipfw delete 1`\n\tipfwConfig   = `sudo ipfw pipe 1 config`\n\tipfwExists   = `sudo ipfw list | grep \"pipe 1\"`\n\tipfwCheck    = `sudo ipfw list`\n)\n\ntype ipfwThrottler struct {\n\tc commander\n}\n\nfunc (i *ipfwThrottler) setup(c *Config) error {\n\tcmd := ipfwAddPipe + c.Device\n\terr := i.c.execute(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfigCmd := i.buildConfigCommand(c)\n\terr = i.c.execute(configCmd)\n\treturn err\n}\n\nfunc (i *ipfwThrottler) teardown(_ *Config) error {\n\terr := i.c.execute(ipfwTeardown)\n\treturn err\n}\n\nfunc (i *ipfwThrottler) exists() bool {\n\tif dry {\n\t\treturn false\n\t}\n\terr := i.c.execute(ipfwExists)\n\treturn err == nil\n}\n\nfunc (i *ipfwThrottler) check() string {\n\treturn ipfwCheck\n}\n\nfunc (i *ipfwThrottler) buildConfigCommand(c *Config) string {\n\tcmd := ipfwConfig\n\n\tif c.Latency > 0 {\n\t\tcmd = cmd + \" delay \" + strconv.Itoa(c.Latency) + \"ms\"\n\t}\n\n\tif c.TargetBandwidth > 0 {\n\t\tcmd = cmd + \" bw \" + strconv.Itoa(c.TargetBandwidth) + \"Kbit/s\"\n\t}\n\n\tif c.PacketLoss > 0 {\n\t\tcmd = cmd + \" plr \" + strconv.FormatFloat(c.PacketLoss/100, 'f', 4, 64)\n\t}\n\n\treturn cmd\n}\n"
  },
  {
    "path": "throttler/pfctl.go",
    "content": "package throttler\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t// TODO: use printf in favour of echo due to shell portability issues\n\tpfctlCreateAnchor    = `(cat /etc/pf.conf && echo \"dummynet-anchor \\\"mop\\\"\" && echo \"anchor \\\"mop\\\"\") | sudo pfctl -f -`\n\tpfctlTeardown        = `sudo pfctl -f /etc/pf.conf`\n\tdnctl                = `sudo dnctl pipe 1 config`\n\tpfctlCreateDummynet  = `echo $'dummynet in on %s all pipe 1'`\n\tpfctlExecuteInline   = `%s | sudo pfctl -a mop -f - `\n\tpfctlEnableFirewall  = `sudo pfctl -E`\n\tpfctlEnableFwRegex   = `pf enabled`\n\tpfctlDisableFirewall = `sudo pfctl -d`\n\tpfctlDisbleFwRegex   = `pf disabled`\n\tpfctlIsEnabled       = `sudo pfctl -sa | grep -i enabled`\n\tdnctlIsConfigured    = `sudo dnctl show`\n\tpfctlIsEnabledRegex  = `Enabled`\n\tdnctlTeardown        = `sudo dnctl -q flush`\n)\n\ntype pfctlThrottler struct {\n\tc commander\n}\n\n// Execute a command and check that any matching line in the result contains 'match'\nfunc (i *pfctlThrottler) executeAndParse(cmd string, match string) bool {\n\tlines, err := i.c.executeGetLines(cmd)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfor _, line := range lines {\n\t\tif strings.Contains(line, match) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (i *pfctlThrottler) setup(c *Config) error {\n\t// Enable firewall\n\terr := i.c.execute(pfctlEnableFirewall)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not enable firewall using: `%s`. Error: %s\", pfctlEnableFirewall, err.Error())\n\t}\n\n\t// Add the dummynet and anchor\n\terr = i.c.execute(pfctlCreateAnchor)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not create anchor rule for dummynet using: `%s`. Error: %s\", pfctlCreateAnchor, err.Error())\n\t}\n\n\t// Add 'execute' portion of the command\n\tinput := fmt.Sprintf(pfctlCreateDummynet, c.Device)\n\tcmd := fmt.Sprintf(pfctlExecuteInline, input)\n\n\terr = i.c.execute(cmd)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not create dummynet using: `%s`. Error: %s\", input, err.Error())\n\t}\n\n\t// Apply the shaping etc.\n\tfor _, cmd := range i.buildConfigCommand(c) {\n\t\terr = i.c.execute(cmd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (i *pfctlThrottler) teardown(_ *Config) error {\n\n\t// Reset firewall rules, leave it running\n\terr := i.c.execute(pfctlTeardown)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not remove firewall rules using: `%s`. Error: %s\", pfctlTeardown, err.Error())\n\t}\n\n\t// Turn off the firewall, discarding any rules\n\terr = i.c.execute(pfctlDisableFirewall)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not disable firewall using: `%s`. Error: %s\", pfctlDisableFirewall, err.Error())\n\t}\n\n\t// Disable dnctl rules\n\terr = i.c.execute(dnctlTeardown)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not disable dnctl rules using: `%s`. Error: %s\", dnctlTeardown, err.Error())\n\t}\n\n\treturn nil\n}\n\nfunc (i *pfctlThrottler) isFirewallRunning() bool {\n\treturn i.executeAndParse(pfctlIsEnabled, pfctlIsEnabledRegex)\n}\nfunc (i *pfctlThrottler) exists() bool {\n\tif dry {\n\t\treturn false\n\t}\n\treturn i.executeAndParse(dnctlIsConfigured, \"port\") || i.isFirewallRunning()\n}\n\nfunc (i *pfctlThrottler) check() string {\n\treturn pfctlIsEnabled\n}\n\nfunc addProtosToCommands(cmds []string, protos []string) []string {\n\tcommands := make([]string, 0)\n\n\tfor _, cmd := range cmds {\n\t\tfor _, proto := range protos {\n\t\t\tcommands = append(commands, fmt.Sprintf(\"%s proto %s\", cmd, proto))\n\t\t}\n\t}\n\n\treturn commands\n}\nfunc addPortsToCommand(cmd string, ports []string) []string {\n\tcommands := make([]string, 0)\n\n\tfor _, port := range ports {\n\t\tcommands = append(commands, fmt.Sprintf(\"%s dst-port %s\", cmd, port))\n\t\tcommands = append(commands, fmt.Sprintf(\"%s src-port %s\", cmd, port))\n\t}\n\n\treturn commands\n}\n\n// Takes care of the annoying differences between ipv4 and ipv6\nfunc addIpsAndProtoToCommands(ipVersion int, cmds []string, ips []string, protos []string) []string {\n\n\tcommands := make([]string, 0)\n\n\tfor _, cmd := range cmds {\n\t\tfor _, ip := range ips {\n\t\t\tsrcIpFlag := \"src-ip\"\n\t\t\tdstIpFlag := \"dst-ip\"\n\t\t\tif ipVersion == 6 {\n\t\t\t\tsrcIpFlag = \"src-ip6\"\n\t\t\t\tdstIpFlag = \"dst-ip6\"\n\t\t\t}\n\n\t\t\tcommands = append(commands, addProtoToCommands(ipVersion, fmt.Sprintf(\"%s %s %s\", cmd, srcIpFlag, ip), protos)...)\n\t\t\tcommands = append(commands, addProtoToCommands(ipVersion, fmt.Sprintf(\"%s %s %s\", cmd, dstIpFlag, ip), protos)...)\n\t\t}\n\t}\n\n\treturn commands\n}\n\nfunc addProtoToCommands(ipVersion int, cmd string, protos []string) []string {\n\tcommands := make([]string, 0)\n\tfor _, proto := range protos {\n\t\tif ipVersion == 6 {\n\t\t\tif proto == \"icmp\" {\n\t\t\t\tproto = \"ipv6-icmp\"\n\t\t\t}\n\t\t}\n\t\tcommands = append(commands, fmt.Sprintf(\"%s proto %s\", cmd, proto))\n\t}\n\treturn commands\n}\n\nfunc (i *pfctlThrottler) buildConfigCommand(c *Config) []string {\n\n\tcmd := dnctl\n\n\t// Add all non tcp version dependent stuff first...\n\tif c.Latency > 0 {\n\t\tcmd = cmd + \" delay \" + strconv.Itoa(c.Latency) + \"ms\"\n\t}\n\n\tif c.TargetBandwidth > 0 {\n\t\tcmd = cmd + \" bw \" + strconv.Itoa(c.TargetBandwidth) + \"Kbit/s\"\n\t}\n\n\tif c.PacketLoss > 0 {\n\t\tcmd = cmd + \" plr \" + strconv.FormatFloat(c.PacketLoss/100, 'f', 4, 64)\n\t}\n\n\t// Add Mask keyword if we have pipe qualifiers\n\tif len(c.TargetPorts) > 0 || len(c.TargetProtos) > 0 || len(c.TargetIps) > 0 || len(c.TargetIps6) > 0 {\n\t\tcmd = cmd + \" mask \"\n\t}\n\n\t// Expand commands with ports\n\tcommands := []string{cmd}\n\n\tif len(c.TargetPorts) > 0 {\n\t\tcommands = addPortsToCommand(cmd, c.TargetPorts)\n\t}\n\n\tif len(c.TargetIps) == 0 && len(c.TargetIps6) == 0 {\n\t\tif len(c.TargetProtos) > 0 {\n\t\t\treturn addProtosToCommands(commands, c.TargetProtos)\n\t\t}\n\t\treturn commands\n\t}\n\n\t// create and combine the ipv4 and ipv6 IPs with the protocol version specific keywords\n\treturn append(addIpsAndProtoToCommands(4, commands, c.TargetIps, c.TargetProtos), addIpsAndProtoToCommands(6, commands, c.TargetIps6, c.TargetProtos)...)\n}\n"
  },
  {
    "path": "throttler/pfctl_test.go",
    "content": "package throttler\n\nimport (\n\t\"testing\"\n)\n\nfunc TestPfctlDefaultConfigCommand(t *testing.T) {\n\n\tr := newCmdRecorder()\n\tth := &pfctlThrottler{r}\n\tc := defaultTestConfig\n\tc.PacketLoss = 0\n\tc.TargetIps = []string{}\n\tc.TargetIps6 = []string{}\n\tc.TargetBandwidth = -1\n\tc.TargetPorts = []string{}\n\tc.TargetProtos = []string{\"tcp,udp,icmp\"}\n\n\tth.setup(&c)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo pfctl -E\",\n\t\t`(cat /etc/pf.conf && echo \"dummynet-anchor \\\"mop\\\"\" && echo \"anchor \\\"mop\\\"\") | sudo pfctl -f -`,\n\t\t`echo $'dummynet in all pipe 1' | sudo pfctl -a mop -f - `,\n\t\t`sudo dnctl pipe 1 config mask  proto tcp,udp,icmp`,\n\t})\n}\n\nfunc TestPfctlThrottleOnlyConfigCommand(t *testing.T) {\n\n\tvar c = Config{\n\t\tDevice:           \"eth0\",\n\t\tStop:             false,\n\t\tLatency:          -1,\n\t\tTargetBandwidth:  -1,\n\t\tDefaultBandwidth: 20000,\n\t\tPacketLoss:       0.1,\n\t}\n\tr := newCmdRecorder()\n\tth := &pfctlThrottler{r}\n\n\tth.setup(&c)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo pfctl -E\",\n\t\t`(cat /etc/pf.conf && echo \"dummynet-anchor \\\"mop\\\"\" && echo \"anchor \\\"mop\\\"\") | sudo pfctl -f -`,\n\t\t`echo $'dummynet in all pipe 1' | sudo pfctl -a mop -f - `,\n\t\t`sudo dnctl pipe 1 config plr 0.0010`,\n\t})\n}\nfunc TestPfctlNoIPThrottleConfigCommand(t *testing.T) {\n\n\tvar c = Config{\n\t\tDevice:           \"eth0\",\n\t\tStop:             false,\n\t\tLatency:          -1,\n\t\tTargetBandwidth:  -1,\n\t\tDefaultBandwidth: 20000,\n\t\tPacketLoss:       0.1,\n\t\tTargetProtos:     []string{\"tcp\"},\n\t}\n\tr := newCmdRecorder()\n\tth := &pfctlThrottler{r}\n\n\tth.setup(&c)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo pfctl -E\",\n\t\t`(cat /etc/pf.conf && echo \"dummynet-anchor \\\"mop\\\"\" && echo \"anchor \\\"mop\\\"\") | sudo pfctl -f -`,\n\t\t`echo $'dummynet in all pipe 1' | sudo pfctl -a mop -f - `,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  proto tcp`,\n\t})\n}\n\nfunc TestPfctlPacketSetup(t *testing.T) {\n\n\tr := newCmdRecorder()\n\tth := &pfctlThrottler{r}\n\tc := defaultTestConfig\n\tc.PacketLoss = 0.5\n\n\tth.setup(&c)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo pfctl -E\",\n\t\t`(cat /etc/pf.conf && echo \"dummynet-anchor \\\"mop\\\"\" && echo \"anchor \\\"mop\\\"\") | sudo pfctl -f -`,\n\t\t`echo $'dummynet in all pipe 1' | sudo pfctl -a mop -f - `,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  dst-port 80 src-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  dst-port 80 dst-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  src-port 80 src-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  src-port 80 dst-ip 10.10.10.10 proto tcp`,\n\t})\n}\n\nfunc TestPfctlProtoSetup(t *testing.T) {\n\n\tr := newCmdRecorder()\n\tth := &pfctlThrottler{r}\n\tc := defaultTestConfig\n\tc.PacketLoss = 0.5\n\tc.TargetProtos = []string{\"tcp\", \"udp\", \"icmp\"}\n\n\tth.setup(&c)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo pfctl -E\",\n\t\t`(cat /etc/pf.conf && echo \"dummynet-anchor \\\"mop\\\"\" && echo \"anchor \\\"mop\\\"\") | sudo pfctl -f -`,\n\t\t`echo $'dummynet in all pipe 1' | sudo pfctl -a mop -f - `,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  dst-port 80 src-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  dst-port 80 src-ip 10.10.10.10 proto udp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  dst-port 80 src-ip 10.10.10.10 proto icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  dst-port 80 dst-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  dst-port 80 dst-ip 10.10.10.10 proto udp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  dst-port 80 dst-ip 10.10.10.10 proto icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  src-port 80 src-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  src-port 80 src-ip 10.10.10.10 proto udp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  src-port 80 src-ip 10.10.10.10 proto icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  src-port 80 dst-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  src-port 80 dst-ip 10.10.10.10 proto udp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0050 mask  src-port 80 dst-ip 10.10.10.10 proto icmp`,\n\t})\n}\n\nfunc TestPfctlMultiplePortsAndIps(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &pfctlThrottler{r}\n\tcfg := defaultTestConfig\n\tcfg.TargetIps = []string{\"1.1.1.1\", \"2.2.2.2\"}\n\tcfg.TargetPorts = []string{\"80\", \"8080\"}\n\tcfg.TargetProtos = []string{\"tcp\"}\n\tth.setup(&cfg)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo pfctl -E\",\n\t\t`(cat /etc/pf.conf && echo \"dummynet-anchor \\\"mop\\\"\" && echo \"anchor \\\"mop\\\"\") | sudo pfctl -f -`,\n\t\t`echo $'dummynet in all pipe 1' | sudo pfctl -a mop -f - `,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  dst-port 80 src-ip 1.1.1.1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  dst-port 80 dst-ip 1.1.1.1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  dst-port 80 src-ip 2.2.2.2 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  dst-port 80 dst-ip 2.2.2.2 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  src-port 80 src-ip 1.1.1.1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  src-port 80 dst-ip 1.1.1.1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  src-port 80 src-ip 2.2.2.2 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  src-port 80 dst-ip 2.2.2.2 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  dst-port 8080 src-ip 1.1.1.1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  dst-port 8080 dst-ip 1.1.1.1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  dst-port 8080 src-ip 2.2.2.2 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  dst-port 8080 dst-ip 2.2.2.2 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  src-port 8080 src-ip 1.1.1.1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  src-port 8080 dst-ip 1.1.1.1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  src-port 8080 src-ip 2.2.2.2 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0010 mask  src-port 8080 dst-ip 2.2.2.2 proto tcp`,\n\t})\n}\n\nfunc TestPfctlMixedIPv6Setup(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &pfctlThrottler{r}\n\tcfg := defaultTestConfig\n\tcfg.TargetProtos = []string{\"icmp\", \"tcp\"}\n\tcfg.PacketLoss = 0.2\n\tcfg.TargetIps6 = []string{\"2001:db8::1\"}\n\tth.setup(&cfg)\n\tr.verifyCommands(t, []string{\n\t\t`sudo pfctl -E`,\n\t\t`(cat /etc/pf.conf && echo \"dummynet-anchor \\\"mop\\\"\" && echo \"anchor \\\"mop\\\"\") | sudo pfctl -f -`,\n\t\t`echo $'dummynet in all pipe 1' | sudo pfctl -a mop -f - `,\n\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  dst-port 80 src-ip 10.10.10.10 proto icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  dst-port 80 src-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  dst-port 80 dst-ip 10.10.10.10 proto icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  dst-port 80 dst-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  src-port 80 src-ip 10.10.10.10 proto icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  src-port 80 src-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  src-port 80 dst-ip 10.10.10.10 proto icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  src-port 80 dst-ip 10.10.10.10 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  dst-port 80 src-ip6 2001:db8::1 proto ipv6-icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  dst-port 80 src-ip6 2001:db8::1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  dst-port 80 dst-ip6 2001:db8::1 proto ipv6-icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  dst-port 80 dst-ip6 2001:db8::1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  src-port 80 src-ip6 2001:db8::1 proto ipv6-icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  src-port 80 src-ip6 2001:db8::1 proto tcp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  src-port 80 dst-ip6 2001:db8::1 proto ipv6-icmp`,\n\t\t`sudo dnctl pipe 1 config plr 0.0020 mask  src-port 80 dst-ip6 2001:db8::1 proto tcp`,\n\t})\n}\n"
  },
  {
    "path": "throttler/tc.go",
    "content": "package throttler\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nconst (\n\ttcRootQDisc    = `dev %s handle 10: root`\n\ttcRootExtra    = `default 1`\n\ttcDefaultClass = `dev %s parent 10: classid 10:1`\n\ttcTargetClass  = `dev %s parent 10: classid 10:10`\n\ttcNetemRule    = `dev %s parent 10:10 handle 100:`\n\ttcRate         = `rate %vkbit`\n\ttcDelay        = `delay %vms`\n\ttcLoss         = `loss %v%%`\n\ttcAddClass     = `sudo tc class add`\n\ttcDelClass     = `sudo tc class del`\n\ttcAddQDisc     = `sudo tc qdisc add`\n\ttcDelQDisc     = `sudo tc qdisc del`\n\tiptAddTarget   = `sudo %s -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10`\n\tiptDelTarget   = `sudo %s -D POSTROUTING -t mangle -j CLASSIFY --set-class 10:10`\n\tiptDestIP      = `-d %s`\n\tiptProto       = `-p %s`\n\tiptDestPorts   = `--match multiport --dports %s`\n\tiptDestPort    = `--dport %s`\n\tiptDelSearch   = `class 0010:0010`\n\tiptList        = `sudo %s -S -t mangle`\n\tip4Tables      = `iptables`\n\tip6Tables      = `ip6tables`\n\tiptDel         = `sudo %s -t mangle -D`\n\ttcExists       = `sudo tc qdisc show | grep \"netem\"`\n\ttcCheck        = `sudo tc -s qdisc`\n)\n\ntype tcThrottler struct {\n\tc commander\n}\n\nfunc (t *tcThrottler) setup(cfg *Config) error {\n\terr := addRootQDisc(cfg, t.c) //The root node to append the filters\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addDefaultClass(cfg, t.c) //The default class for all traffic that isn't classified\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addTargetClass(cfg, t.c) //The class that the network emulator rule is assigned\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addNetemRule(cfg, t.c) //The network emulator rule that contains the desired behavior\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn addIptablesRules(cfg, t.c) //The network emulator rule that contains the desired behavior\n}\n\nfunc addRootQDisc(cfg *Config, c commander) error {\n\t//Add the root QDisc\n\troot := fmt.Sprintf(tcRootQDisc, cfg.Device)\n\tstrs := []string{tcAddQDisc, root, \"htb\", tcRootExtra}\n\tcmd := strings.Join(strs, \" \")\n\n\treturn c.execute(cmd)\n}\n\nfunc addDefaultClass(cfg *Config, c commander) error {\n\t//Add the default Class\n\tdef := fmt.Sprintf(tcDefaultClass, cfg.Device)\n\trate := \"\"\n\n\tif cfg.DefaultBandwidth > 0 {\n\t\trate = fmt.Sprintf(tcRate, cfg.DefaultBandwidth)\n\t} else {\n\t\trate = fmt.Sprintf(tcRate, 1000000)\n\t}\n\n\tstrs := []string{tcAddClass, def, \"htb\", rate}\n\tcmd := strings.Join(strs, \" \")\n\n\treturn c.execute(cmd)\n}\n\nfunc addTargetClass(cfg *Config, c commander) error {\n\t//Add the target Class\n\ttar := fmt.Sprintf(tcTargetClass, cfg.Device)\n\trate := \"\"\n\n\tif cfg.TargetBandwidth > -1 {\n\t\trate = fmt.Sprintf(tcRate, cfg.TargetBandwidth)\n\t} else {\n\t\trate = fmt.Sprintf(tcRate, 1000000)\n\t}\n\n\tstrs := []string{tcAddClass, tar, \"htb\", rate}\n\tcmd := strings.Join(strs, \" \")\n\n\treturn c.execute(cmd)\n}\n\nfunc addNetemRule(cfg *Config, c commander) error {\n\t//Add the Network Emulator rule\n\tnet := fmt.Sprintf(tcNetemRule, cfg.Device)\n\tstrs := []string{tcAddQDisc, net, \"netem\"}\n\n\tif cfg.Latency > 0 {\n\t\tstrs = append(strs, fmt.Sprintf(tcDelay, cfg.Latency))\n\t}\n\n\tif cfg.TargetBandwidth > -1 {\n\t\tstrs = append(strs, fmt.Sprintf(tcRate, cfg.TargetBandwidth))\n\t}\n\n\tif cfg.PacketLoss > 0 {\n\t\tstrs = append(strs, fmt.Sprintf(tcLoss, strconv.FormatFloat(cfg.PacketLoss, 'f', 2, 64)))\n\t}\n\n\tcmd := strings.Join(strs, \" \")\n\n\treturn c.execute(cmd)\n}\n\nfunc addIptablesRules(cfg *Config, c commander) error {\n\tvar err error\n\tif len(cfg.TargetIps) == 0 && len(cfg.TargetIps6) == 0 {\n\t\tif err == nil {\n\t\t\terr = addIptablesRulesForAddrs(cfg, c, ip4Tables, cfg.TargetIps)\n\t\t}\n\t\tif err == nil {\n\t\t\terr = addIptablesRulesForAddrs(cfg, c, ip6Tables, cfg.TargetIps6)\n\t\t}\n\t\treturn err\n\t}\n\tif err == nil && len(cfg.TargetIps) > 0 {\n\t\terr = addIptablesRulesForAddrs(cfg, c, ip4Tables, cfg.TargetIps)\n\t}\n\tif err == nil && len(cfg.TargetIps6) > 0 {\n\t\terr = addIptablesRulesForAddrs(cfg, c, ip6Tables, cfg.TargetIps6)\n\t}\n\treturn err\n}\n\nfunc addIptablesRulesForAddrs(cfg *Config, c commander, command string, addrs []string) error {\n\trules := []string{}\n\tports := \"\"\n\n\tif len(cfg.TargetPorts) > 0 {\n\t\tif len(cfg.TargetPorts) > 1 {\n\t\t\tprts := strings.Join(cfg.TargetPorts, \",\")\n\t\t\tports = fmt.Sprintf(iptDestPorts, prts)\n\t\t} else {\n\t\t\tports = fmt.Sprintf(iptDestPort, cfg.TargetPorts[0])\n\t\t}\n\t}\n\n\taddTargetCmd := fmt.Sprintf(iptAddTarget, command)\n\n\tif len(cfg.TargetProtos) > 0 {\n\t\tfor _, ptc := range cfg.TargetProtos {\n\t\t\tproto := fmt.Sprintf(iptProto, ptc)\n\t\t\trule := addTargetCmd + \" \" + proto\n\n\t\t\tif ptc != \"icmp\" {\n\t\t\t\tif ports != \"\" {\n\t\t\t\t\trule += \" \" + ports\n\t\t\t\t}\n\t\t\t}\n\n\t\t\trules = append(rules, rule)\n\t\t}\n\t} else {\n\t\trules = []string{addTargetCmd}\n\t}\n\n\tif len(addrs) > 0 {\n\t\tiprules := []string{}\n\t\tfor _, ip := range addrs {\n\t\t\tdest := fmt.Sprintf(iptDestIP, ip)\n\t\t\tif len(rules) > 0 {\n\t\t\t\tfor _, rule := range rules {\n\t\t\t\t\tr := rule + \" \" + dest\n\t\t\t\t\tiprules = append(iprules, r)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tiprules = append(iprules, dest)\n\t\t\t}\n\t\t}\n\t\tif len(iprules) > 0 {\n\t\t\trules = iprules\n\t\t}\n\t}\n\n\tfor _, rule := range rules {\n\t\tif err := c.execute(rule); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (t *tcThrottler) teardown(cfg *Config) error {\n\tif err := delIptablesRules(cfg, t.c); err != nil {\n\t\treturn err\n\t}\n\n\t// The root node to append the filters\n\tif err := delRootQDisc(cfg, t.c); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc delIptablesRules(cfg *Config, c commander) error {\n\tiptablesCommands := []string{ip4Tables, ip6Tables}\n\n\tfor _, iptablesCommand := range iptablesCommands {\n\t\tif !c.commandExists(iptablesCommand) {\n\t\t\tcontinue\n\t\t}\n\t\tlines, err := c.executeGetLines(fmt.Sprintf(iptList, iptablesCommand))\n\t\tif err != nil {\n\t\t\t// ignore exit code 3 from iptables, which might happen if the system\n\t\t\t// has the ip6tables command, but no IPv6 capabilities\n\t\t\twerr, ok := err.(*exec.ExitError)\n\t\t\tif !ok {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstatus, ok := werr.Sys().(syscall.WaitStatus)\n\t\t\tif !ok {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif status.ExitStatus() == 3 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tdelCmdPrefix := fmt.Sprintf(iptDel, iptablesCommand)\n\n\t\tfor _, line := range lines {\n\t\t\tif strings.Contains(line, iptDelSearch) {\n\t\t\t\tcmd := strings.Replace(line, \"-A\", delCmdPrefix, 1)\n\t\t\t\terr = c.execute(cmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc delRootQDisc(cfg *Config, c commander) error {\n\t//Delete the root QDisc\n\troot := fmt.Sprintf(tcRootQDisc, cfg.Device)\n\n\tstrs := []string{tcDelQDisc, root}\n\tcmd := strings.Join(strs, \" \")\n\n\treturn c.execute(cmd)\n}\n\nfunc (t *tcThrottler) exists() bool {\n\tif dry {\n\t\treturn false\n\t}\n\terr := t.c.execute(tcExists)\n\treturn err == nil\n}\n\nfunc (t *tcThrottler) check() string {\n\treturn tcCheck\n}\n"
  },
  {
    "path": "throttler/tc_test.go",
    "content": "package throttler\n\nimport (\n\t\"testing\"\n)\n\ntype cmdRecorder struct {\n\tcommands     []string\n\tresponses    map[string][]string\n\tcmdBlackList []string\n}\n\nfunc newCmdRecorder() *cmdRecorder {\n\treturn &cmdRecorder{[]string{}, map[string][]string{}, []string{}}\n}\n\nfunc (r *cmdRecorder) execute(cmd string) error {\n\tr.commands = append(r.commands, cmd)\n\treturn nil\n}\n\nfunc (r *cmdRecorder) executeGetLines(cmd string) ([]string, error) {\n\tr.execute(cmd)\n\tif responses, found := r.responses[cmd]; found {\n\t\treturn responses, nil\n\t}\n\treturn []string{}, nil\n}\n\nfunc (r *cmdRecorder) commandExists(cmd string) bool {\n\tfor _, blackListed := range r.cmdBlackList {\n\t\tif blackListed == cmd {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (r *cmdRecorder) verifyCommands(t *testing.T, expected []string) {\n\tif len(expected) != len(r.commands) {\n\t\tfor i, cmd := range expected {\n\t\t\tt.Logf(\"Expected (%d): %s\", i, cmd)\n\t\t}\n\t\tfor i, cmd := range r.commands {\n\t\t\tt.Logf(\"Actual   (%d): %s\", i, cmd)\n\t\t}\n\n\t\tt.Fatalf(\"Expected to see %d commands, got %d\", len(expected), len(r.commands))\n\t}\n\n\tfor i, cmd := range expected {\n\t\tif actual := r.commands[i]; actual != cmd {\n\t\t\tt.Fatalf(\"Expected to see command `%s`, got `%s`\", cmd, actual)\n\t\t}\n\t}\n}\n\nvar defaultTestConfig = Config{\n\tDevice:           \"eth0\",\n\tStop:             false,\n\tLatency:          -1,\n\tTargetBandwidth:  -1,\n\tDefaultBandwidth: 20000,\n\tPacketLoss:       0.1,\n\tTargetIps:        []string{\"10.10.10.10\"},\n\tTargetPorts:      []string{\"80\"},\n\tTargetProtos:     []string{\"tcp\"},\n\tDryRun:           false,\n}\n\nfunc TestTcPacketLossSetup(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &tcThrottler{r}\n\tcfg := defaultTestConfig\n\tcfg.Device = \"eth1\"\n\tcfg.PacketLoss = 0.2\n\tth.setup(&cfg)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo tc qdisc add dev eth1 handle 10: root htb default 1\",\n\t\t\"sudo tc class add dev eth1 parent 10: classid 10:1 htb rate 20000kbit\",\n\t\t\"sudo tc class add dev eth1 parent 10: classid 10:10 htb rate 1000000kbit\",\n\t\t\"sudo tc qdisc add dev eth1 parent 10:10 handle 100: netem loss 0.20%\",\n\t\t\"sudo iptables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10 -p tcp --dport 80 -d 10.10.10.10\",\n\t})\n}\n\nfunc TestTcWildcardIps(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &tcThrottler{r}\n\tcfg := defaultTestConfig\n\tcfg.TargetIps = []string{}\n\tcfg.TargetPorts = []string{}\n\tcfg.TargetProtos = []string{}\n\tcfg.PacketLoss = -1\n\tth.setup(&cfg)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo tc qdisc add dev eth0 handle 10: root htb default 1\",\n\t\t\"sudo tc class add dev eth0 parent 10: classid 10:1 htb rate 20000kbit\",\n\t\t\"sudo tc class add dev eth0 parent 10: classid 10:10 htb rate 1000000kbit\",\n\t\t\"sudo tc qdisc add dev eth0 parent 10:10 handle 100: netem\",\n\t\t\"sudo iptables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10\",\n\t\t\"sudo ip6tables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10\",\n\t})\n}\n\nfunc TestTcMultiplePortsAndIps(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &tcThrottler{r}\n\tcfg := defaultTestConfig\n\tcfg.TargetIps = []string{\"1.1.1.1\", \"2.2.2.2\"}\n\tcfg.TargetPorts = []string{\"80\", \"8080\"}\n\tcfg.TargetProtos = []string{\"tcp\", \"udp\"}\n\tth.setup(&cfg)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo tc qdisc add dev eth0 handle 10: root htb default 1\",\n\t\t\"sudo tc class add dev eth0 parent 10: classid 10:1 htb rate 20000kbit\",\n\t\t\"sudo tc class add dev eth0 parent 10: classid 10:10 htb rate 1000000kbit\",\n\t\t\"sudo tc qdisc add dev eth0 parent 10:10 handle 100: netem loss 0.10%\",\n\t\t\"sudo iptables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10 -p tcp --match multiport --dports 80,8080 -d 1.1.1.1\",\n\t\t\"sudo iptables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10 -p udp --match multiport --dports 80,8080 -d 1.1.1.1\",\n\t\t\"sudo iptables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10 -p tcp --match multiport --dports 80,8080 -d 2.2.2.2\",\n\t\t\"sudo iptables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10 -p udp --match multiport --dports 80,8080 -d 2.2.2.2\",\n\t})\n}\n\nfunc TestTcMixedIPv6Setup(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &tcThrottler{r}\n\tcfg := defaultTestConfig\n\tcfg.Device = \"eth1\"\n\tcfg.PacketLoss = 0.2\n\tcfg.TargetIps6 = []string{\"2001:db8::1\"}\n\tth.setup(&cfg)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo tc qdisc add dev eth1 handle 10: root htb default 1\",\n\t\t\"sudo tc class add dev eth1 parent 10: classid 10:1 htb rate 20000kbit\",\n\t\t\"sudo tc class add dev eth1 parent 10: classid 10:10 htb rate 1000000kbit\",\n\t\t\"sudo tc qdisc add dev eth1 parent 10:10 handle 100: netem loss 0.20%\",\n\t\t\"sudo iptables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10 -p tcp --dport 80 -d 10.10.10.10\",\n\t\t\"sudo ip6tables -A POSTROUTING -t mangle -j CLASSIFY --set-class 10:10 -p tcp --dport 80 -d 2001:db8::1\",\n\t})\n}\n\nfunc TestTcTeardown(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &tcThrottler{r}\n\tr.responses = map[string][]string{\n\t\t\"sudo iptables -S -t mangle\": {\n\t\t\t\"-P PREROUTING ACCEPT\",\n\t\t\t\"-P INPUT ACCEPT\",\n\t\t\t\"-P FORWARD ACCEPT\",\n\t\t\t\"-P OUTPUT ACCEPT\",\n\t\t\t\"-P POSTROUTING ACCEPT\",\n\t\t\t\"-A POSTROUTING -d 10.10.10.10 -p tcp -m tcp --dport 80 -j CLASSIFY --set-class 0010:0010\",\n\t\t},\n\t\t\"sudo ip6tables -S -t mangle\": {\n\t\t\t\"-P PREROUTING ACCEPT\",\n\t\t\t\"-P INPUT ACCEPT\",\n\t\t\t\"-P FORWARD ACCEPT\",\n\t\t\t\"-P OUTPUT ACCEPT\",\n\t\t\t\"-P POSTROUTING ACCEPT\",\n\t\t},\n\t}\n\tth.teardown(&defaultTestConfig)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo iptables -S -t mangle\",\n\t\t\"sudo iptables -t mangle -D POSTROUTING -d 10.10.10.10 -p tcp -m tcp --dport 80 -j CLASSIFY --set-class 0010:0010\",\n\t\t\"sudo ip6tables -S -t mangle\",\n\t\t\"sudo tc qdisc del dev eth0 handle 10: root\",\n\t})\n}\n\nfunc TestTcTeardownNoIpTables(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &tcThrottler{r}\n\tth.teardown(&defaultTestConfig)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo iptables -S -t mangle\",\n\t\t\"sudo ip6tables -S -t mangle\",\n\t\t\"sudo tc qdisc del dev eth0 handle 10: root\",\n\t})\n}\n\nfunc TestTcIPv6Teardown(t *testing.T) {\n\tr := newCmdRecorder()\n\tth := &tcThrottler{r}\n\tr.responses = map[string][]string{\n\t\t\"sudo iptables -S -t mangle\": {},\n\t\t\"sudo ip6tables -S -t mangle\": {\n\t\t\t\"-P PREROUTING ACCEPT\",\n\t\t\t\"-P INPUT ACCEPT\",\n\t\t\t\"-P FORWARD ACCEPT\",\n\t\t\t\"-P OUTPUT ACCEPT\",\n\t\t\t\"-P POSTROUTING ACCEPT\",\n\t\t\t\"-A POSTROUTING -d 2001:db8::1 -p tcp -m tcp --dport 80 -j CLASSIFY --set-class 0010:0010\",\n\t\t},\n\t}\n\tconfig := defaultTestConfig\n\n\tth.teardown(&config)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo iptables -S -t mangle\",\n\t\t\"sudo ip6tables -S -t mangle\",\n\t\t\"sudo ip6tables -t mangle -D POSTROUTING -d 2001:db8::1 -p tcp -m tcp --dport 80 -j CLASSIFY --set-class 0010:0010\",\n\t\t\"sudo tc qdisc del dev eth0 handle 10: root\",\n\t})\n}\n\nfunc TestTcTeardownNoIPv6(t *testing.T) {\n\tr := newCmdRecorder()\n\tr.cmdBlackList = []string{\"ip6tables\"}\n\tth := &tcThrottler{r}\n\tr.responses = map[string][]string{\n\t\t\"sudo iptables -S -t mangle\": {\n\t\t\t\"-P PREROUTING ACCEPT\",\n\t\t\t\"-P INPUT ACCEPT\",\n\t\t\t\"-P FORWARD ACCEPT\",\n\t\t\t\"-P OUTPUT ACCEPT\",\n\t\t\t\"-P POSTROUTING ACCEPT\",\n\t\t\t\"-A POSTROUTING -d 10.10.10.10 -p tcp -m tcp --dport 80 -j CLASSIFY --set-class 0010:0010\",\n\t\t},\n\t}\n\n\tth.teardown(&defaultTestConfig)\n\tr.verifyCommands(t, []string{\n\t\t\"sudo iptables -S -t mangle\",\n\t\t\"sudo iptables -t mangle -D POSTROUTING -d 10.10.10.10 -p tcp -m tcp --dport 80 -j CLASSIFY --set-class 0010:0010\",\n\t\t\"sudo tc qdisc del dev eth0 handle 10: root\",\n\t})\n}\n"
  },
  {
    "path": "throttler/throttler.go",
    "content": "package throttler\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n)\n\nconst (\n\tlinux           = \"linux\"\n\tdarwin          = \"darwin\"\n\tfreebsd         = \"freebsd\"\n\twindows         = \"windows\"\n\tcheckOSXVersion = \"sw_vers -productVersion\"\n\tipfw            = \"ipfw\"\n\tpfctl           = \"pfctl\"\n)\n\n// Config specifies options for configuring packet filter rules.\ntype Config struct {\n\tDevice           string\n\tStop             bool\n\tLatency          int\n\tTargetBandwidth  int\n\tDefaultBandwidth int\n\tPacketLoss       float64\n\tTargetIps        []string\n\tTargetIps6       []string\n\tTargetPorts      []string\n\tTargetProtos     []string\n\tDryRun           bool\n}\n\ntype throttler interface {\n\tsetup(*Config) error\n\tteardown(*Config) error\n\texists() bool\n\tcheck() string\n}\n\ntype commander interface {\n\texecute(string) error\n\texecuteGetLines(string) ([]string, error)\n\tcommandExists(string) bool\n}\n\ntype dryRunCommander struct{}\n\ntype shellCommander struct{}\n\nvar dry bool\n\nfunc setup(t throttler, cfg *Config) {\n\tif t.exists() {\n\t\tfmt.Println(\"It looks like the packet rules are already setup\")\n\t\tos.Exit(1)\n\t}\n\n\tif err := t.setup(cfg); err != nil {\n\t\tfmt.Println(\"I couldn't setup the packet rules:\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Println(\"Packet rules setup...\")\n\tfmt.Printf(\"Run `%s` to double check\\n\", t.check())\n\tfmt.Printf(\"Run `%s --device %s --stop` to reset\\n\", os.Args[0], cfg.Device)\n}\n\nfunc teardown(t throttler, cfg *Config) {\n\tif !t.exists() {\n\t\tfmt.Println(\"It looks like the packet rules aren't setup\")\n\t\tos.Exit(1)\n\t}\n\n\tif err := t.teardown(cfg); err != nil {\n\t\tfmt.Println(\"Failed to stop packet controls\")\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Println(\"Packet rules stopped...\")\n\tfmt.Printf(\"Run `%s` to double check\\n\", t.check())\n\tfmt.Printf(\"Run `%s` to start\\n\", os.Args[0])\n}\n\n// Run executes the packet filter operation, either setting it up or tearing\n// it down.\nfunc Run(cfg *Config) {\n\tdry = cfg.DryRun\n\tvar t throttler\n\tvar c commander\n\n\tif cfg.DryRun {\n\t\tc = &dryRunCommander{}\n\t} else {\n\t\tc = &shellCommander{}\n\t}\n\n\tswitch runtime.GOOS {\n\tcase freebsd:\n\t\tif cfg.Device == \"\" {\n\t\t\tfmt.Println(\"Device not specified, unable to default to eth0 on FreeBSD.\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tt = &ipfwThrottler{c}\n\tcase darwin:\n\t\t// Avoid OS version pinning and choose based on what's available\n\t\tif c.commandExists(pfctl) {\n\t\t\tt = &pfctlThrottler{c}\n\t\t} else if c.commandExists(ipfw) {\n\t\t\tt = &ipfwThrottler{c}\n\t\t} else {\n\t\t\tfmt.Println(\"Could not determine an appropriate firewall tool for OSX (tried pfctl, ipfw), exiting\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif cfg.Device == \"\" {\n\t\t\tcfg.Device = \"eth0\"\n\t\t}\n\n\tcase linux:\n\t\tif cfg.Device == \"\" {\n\t\t\tcfg.Device = \"eth0\"\n\t\t}\n\n\t\tt = &tcThrottler{c}\n\tdefault:\n\t\tfmt.Printf(\"I don't support your OS: %s\\n\", runtime.GOOS)\n\t\tos.Exit(1)\n\t}\n\n\tif !cfg.Stop {\n\t\tsetup(t, cfg)\n\t} else {\n\t\tteardown(t, cfg)\n\t}\n}\n\nfunc (c *dryRunCommander) execute(cmd string) error {\n\tfmt.Println(cmd)\n\treturn nil\n}\n\nfunc (c *dryRunCommander) executeGetLines(cmd string) ([]string, error) {\n\tfmt.Println(cmd)\n\treturn []string{}, nil\n}\n\nfunc (c *dryRunCommander) commandExists(cmd string) bool {\n\treturn true\n}\n\nfunc (c *shellCommander) execute(cmd string) error {\n\tfmt.Println(cmd)\n\treturn exec.Command(\"/bin/sh\", \"-c\", cmd).Run()\n}\n\nfunc (c *shellCommander) executeGetLines(cmd string) ([]string, error) {\n\tlines := []string{}\n\tchild := exec.Command(\"/bin/sh\", \"-c\", cmd)\n\n\tout, err := child.StdoutPipe()\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\terr = child.Start()\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tscanner := bufio.NewScanner(out)\n\n\tfor scanner.Scan() {\n\t\tlines = append(lines, scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn []string{}, errors.New(fmt.Sprint(\"Error reading standard input:\", err))\n\t}\n\n\terr = child.Wait()\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\treturn lines, nil\n}\n\nfunc (c *shellCommander) commandExists(cmd string) bool {\n\t_, err := exec.LookPath(cmd)\n\treturn err == nil\n}\n"
  }
]