Compare commits

...
958 Commits
Author SHA1 Message Date
Leonid Bugaev a8cfaa7581 Add --output-http-compatibility-mode
Add support for using default Go HTTP client
2019-03-10 10:29:28 +01:00
Leonid Bugaev 707b311456 Add deleteHttpCookie method (#658)
Version bumped to 1.0, together with upcoming GoReplay release
2019-03-07 22:45:17 +01:00
EhsanKhaki b37fe727b4 Typos and fixes (#657) 2019-03-07 22:23:50 +01:00
Matt Robenolt f6b0d5d794 Support for HTTP(S) Proxy (#655)
Works like with standard Go client
2019-02-23 10:46:53 +01:00
Leonid Bugaev e3f3348105 Update gopacket 2019-02-16 10:13:03 +01:00
Cole Kettler 60e150de67 Fix golint URL per https://github.com/golang/lint/issues/415 (#618) 2019-02-16 09:55:34 +01:00
igorljubuncic c092718ee6 Add support for building snaps (#625) 2019-02-16 09:51:54 +01:00
bruce34 84e99a8bb0 Fix array out of bounds during using http-set-header (#627)
Happens for example when payload stops at a '-' and we are searching for
Accept-Encoding.The method has been simplified and now does full case
insensitivity. Performance checking, on x64, it is ever so slightly
faster than the original.
2019-02-16 09:49:29 +01:00
bruce34 279aa3fc3f More robust chunked encoding finished check. (#628) 2019-02-16 09:41:10 +01:00
Leonid Bugaev 408f1d0f31 Merge branch 'bruce34-b34-pcap-immediate-mode' 2019-02-16 09:40:18 +01:00
Leonid Bugaev f57703ee5c Merge branch 'b34-pcap-immediate-mode' of https://github.com/bruce34/goreplay into bruce34-b34-pcap-immediate-mode 2019-02-16 09:40:02 +01:00
Leonid Bugaev 264d8cf00e Add more error handling 2019-02-16 09:37:00 +01:00
bruce34 6f70a939f4 Add setting for copyBufferSize, defaults to 5 Mbytes (#630) 2019-02-16 09:34:53 +01:00
bruce34 c693938ef9 Allow a range of output-http-workers with min and max. (#631)
This provides the ability to have a maximum number of workers, yet still allow scaling down. The scaling down is important to stop timeouts happening with under-utilised workers.
Note, although the code has workers_min, workers_max, the settings option --output-http-workers has remained and becomes the "max" value. I did this to hopefully not break too much for others. The min will default to 1, so users will see dynamic scaling unless they also set min to be the same. This will probably benefit them as they will avoid potential timeouts when the traffic reduces. But something to be aware of.
2019-02-16 09:32:56 +01:00
bruce34 267d6d0e2b Add adjustable output-http-stats-ms (#633)
This adds an option to log output-http-stats at a period desired.
2019-02-16 09:29:51 +01:00
bruce34 e9a5cc19b5 Configurable http_output queue length (#634)
Makes sense!
2019-02-16 09:27:44 +01:00
bruce34 d8cace421e Configurable override snaplen to 64k for virtualized environments (#637) 2019-02-16 09:26:39 +01:00
Miquel B bf98a636c4 Using scratch image to execute goreplay (#619)
We could minimize the docker image final size using scratch image
2019-02-16 09:17:11 +01:00
bruce34 476ed808f9 Bugfix index out of bounds (\r\n\r\n split over two packets) (#632) 2019-02-16 09:03:17 +01:00
Leonid Bugaev ec3f104c8c Add way to dynamically profile
Added new `--http-pprof` option, example: "--http-pprof :8181"
It starts web server on given address, and expose special /debug/pprof
endpoint

See https://golang.org/pkg/net/http/pprof/
2019-02-16 08:59:43 +01:00
Leonid Bugaev 85c6070775 File output now case limit by size
Added new `output-file-max-size-limit` option
2019-02-16 08:49:31 +01:00
Leonid Bugaev b4a2c018c1 Fix request filtering issue
https://github.com/buger/goreplay/issues/648
2019-01-25 20:00:22 +01:00
Leonid Bugaev fb3870d68c Fix --http-allow-header to filter non existent headers
Fix https://github.com/buger/goreplay/issues/604
2019-01-24 23:47:14 +01:00
elad 7b0f81b82f Keep headers request during redirects (#645)
During redirect, send original request headers payload, just with modified location.
2019-01-20 20:14:37 +01:00
Vladimir Dubovik 633cfd5fb4 support value with "=" in httpCookie() 2019-01-07 19:59:50 +01:00
bruce34 a5a3012347 Allow commons tgzs to be cached 2019-01-03 23:06:30 +03:00
bruce34 393eb74f9c Add setting for pcap immediate mode to fix timeouts waiting for packets 2018-12-17 16:24:51 +00:00
Leonid Bugaev 52ed8b4d1e Add protection for malformed records 2018-08-24 16:35:04 +05:00
Leonid Bugaev 29139e9eda Fix prefixer panic when body is too small 2018-08-10 21:34:00 +05:00
myzhan 9fd7a46e7e FIX: miscalculation of the mean value 2018-08-08 17:23:33 +05:00
chainhelen f85bb29327 remove unused "copy" 2018-08-06 11:44:33 +05:00
Leonid Bugaev 68082bfb11 Fix typo 2018-08-02 21:41:36 +05:00
Leonid Bugaev 28d646d118 Merge branch 'master' of https://github.com/buger/gor 2018-08-02 21:39:42 +05:00
Leonid Bugaev c93ff3598c Fix prettifier buffer overflow 2018-08-02 21:36:47 +05:00
Scott Albertson 0bc3fba5d0 Add a "Reviewed by Hound" badge 2018-08-01 13:28:52 +05:00
Alex Zvorygin 65fd1983b1 Fix broken link to goreplay.com -> goreplay.org 2018-07-13 09:09:33 +05:00
Alex Zvorygin 88972ff301 fix typo in ruby middleware example
continiously -> continuously
2018-07-04 13:55:58 +05:00
Samuel Gulliksson 85a7bc1e9a Fix typo in Python middleware example. 2018-06-28 09:18:26 +05:00
Alex Zvorygin 36a8845ffe Fix typo 2018-06-28 09:18:02 +05:00
Leonid Bugaev 9eb6ab262b Add "deleteHttpHeader" 2018-06-22 22:11:29 +05:00
Chintan Patel 896dbe312a Exporting the httpHeaders method
This method export was missing from last commit (when `httpHeaders` was created)
2018-06-08 08:09:10 +05:00
Leonid Bugaev edae33717e Improve start/end time calculation 2018-05-28 10:05:07 +03:00
Leonid Bugaev c5d1112e7a Add way to control packet capture buffer size and optimize snaplen
Added `—input-raw-buffer-size` - Controls size of the OS buffer (in
bytes) which holds packets until they dispatched. Default value depends
by system: in Linux around 2MB. If you see big package drop, increase
this value.

Additionally snaplen (max number of bytes being read for each packet)
now dynamically set based on interface MTU + max header size. In most
situations it should reduce package drop, because each packet will
consume less space in buffer.
2018-05-27 12:31:47 +03:00
Jordan Crawford 18610d3555 Solve issue 535 missing responses to HEAD requests, and add a test to verify 2018-05-23 20:53:01 +03:00
bruce34 0fea94a76c Fix 100 continue (#562)
* On write error, disconnect to force a new connection

* Don't loose bytes checking connection isAlive

* Soak up any 1xx return codes, catching up to the real return code
2018-05-23 20:49:02 +03:00
defa sun 7b1544157f fix out of range index in headerIndex, github.com/buger/goreplay/issues/578 2018-05-23 20:33:32 +03:00
Daniel Roop 4e46bb46af Updated README to include httpHeaders 2018-05-23 20:22:58 +03:00
Daniel Roop b1092d1567 Created helper to return all http headers for node middleware 2018-05-23 20:22:58 +03:00
Leonid Bugaev 0c0ef97b67 Add additional tests 2018-05-12 15:17:26 +03:00
Leonid Bugaev fe6cfd90fe Fix responses when header end line separated by multiple packets 2018-05-10 22:19:56 +03:00
Leonid Bugaev c9fe4a11ad Fix proto.Body when body < 4 bytes 2018-05-10 22:19:08 +03:00
Leonid Bugaev e9294aeb5f Fix emitter typo 2018-05-10 22:18:47 +03:00
Leonid Bugaev cb1ae0e7c0 Revert "Update middleware.js"
This reverts commit 2db143aaef.
2018-04-24 19:42:37 +03:00
Oleg Blokhin 2db143aaef Update middleware.js
fix request filtering in middleware.js
2018-04-24 19:42:05 +03:00
Ubuntu a65256d707 Fixed kafka client run of brokers and index out of range issues 2018-02-27 20:17:45 +03:00
Rajat Verma 1f62555ca8 Update README.md
Fix minor typos
2018-02-27 20:17:14 +03:00
Leonid Bugaev d265594b00 Ensure that tcp-output do not loose messages when reconnecting 2018-02-07 20:29:19 +02:00
Leonid Bugaev 0097c599df Fix response latency calculation
Previously latency calcualted as Response.End - Request.Start
Where both End and Start is a last and first packets

This calcualtion is wrong, because it is total roundtrip

Correct server latency will be Response.End - Request.End

In addition added new `--input-raw-timestamp-type` option
which allows choose more precise packet timestamp source (if available).
2018-02-05 21:47:48 +02:00
Ohad Basan f8a1b9dde6 fix error in bash example 2018-02-03 13:17:20 +02:00
Ohad Basan 22a67df6c0 fix wrong param in docs 2018-02-03 13:17:20 +02:00
Leonid Bugaev 5bd47ee1df Merge branch 'master' of https://github.com/buger/gor 2018-01-10 21:24:38 +02:00
Leonid Bugaev 45d7527128 Increase middleware buffer to avoid overloads when prettifier returns buffer larger then original 2018-01-10 21:23:55 +02:00
Daniel Albuquerque bf8198d639 Hardcode alpine version and bump version of goreplay from 16.0.2 to 16.1 2017-11-15 21:20:44 +02:00
Mel Shafer 3acec0fd42 fix typo in the README 2017-10-31 09:15:00 +02:00
noibar cc005ddcbb Fix comment on tcp message methods (#521)
* Fix comment on tcp message methods

* Update tcp message constructor documentation
2017-10-23 18:26:14 +03:00
Leonid Bugaev debb265d6d Fix memory leak 2017-10-04 20:18:05 +03:00
Leonid Bugaev c5f12b567b Add log helper and fix memory leak 2017-09-24 22:32:03 +05:00
Leonid Bugaev 4255d4155f Improve handling for 100-continue requests for clients ignoring response (#513)
Some clients, even if have `Expect: 100-continue` in request, start
sending data without waiting approval from the server. More over, there
is cases when response “100 Continue” is received, client changes TCP
seq, and following requests start having valid sequences, based on
response one.

This change should address this bugs.

As small addition extended list of http methods, to fully support
webdav.
2017-09-15 19:25:46 +05:00
Leonid Bugaev 4bb64be27e Fix panic when reading too big response in debug mode 2017-09-14 22:35:45 +05:00
Leonid Bugaev e310fc8369 Fix zero-length 100-continue packets
Should fix https://github.com/buger/goreplay/issues/496
2017-09-03 22:11:42 +05:00
Leonid Bugaev c8f4493eca Update COMM-LICENSE
Misc improvements
2017-08-28 19:26:24 +05:00
Aggelos Avgerinos d309650589 Allow all HTTP methods to have body (#479)
HTTP specification in section 4.3 (Message Body) states:

"A message-body MUST NOT be included in a request if the specification of the
request method (section 5.1.1)"

Section 5.1.1 has links to the description of each method (sections 9.2
to 9.9). None of those sections prohibit the transfer of a message body,
it just points out how each method should be treated server-side.
2017-08-22 19:28:21 +05:00
田欧 17f6c59061 remove some else statements for reducing indent (#488)
* remove else

* remove else
2017-08-22 19:22:59 +05:00
Ashwin Jayaprakash 9cf1ad65df Filter requests using regex on base64 decoded userId:passwd of basic auth (#475)
Example snippet: --http-basic-auth-filter "^customer[0-9].*"
2017-08-22 19:16:55 +05:00
田欧 16b6a3cc31 Adjust package order (#487)
* format package order

* format package order

* format package order

* format package order and format code by fmt
2017-08-22 19:15:01 +05:00
Ivan Klishch dfb67b4456 Fixed Dockerfile that fails during docker build (#472)
* Fixed Dockerfile that fails during docker build

* make build should use Dockerfile.dev since other make targets use it
2017-08-22 19:14:32 +05:00
François-Xavier Ponscarme efce146244 fix: add basic auth support in elastic URI (#433)
* fix: add basic auth support in elastic URI

* more simple URI check and index extract

* chore: remove dead code
2017-08-22 19:13:46 +05:00
SoulZxz eb8eb1db52 fix file rotate issues 2017-08-22 19:12:51 +05:00
Amir Majedi d7ffc3c359 Adding a python middleware example file 2017-08-22 17:35:59 +05:00
Leonid Bugaev 1c3cd633d1 Fix bpfFilter 2017-08-22 17:20:45 +05:00
Leonid Bugaev b8befff286 Sync makefile 2017-08-22 17:07:37 +05:00
Leonid Bugaev 2b79791fe6 Reading from pcap file should properly set src and dest ports 2017-08-22 17:07:37 +05:00
Leonid Bugaev 39ebff56b4 Update to use latest docker.dev 2017-08-22 17:07:37 +05:00
thinkerou c138fa9739 format file 2017-08-11 14:40:55 +03:00
thinkerou 89c34c6bf5 format file 2017-08-11 14:40:55 +03:00
tianou a1054b10e8 fix typo 2017-08-11 06:33:26 +03:00
Leonid Bugaev cf402a1d0e Add option to specify custom BPF filter
Can be useful in case of non standard network interfaces when like
tunnels or SPAN ports, when IP of interface does not match with IP of
packet.

Can be used to read traffic from multiple ports and interfaces at once
as well.
2017-07-27 17:56:33 +03:00
Leonid Bugaev 09f47b25bf Fix panic for non compilant http requests 2017-07-20 21:02:07 +03:00
Leonid Bugaev 652e589e2b fix proto.Path 2017-06-30 15:58:45 +02:00
Leonid Bugaev 5aa1696680 Add TLS security support between --input-tcp and --output-tcp 2017-06-27 17:11:34 +02:00
Leonid Bugaev 21531cea9a Add support for rewriting headers 2017-06-27 15:30:34 +02:00
Leonid Bugaev 03767d1a77 Add support for HTTP 1.0 and less 2017-06-27 14:24:43 +02:00
Leonid Bugaev 2680ce9dd4 Fix #467 2017-06-27 14:01:17 +02:00
Leonid Bugaev b3dffae66f When using --input-file it should exit once file is fully read 2017-06-27 13:56:14 +02:00
Leonid Bugaev aa4a878436 Handle gzip encoding error
Fix #470
2017-06-24 20:35:35 +02:00
Michael Marino 4fe95be416 Add example of middleware for javascript 2017-06-03 11:32:49 +03:00
KingLebron 23771b8994 [Spelling Error] Change 'dirrectory' to 'directory'
:)
2017-05-23 14:32:43 +03:00
Leonid Bugaev a1a4460c90 Update Dockerfile 2017-05-18 16:53:11 +03:00
Leonid Bugaev 2b20c1107a Update Dockerfile 2017-05-18 16:52:46 +03:00
Leonid Bugaev d755c579e4 Create Dockerfile 2017-05-18 16:47:41 +03:00
Leonid Bugaev 064519ce89 Rename Dockerfile to Dockerfile.dev 2017-05-18 16:40:42 +03:00
Leonid Bugaev cdd818fe77 Update README.md 2017-05-17 22:48:45 +03:00
Leonid Bugaev c23f95d4cf Add httpMethod function 2017-05-17 22:47:05 +03:00
Leonid Bugaev 4cf59cc913 Merge branch 'master' of https://github.com/buger/gor 2017-05-17 22:43:18 +03:00
Leonid Bugaev 8f450c77a6 Update README.md 2017-05-17 21:34:26 +03:00
Leonid Bugaev a49b250ab4 Fix typo 2017-05-17 21:32:08 +03:00
Leonid Bugaev de47f6d6f6 Fix httpHeader when header value contain ":" 2017-05-17 21:21:44 +03:00
Leonid Bugaev d9ce263c6a Update README.md 2017-05-02 17:42:13 +02:00
Leonid Bugaev 74225ebb22 Rename all package imports from gor to goreplay 2017-05-01 17:56:50 +02:00
Leonid Bugaev d1ddda4181 Add govendor and vendor all depended packages 2017-05-01 17:10:32 +02:00
Leonid Bugaev a15055ef7f Update README.md 2017-05-01 15:25:44 +02:00
ikenchina 1aa24a9910 fixed bug 2017-04-20 07:23:22 +02:00
Leonid Bugaev dcc7af4c09 Fix output-file sizeLimit 2017-04-07 15:09:16 +02:00
Leonid Bugaev 0fb98a8f48 Improve http handling 2017-04-07 14:48:12 +02:00
Leonid Bugaev 6ea23de38b Add new option --input-raw-expire to configure TCP message expiration 2017-03-17 15:23:57 +01:00
Leonid Bugaev 375538263b Add additional check for malformed packets 2017-03-17 15:01:32 +01:00
Leonid Bugaev a2a1bd5c67 Fix handling of 304 responses if EOF error received 2017-03-10 09:32:24 +01:00
Leonid Bugaev ce46188dc2 Update NodeJS middleware 2017-03-06 20:15:35 +03:00
Leonid Bugaev 7c67b8c566 Add NodeJS middleware framework 2017-02-28 17:17:24 +03:00
Leonid Bugaev 5a8d56e10b Improve http client error handling
If replaying too fast, we can result in no TCP error, but actual
response is empty or garbage.
2017-02-26 20:55:40 +03:00
Leonid Bugaev c8dfe67ccb Fix middleware when used with prettyfier and gzip encoding
If while decompressing gzip payload decompressed value was less then
compressed, it did not changed buffer length, and middleware received
bytes left from gzip response.
2017-02-26 20:54:26 +03:00
Leonid Bugaev e1f3d71f4e Make http prettifier work with middleware 2017-02-07 13:34:51 +03:00
Leonid Bugaev 858dfaac78 Make HTTP output less verbose
It will act same with —debug flag
2017-02-07 13:33:45 +03:00
Leonid Bugaev 6a48882125 Fix infinite lock at file output 2017-02-05 17:26:22 +03:00
Leonid Bugaev bf1c67c5a1 Add install task 2017-02-05 17:26:04 +03:00
Nicholas Wiersma e726e45dc0 Fix kafka issue (#419) 2017-01-25 15:25:06 +04:00
Leonid Bugaev d66ba0353a Prettify http (#418)
Prettify HTTP
2017-01-23 21:02:26 +04:00
Leonid Bugaev ecb16664db Allow to use payload type for file names (#417) 2017-01-23 16:40:14 +04:00
Leonid Bugaev 8c16220532 Track http responses (#416) 2017-01-23 16:20:27 +04:00
Leonid Bugaev ed37589748 Cleanup modifier settings after test 2017-01-23 14:43:58 +03:00
Leonid Bugaev 590304d687 Ensure that flush do not get called on closed file 2017-01-23 14:43:43 +03:00
Leonid Bugaev e69570367b More fmt fixes 2017-01-23 13:34:57 +03:00
Leonid Bugaev 043c0b7436 few fmt fixes 2017-01-23 13:33:36 +03:00
Leonid Bugaev 768a29e2af Merge branch 'msales-apache-kafka-input' 2017-01-20 21:03:03 +03:00
Leonid Bugaev 5e90377a7f Fmt changes 2017-01-20 21:01:19 +03:00
Leonid Bugaev f520b338f3 Add tests and modify to work same as Kafka output 2017-01-20 21:00:23 +03:00
Leonid Bugaev 53cbd8863d Merge branch 'apache-kafka-input' of https://github.com/msales/goreplay into msales-apache-kafka-input 2017-01-20 18:15:33 +03:00
Leonid Bugaev def3c91898 Add Kafka tests and raw format mode (#415)
* Add tests and send messages in raw format by default
2017-01-20 19:13:30 +04:00
Leonid Bugaev 4ea306b5a9 Merge branch 'master' of https://github.com/buger/gor 2017-01-20 16:10:12 +03:00
Leonid Bugaev 3b51158163 continue work on new docs 2017-01-20 16:09:00 +03:00
Leonid Bugaev fe321cd055 Merge pull request #413 from SophisticaSean/master
flush the output buffer when it should be flushed
2017-01-08 11:54:53 +04:00
Leonid Bugaev 8421ddb6ff Rename Home.md to index.md 2017-01-05 20:35:21 +03:00
Leonid Bugaev e5935a001d Set theme jekyll-theme-cayman 2017-01-05 20:31:56 +03:00
Leonid Bugaev a519c09770 Set theme jekyll-theme-slate 2017-01-05 20:28:45 +03:00
Leonid Bugaev 17c1abfc5e Create CNAME 2017-01-05 20:25:09 +03:00
Leonid Bugaev ea8d3f7299 Set theme jekyll-theme-cayman 2017-01-05 20:21:20 +03:00
Leonid Bugaev 962fd70d1a Add docs to master 2017-01-05 20:19:44 +03:00
Sean Lewis b0b697cba6 flush the output buffer when it should be flushed
fixes #409
2017-01-04 14:59:39 -07:00
Leonid Bugaev 060f521a0a Merge pull request #412 from buger/handle_spaces_in_filters
Allow spaces inside filters
2016-12-27 19:52:11 +04:00
Leonid Bugaev 8e5a256226 Allow spaces inside filters 2016-12-27 18:48:59 +03:00
Leonid Bugaev 8ce5318fbf Merge pull request #410 from smostovoy/381-dumb-to-files
Support %r - request id - output file pattern #381
2016-12-27 19:07:54 +04:00
Leonid Bugaev db1e3d71e7 Merge pull request #411 from buger/fix-proto-crash
Fix crashes in ParseHeaders
2016-12-27 18:39:22 +04:00
Leonid Bugaev f5e8e26e96 Fix #408 2016-12-27 17:16:29 +03:00
Sergey Mostovoy 826cc45d44 clean files in test [#381] 2016-12-27 12:46:47 +02:00
Sergey Mostovoy 5909dd71c5 Support %r - request id - output file pattern #381 2016-12-27 12:18:49 +02:00
Leonid Bugaev 3043189d55 Merge branch 'pr/406' 2016-12-23 20:29:13 +03:00
Leonid Bugaev 9b40730338 Merge branch 'master' into pr/406 2016-12-23 20:26:09 +03:00
Leonid Bugaev be49c7e7ac Run GC on each 1000th request 2016-12-23 20:25:09 +03:00
Nicholas Wiersma dfd5fa0c4f Update documentation 2016-12-22 10:28:35 +01:00
Sergey Mostovoy 5b5c3f33f4 Filter response if request is filtered #388 2016-12-22 11:25:29 +02:00
Nicholas Wiersma 1f19e550bb Create kafka input 2016-12-22 09:59:48 +01:00
Leonid Bugaev fd5118b76d fix test: should not add port to host for https 2016-12-19 14:45:18 +03:00
Leonid Bugaev 7c7882969f Merge pull request #377 from kudos/patch-1
Treat PATCH as a HTTP verb
2016-12-18 20:29:48 +03:00
Leonid Bugaev 5e6b58e7a6 Merge branch 'master' of https://github.com/buger/gor 2016-12-18 20:15:35 +03:00
Leonid Bugaev a9ab7ca2f1 Merge pull request #395 from ylegat/feature/use-pcap-timestamp
Resolve buger/gor#392 : use pcap timestamp
2016-12-18 20:15:09 +03:00
Leonid Bugaev 0a74db6aae Disallow zero timeout (also used fix tests) 2016-12-18 20:09:24 +03:00
Yohan Legat b462c06a7c remove dead code 2016-12-08 17:35:45 +01:00
Yohan Legat c6244435ca [Boyscout] unexport TCPPacket.Dump() and Packet struct 2016-12-08 15:18:10 +01:00
Yohan Legat fa0e96b7ef Resolve buger/gor#392 : use pcap timestamp
Timestamp requests are now fetched from pcap payload
2016-12-08 15:18:10 +01:00
Leonid Bugaev ca61e39790 Merge pull request #398 from oivoodoo/master
Register kafka output plugin in case of having passed settings
2016-12-02 18:02:49 +03:00
Alexandr Korsak bea255ab11 Register kafka output plugin in case of having passed settings 2016-12-01 16:46:18 +03:00
Leonid Bugaev bde2977268 Merge pull request #396 from ylegat/bugfix/handle-content-length-missing-for-1xx-204-304
Resolve buger/gor#394 : Timeout for NO_CONTENT responses
2016-12-01 14:15:47 +03:00
Yohan Legat 12043e5a01 Resolve buger/gor#394 : Timeout for NO_CONTENT responses
1xx, 204 and 304 HTTP responses MUST NOT include a message body (see [RFC-2616](https://tools.ietf.org/html/rfc2616#section-4.4)).
Also, a server MAY send a Content-Length header field in a 304 (Not Modified) and MUST NOT send a Content-Length header field in any response with a status code of 1xx (Informational) or 204 (No Content) (see [RFC-7230](https://tools.ietf.org/html/rfc7230#section-3.3.2))
2016-12-01 12:08:32 +01:00
Leonid Bugaev 719e9b8e56 Merge pull request #379 from blastworksinc/feature/kafka-output
Add Apache Kafka output as JSON message
2016-11-30 20:38:47 +03:00
Leonid Bugaev cedc5fae32 Merge pull request #390 from outpace/sni-support
Add basic SNI support
2016-11-23 20:36:19 +03:00
Daniel Solano Gómez 963f7a73d7 Add basic SNI support
By adding the server name as part of the TLS client configuration, gor
will now support connecting to hosts that require SNI (such as Amazon
API Gateway).
2016-11-23 09:55:54 -05:00
Leonid Bugaev 1f24c709c2 Do not add port to Host header for https (#385) 2016-11-14 17:49:58 +03:00
Leonid Bugaev a1174a159c Do not add port to Host header for https 2016-11-14 17:47:30 +03:00
Alexandr Korsak f90dcc763b Remove server.go because of having 'gor file-server :8080' 2016-11-08 22:21:35 +03:00
Alexandr Korsak 638ddfb144 Add one more test case to cover ':' inside of header value 2016-11-02 17:50:45 +03:00
Alexandr Korsak 40f7facc33 User-Agent could contains ':' inside of value. 2016-11-02 15:34:42 +03:00
Alexandr Korsak 0a038575f3 Add all headers and properly passed body 2016-11-02 00:03:12 +03:00
Alexandr Korsak d424167f04 Change example of port for kafka host 2016-11-01 17:55:04 +03:00
Alexandr Korsak 41d3ce48a3 Add json message output for kafka 2016-11-01 17:51:15 +03:00
Alexandr Korsak 9b96dc20df Change Dockerfile because of issue on build echo.java 2016-10-31 19:29:59 +03:00
Alexandr Korsak e3a9a9b2c2 Add kafka output 2016-10-31 19:04:05 +03:00
Jonathan Cremin 76fb91966b Treat PATCH as a HTTP verb 2016-10-27 18:44:54 +01:00
manjeshnilange 22466d4028 Adding ability to output http client to close connection on specific … (#375)
* Adding ability to output http client to close connection on specific response status

* Addressed review comments
2016-10-25 22:06:43 +03:00
Leonid Bugaev 47db326b0f Fix truncated tcp check 2016-10-11 18:56:30 +03:00
Huu Khiem (Mark) 0831476beb Set default value for output-http-timeout at declaration (#371)
The actual default is 5s, set in the call of NewHTTPClient,
even if we use `--output-http--timeout=0`.

It's clearer to user if this value id declared upfront.
2016-09-27 10:40:26 +03:00
Leonid Bugaev 967c380dc3 go fmt 2016-08-31 17:27:45 +03:00
Leonid Bugaev 1674b58707 Fix basic http auth 2016-08-31 17:27:18 +03:00
Leonid Bugaev a2f5e43375 Fix replayed response header 2016-08-31 16:27:07 +03:00
Leonid Bugaev fc0361dcdc Fix handling of connection: close for POST requests 2016-08-31 16:11:13 +03:00
Guillaume Gelin 647f7022cf Add google/gopacket in vendor/ (#360) 2016-08-23 19:29:27 +03:00
Mourjo Sen 082106dfd8 Fix Java middleware example (#358)
* Add encoding/decoding HTTP msgs to Java middleware example.

* Add clojure middleware example.
2016-08-20 19:55:45 +03:00
Leonid Bugaev ecd7e3a5e5 Update README.md 2016-08-08 19:35:11 +03:00
Leonid Bugaev 544d9402f0 Disable forced flush 2016-08-08 18:09:14 +03:00
Leonid Bugaev 25ded56a59 Update COMM-LICENSE 2016-08-05 14:14:37 +03:00
Leonid Bugaev 392d9a2f0e Update LICENSE.txt 2016-08-05 14:09:20 +03:00
Leonid Bugaev fbebe72f02 Fix multi-packet splited headers 2016-08-03 16:56:50 +03:00
Leonid Bugaev e38f6a5801 Do not quite on flush error 2016-08-02 12:55:02 +03:00
Leonid Bugaev 25b998fa3f Fix run command 2016-08-01 19:23:14 +03:00
Leonid Bugaev f1f8e2f2a4 Fix http-disallow-header option 2016-08-01 19:17:05 +03:00
Leonid Bugaev 07fa6d9a7c Force Go DNS resolver 2016-08-01 18:05:52 +03:00
Leonid Bugaev f0acd31d88 Disable --input-http flag until I decide how to do it properly 2016-07-31 20:18:49 +03:00
Leonid Bugaev d34c27c3de Track FIN packets to check for closed connection (#350)
* Track FIN packets to check for closed connection

* Add tests for FIN / fix bugs

* Fmt changes
2016-07-31 20:16:01 +03:00
Leonid Bugaev 1d811f34db Update LICENSE.txt 2016-07-13 20:29:36 +03:00
Leonid Bugaev 35bb655f2d Fix response meta 2016-07-13 15:59:01 +03:00
Leonid Bugaev 24fc5b0078 Update README.md 2016-07-10 19:13:57 +03:00
Leonid Bugaev 8e0a8b31a9 Add missing submodule 2016-07-08 19:38:45 +03:00
Leonid Bugaev dac04cbef3 Merge branch 'ortz-feature/timeout-flag' 2016-07-08 19:27:33 +03:00
Leonid Bugaev dae6a8915d Refactor exit-after 2016-07-08 19:27:20 +03:00
Or Tzabary 6620d25626 Change flag name, use of DurationVar instead of int 2016-07-08 19:04:24 +03:00
Or Tzabary c78933f1df Feature flag 2016-07-08 17:05:46 +03:00
Leonid Bugaev 12287d8bae Fix type check, and add asserts submodule 2016-07-07 18:41:29 +03:00
Leonid Bugaev a5cc943af4 Fix padded packet check 2016-07-07 18:11:33 +03:00
Joseph Lawson e65035dd95 Update elasticsearch output to use vendored elastigo and fix #331. (#333)
* add elastigo submodule

* add gou submodule

* add go-hostpool submodule

* use vendored elasticgo

* update ReqUrl to ReqURL
2016-07-07 16:30:51 +03:00
Joseph Lawson c128d46088 calculate TCP payload slice sizes for Ethernet II packets less than 64 octets (#326)
* remove unused bCLRF var.

* calculate TCP payload slice sizes for Ethernet II packets less than 64 octets

* simplify slicing off padding for Ethernet link packets less than 61 octets in length.

* Make IPv4 header stripping comments more accurate.
2016-07-06 21:10:02 +03:00
Leonid Bugaev 1ed8691b38 Fix loopback for non local IP's 2016-07-05 17:09:56 +03:00
Leonid Bugaev f17f51390a Fix 100-continue with multi-packet headers
Also adds —output-null for testing purpose
2016-07-01 20:01:25 +03:00
Leonid Bugaev 5a0c03ec33 Fix BodySize for multi-packet headers 2016-06-30 14:13:27 +03:00
Leonid Bugaev 803d53a760 Merge branch 'ylegat-feature/respect_timestamps_when_replaying_requests' 2016-06-29 17:30:05 +03:00
Leonid Bugaev 7c33336433 Add missing change 2016-06-29 17:29:36 +03:00
Leonid Bugaev 37650df2c8 Refactor #308 2016-06-29 17:29:09 +03:00
Leonid Bugaev f2ff542cea Merge branch 'feature/respect_timestamps_when_replaying_requests' of https://github.com/ylegat/gor into ylegat-feature/respect_timestamps_when_replaying_requests 2016-06-27 16:19:47 +03:00
Leonid Bugaev c756a11333 Pass only valid HTTP responses (#317) 2016-06-27 16:00:57 +03:00
Leonid Bugaev 48fdc02d2f Fix tests + refactoring 2016-06-21 18:32:07 +03:00
Leonid Bugaev f2c9aee4ac Merge branch 'o19s-fix-307' 2016-06-21 18:06:05 +03:00
Leonid Bugaev aea32d9395 Rename DelHeader to DeleteHeader 2016-06-21 18:05:32 +03:00
Joseph Lawson 0089892b26 update 100-continue logic to support different header placement 2016-06-20 16:58:36 -04:00
Joseph Lawson 5d2cc68fff Add proto.DelHeader
Update proto.go to handle headers with whitespace after
2016-06-20 16:58:36 -04:00
Joseph Lawson b0fff3c402 Alternative 100 continue test 2016-06-20 16:58:36 -04:00
Joseph Lawson da09b14c8b DRY 100-continue tests 2016-06-20 16:58:36 -04:00
Leonid Bugaev e50ff77ca6 Update echo.sh 2016-06-20 19:57:10 +03:00
Leonid Bugaev 51860e130c Add support for known network layers
Fix #310
Close #311
2016-06-20 19:32:13 +03:00
Yohan Legat 9e7351d28c Resolve buger/gor#300 : respect timestamps when replaying requests
When Gor deals with multiple input files, it sorts them and replay their requests file after file.
This behavior is not convenient and should be changed. We should respect timestamps order when replaying requests.
2016-06-17 11:53:10 +02:00
Marc Lallaouret 2c49556b2e Clean current output file name (#304) 2016-06-16 22:33:55 +06:00
Marc Lallaouret d0e1858eb3 Fix Close implementation of plugins (#305)
Indeed they do not declare error as return type and so, were not called at the end of the program
2016-06-16 22:33:07 +06:00
Leonid Bugaev 95eecb6b1c Output file fixes
* Fixed flush/Write race
* Fixed names with underscores
2016-06-14 20:27:52 +05:00
Leonid Bugaev c4271ffaf4 Connection timeout should inherit Timeout 2016-06-12 16:19:51 +05:00
Leonid Bugaev f4e2b12d0f v0.14.1 (#301)
* Fix output-file

* Fix tunnel interface
2016-06-10 21:15:08 +06:00
Leonid Bugaev d193e24910 Raise error if packet layer unknown 2016-06-10 10:38:13 +05:00
Leonid Bugaev d36afeeb39 Update homebrew formula 2016-06-09 20:18:40 +05:00
Leonid Bugaev 06d129d20d Add support for injecting real ip (#296) 2016-06-09 19:06:59 +06:00
Leonid Bugaev a3aeca204c Check dst and src IP's for packets (#295)
* Add IP check

* Check dst and src ips
2016-06-09 18:41:01 +06:00
Leonid Bugaev 35696a49c2 Add logging to the file-server 2016-06-08 14:38:09 +05:00
Leonid Bugaev 0fb8cec69b Embed simple file server for tutorial purpose 2016-06-07 19:43:53 +05:00
Leonid Bugaev cefa2b5cc2 Write files in chunks (#293)
* Chunked output strategy
* Fix sorting with indexes >= 10
2016-06-07 18:46:13 +06:00
Leonid Bugaev ae092d6a02 Add custom HTTP methods
Should fix #291
2016-06-04 21:12:43 +05:00
Leonid Bugaev 9a6186ce9c Merge pull request #290 from buger/output-file-improvements
File replay and recording improvements
2016-06-01 20:42:34 +06:00
Leonid Bugaev ede0fb4c4c Allow looping mode for --input-file 2016-06-01 18:49:20 +05:00
Leonid Bugaev 651bd82d3d input-file support for gzip files 2016-06-01 10:41:29 +05:00
zweite a4e5918534 start should after beging listen signal (#289) 2016-06-01 11:11:43 +06:00
Leonid Bugaev ecfd8549a6 Remove debug 2016-05-31 20:57:19 +05:00
Leonid Bugaev 0f5b509397 Add support for reading multiple files 2016-05-31 20:44:04 +05:00
Leonid Bugaev c8a234b3dc Remove test artifacts 2016-05-31 17:12:34 +05:00
Leonid Bugaev b6f7de00c5 Add compression support 2016-05-31 16:41:01 +05:00
Leonid Bugaev ba98e6e18a Allow date templates for file names 2016-05-31 15:52:35 +05:00
Leonid Bugaev b01748bbdf Update echo.rb 2016-05-27 20:07:21 +05:00
Leonid Bugaev 75d217b846 Few fmt fixes 2016-05-27 16:38:09 +05:00
Leonid Bugaev c1f354a01c Support lower case headers 2016-05-27 16:36:28 +05:00
Leonid Bugaev b900e38035 Add homebrew formula 2016-05-27 16:36:09 +05:00
Matteo 2f45fc8ef3 Fix link in Readme.md (#287) 2016-05-27 16:33:22 +06:00
Leonid Bugaev 62b92576a0 Update README.md 2016-05-25 19:15:01 +05:00
Leonid Bugaev 98fe7f19b2 Fix raw socket ipv6 support 2016-05-25 16:27:18 +05:00
Dmitri Shuralyov 1c3af3ef6d README: Fix link to issue tracker. (#283)
It looks like you've used incorrect Markdown syntax to create a few links in commit eb9e073af8. You've since fixed some of the other links, e.g., in 2f86d005ad, but this one remained unfixed.

Also change the URL to point to issue tracker, and change the schema to https.
2016-05-24 13:22:01 +06:00
Leonid Bugaev 98868e81c5 Do not run multiple BPF filters at once 2016-05-23 18:12:31 +05:00
Leonid Bugaev 0ccace8cad Improve reconnection strategy 2016-05-23 18:05:34 +05:00
Leonid Bugaev a181b144d7 Fix output-stdout 2016-05-23 18:05:09 +05:00
Leonid Bugaev bf13dc59c3 Rename --output-dummy to --output-stdout and make it boolean (#282) 2016-05-21 21:16:47 +06:00
Leonid Bugaev d944ac6789 Properly handle requests with headers consisting of multiple packets (#281) 2016-05-21 19:46:34 +06:00
Leonid Bugaev a52f56df2b Do not track response by default (#279)
* Do not track response by default

* Add track-response integration test

* Apply fmt
2016-05-20 21:09:39 +06:00
Leonid Bugaev 2836b555e3 Fix http client when headers are sent in separate chunks 2016-05-19 11:54:19 +05:00
Leonid Bugaev af6307e6ef Rename http-buffer option 2016-05-19 11:52:35 +05:00
Ricardo Galli 38535a2055 Added http client buffer size (#249) 2016-05-19 11:33:17 +06:00
Leonid Bugaev ae7a3b7fa5 Merge pull request #277 from buger/http-compilance
Improve Http client compilance
2016-05-19 11:31:55 +06:00
Leonid Bugaev 3fa1b66fc5 Fix typo 2016-05-19 10:31:44 +05:00
Leonid Bugaev 7496692d76 Fix hound 2016-05-19 10:31:06 +05:00
Leonid Bugaev cdbf3b910e Apply fmt and fix tests 2016-05-19 10:26:39 +05:00
Leonid Bugaev fe90601bff Improve HTTP client compliance 2016-05-19 10:10:15 +05:00
Leonid Bugaev d40d6c6116 Fix --input-tcp for payloads > 64kb 2016-05-17 19:56:13 +05:00
Leonid Bugaev 37d657fc33 Update README.md 2016-05-17 18:27:04 +05:00
Leonid Bugaev 2f86d005ad Update README.md 2016-05-17 18:24:59 +05:00
Leonid Bugaev 9bed47e4d0 Update README.md 2016-05-17 18:10:27 +05:00
Leonid Bugaev 61605aefb2 Update README.md 2016-05-17 18:09:54 +05:00
Leonid Bugaev eb9e073af8 Update README.md 2016-05-17 18:07:25 +05:00
Leonid Bugaev 163f4602e4 Update README.md 2016-05-17 17:57:28 +05:00
Leonid Bugaev fee36a486d Fix makefile 2016-05-14 11:36:33 +05:00
Leonid Bugaev 854ea15900 Update release script 2016-05-13 17:42:59 +05:00
Leonid Bugaev f8349e4488 Merge pull request #273 from buger/libpcap-fixes
Libpcap fixes
2016-05-13 18:35:06 +06:00
Leonid Bugaev aac1345d16 Add Mac support 2016-05-13 17:31:39 +05:00
Leonid Bugaev 663bd8b95d fmt fixes 2016-05-13 14:46:27 +05:00
Leonid Bugaev 19bfb8211c Use latest libpcap and ensure to close sockets 2016-05-13 14:33:20 +05:00
Leonid Bugaev cbc871b83f Improve listening on all interfaces for complex environments
If one interface is failed it should not fail whole program
2016-05-11 20:08:20 +05:00
Leonid Bugaev 768c5f9726 Apply FMT 2016-05-11 16:53:23 +05:00
Leonid Bugaev 47bb312b73 Allow listening on ALL interfaces 2016-05-11 16:52:52 +05:00
Leonid Bugaev fb9cf68ff9 Merge pull request #270 from buger/ipv6
Add support for IPv6
2016-05-11 17:28:40 +06:00
Leonid Bugaev 759efce521 Add support for IPv6 2016-05-11 16:27:48 +05:00
Leonid Bugaev af831381aa Merge pull request #269 from buger/performance
Fix memory leaks and performance improvements
2016-05-11 15:32:17 +06:00
Leonid Bugaev 85e84ce330 Improve handling of fragmented messages 2016-05-11 14:26:11 +05:00
Leonid Bugaev 2bc441e0be More fixes 2016-05-11 13:16:05 +05:00
Leonid Bugaev 7ee06e84f4 Add dest port to id 2016-05-10 15:40:13 +05:00
Leonid Bugaev 4109336a43 Remove unused logging 2016-05-10 11:10:14 +05:00
Leonid Bugaev 3ada9b63fd Remove unused fields from packet 2016-05-10 11:08:39 +05:00
Leonid Bugaev c41608e48c Fix tests 2016-05-10 11:01:49 +05:00
Leonid Bugaev 48995cc41b Do not span multiple goroutines 2016-05-10 06:40:35 +05:00
Leonid Bugaev 6a3b791f7b Fix memory leak and improve tests 2016-05-09 18:00:12 +05:00
Leonid Bugaev ddaa0e9d74 Require IP address
libpcap can’t listen on all interfaces in single thread
2016-05-03 18:47:11 +05:00
Leonid Bugaev 281219e6a0 Use static linking for libpcap and fix error with truncated packets 2016-05-03 17:55:38 +05:00
Leonid Bugaev ba227ae9ba Fix license file 2016-05-03 10:28:15 +05:00
Leonid Bugaev 5779ea1b45 Update java middleware to not use apache commons 2016-05-02 16:31:38 +05:00
Leonid Bugaev bb0fab4d35 Update README.md 2016-04-30 18:35:51 +05:00
Leonid Bugaev 8cc377f22f Update README.md 2016-04-30 18:35:13 +05:00
Leonid Bugaev 5bea65c723 Fix input raw command line options 2016-04-29 21:44:50 +05:00
Leonid Bugaev 52a0ebfd57 Fmt fixes 2016-04-29 16:01:37 +05:00
Leonid Bugaev a8731f290c Fix broken pipe error 2016-04-29 16:01:30 +05:00
Leonid Bugaev 2f0e865e82 Fix middleware crashing for big payloads.
Fix #245 and #250
2016-04-29 15:34:38 +05:00
Leonid Bugaev afc8f7852e Libpcap support and vairous bugfixes
Merge #260
2016-04-29 14:48:17 +05:00
Leonid Bugaev 00feb08165 Add benchmark for testing packet capture (and its quality) 2016-04-26 17:18:09 +05:00
Leonid Bugaev 0754ed7d83 Merge pull request #239 from dougjohnson/output-http-debug
add flag to enable debugging of http output
2016-04-25 17:55:04 +06:00
Leonid Bugaev 4baf3985dc More debugging 2016-04-25 16:46:34 +05:00
Leonid Bugaev 32264eb427 Update README.md 2016-04-25 10:44:58 +05:00
Salimane Adjao Moustapha f2cedaf89f Merge pull request #256 from buger/revert-238-fix-memory-leak-in-aliases
Revert "Fixes memory leak by adding respAliases cleanup after expiration time"
2016-04-23 21:35:38 +02:00
Salimane Adjao Moustapha e8f7d30551 Revert "Fixes memory leak by adding respAliases cleanup after expiration time" 2016-04-23 21:17:54 +02:00
Salimane Adjao Moustapha 0c7643f477 Merge pull request #238 from AnderEnder/fix-memory-leak-in-aliases
Fixes memory leak by adding respAliases cleanup after expiration time
2016-04-23 20:23:11 +02:00
Salimane Adjao Moustapha 4c8a73a58b Merge pull request #235 from sneakybeaky/input_file_reader
Replace the use of bufio.Scanner with bufio.Reader
2016-04-23 20:20:42 +02:00
Leonid Bugaev 3d7455d6c1 Update README.md 2016-04-23 18:35:17 +05:00
Leonid Bugaev 3c40ac7ab6 Fix input dummy spec 2016-04-23 09:38:46 +05:00
Leonid Bugaev e0e065ba8a Fix license name 2016-04-23 09:36:33 +05:00
Leonid Bugaev fc1771ef70 Update README.md 2016-04-22 15:00:29 +05:00
Leonid Bugaev 5ec67ee88d Create COM-LICENSE 2016-04-22 14:21:41 +05:00
Leonid Bugaev 500d80d261 Update LICENSE.txt 2016-04-22 14:21:01 +05:00
Leonid Bugaev eb395ff815 Update README.md 2016-04-22 13:47:06 +05:00
Leonid Bugaev 538c05ec62 Merge pull request #255 from gitter-badger/gitter-badge
Add a Gitter chat badge to README.md
2016-04-22 14:45:56 +06:00
The Gitter Badger d99117c92b Add Gitter badge 2016-04-22 08:45:25 +00:00
Jon Barber e659f65d76 Replace the use of bufio.Scanner with bufio.Reader so that requests over 64Kb in size can be replayed from a capture file. 2016-04-21 10:15:48 +01:00
Andrii Radyk 7a2f1aef4c Merge remote-tracking branch 'upstream/master' into fix-memory-leak-in-aliases 2016-04-21 09:23:03 +02:00
Leonid Bugaev 6c410ab978 Update README.md 2016-04-21 11:51:33 +05:00
Leonid Bugaev a3403a3295 Update README.md 2016-04-21 11:49:19 +05:00
Leonid Bugaev cb4db10caf Update README.md 2016-04-21 11:48:58 +05:00
Leonid Bugaev 55405b6bfc Update README.md 2016-04-21 11:48:03 +05:00
Leonid Bugaev fecfa7f15f More listener tests 2016-04-21 10:34:08 +05:00
Leonid Bugaev eb6166724b Try to fix tests 2016-04-21 06:27:19 +05:00
Salimane Adjao Moustapha dbd8a48561 Merge pull request #237 from leejones/patch-1
Moved -output-http-redirects option description to a new line in README.md
2016-04-21 01:04:53 +02:00
Salimane Adjao Moustapha d6f5ac1c3d Merge pull request #241 from mortonfox/patch-1
Fix link to the 'too many open files' blog entry
2016-04-21 00:51:34 +02:00
Leonid Bugaev 334db15df9 Apply gofmt simplification 2016-04-20 22:03:19 +05:00
Leonid Bugaev d3e58ba374 Update README.md 2016-04-20 21:56:04 +05:00
Leonid Bugaev 7dee2dbefb Update README.md 2016-04-20 21:55:35 +05:00
Leonid Bugaev 1014abf878 Merge pull request #253 from buger/listener-tests
Listener tests, fix TravisCI builds, switch to 1.6
2016-04-20 22:49:42 +06:00
Leonid Bugaev fa11cc04c8 Explicitly set ip in tests 2016-04-20 21:44:37 +05:00
Leonid Bugaev 4cfa33f89c Fix tests and formatting 2016-04-20 21:40:18 +05:00
Leonid Bugaev a62f269d3e Try to use local ip in tests 2016-04-20 21:34:00 +05:00
Leonid Bugaev 7b2d7800b4 Merge remote-tracking branch 'origin/go-1.5' into go-1.5
# Conflicts:
#	Makefile
#	raw_socket_listener/listener.go
#	raw_socket_listener/listener_test.go
#	raw_socket_listener/tcp_message.go
2016-04-20 21:26:09 +05:00
Leonid Bugaev e5daaf067e Fix tests 2016-04-20 21:19:20 +05:00
Leonid Bugaev 9fc7cdc0d3 Add tests for listener and tcp_message 2016-04-19 20:43:54 +05:00
Leonid Bugaev 94f066c97a Merge pull request #246 from korzonek/master
codebeat badge
2016-03-10 16:29:34 +05:00
Tomasz Korzeniowski 7f27d60f8a codebeat badge
Is it fine to add codebeat badge to README? 

codebeat is automated code review tool for Swift,Ruby,Go & Python that helps get instant feedback on code quality. 

"Quick wins" suggested by codebeat could be a nice candidate for a pull request and help other developers become contributors.

FYI. To be fully open and honest. I'm co-founder of codebeat.
2016-03-10 11:40:55 +01:00
Morton Fox ad2bf0334c Fix link to the 'too many open files' blog entry 2016-02-01 16:24:44 -05:00
Doug Johnson 699eefe317 add flag to enable debugging of http output 2016-01-26 21:56:55 +00:00
Andrii Radyk 2a955dcdbf Fixes memory leak by adding respAliases cleanup after expiration time 2016-01-26 13:26:47 +01:00
Lee Jones 28f82b462e Update README.md
Moved `-output-http-redirects` option description to new line.
2016-01-22 16:12:57 -06:00
Leonid Bugaev 1fdcc54121 Merge pull request #225 from johanneswuerbach/middleware-failures
Handle middleware failures
2015-11-23 18:22:24 +01:00
Johannes Würbach 5378ecca71 Handle middleware failures
Without this the middleware might crash silently and gor keeps running
2015-11-23 17:54:52 +01:00
Leonid Bugaev 9d861af3a2 Merge pull request #219 from pbsurf/pbsurf/fix_crashes
fix crash on missing payload metadata
2015-11-18 11:32:19 +01:00
pbsurf 5c272661e9 fix crash on missing payload metadata 2015-11-04 20:40:44 +00:00
Leonid Bugaev a4c40cd8b4 Update README.md 2015-10-07 22:18:38 +03:00
Leonid Bugaev d23848167d Merge pull request #214 from bkochendorfer/itercepted
Fix small typo
2015-09-30 10:34:15 +03:00
Brett Kochendorfer 44506785cb Fix small typo 2015-09-29 15:11:51 -05:00
Leonid Bugaev bb2adbce65 Update travis 2015-09-24 17:21:16 +03:00
Leonid Bugaev 028bc6c34e Switch to Go 1.5 2015-09-24 17:20:49 +03:00
Leonid Bugaev 16c5b6f15b Merge pull request #210 from buger/support-non-rfc-headers
Handle headers added by bad clients
2015-09-23 16:53:49 +03:00
Leonid Bugaev 5cf8f7dfd0 Handle headers added by bad clients 2015-09-23 16:32:50 +03:00
Leonid Bugaev 2b522285c6 Fix 100-continue check for packets with data < 4 2015-09-05 16:48:39 +03:00
Leonid Bugaev 5dcec259d6 Add more debug 2015-09-04 17:44:14 +03:00
Leonid Bugaev 766bbc6127 Merge pull request #202 from buger/file-input-speed-fix
Fix file input replay speed
2015-09-03 21:55:09 +03:00
Leonid Bugaev 6d2a895db3 Fix file input replay speed 2015-09-03 21:50:32 +03:00
Leonid Bugaev d81e39d25c Improve test speed 2015-09-02 22:40:00 +03:00
Leonid Bugaev ed94985346 Merge pull request #201 from buger/tcp-gc
Improve raw input scheduler
2015-09-02 20:43:41 +03:00
Leonid Bugaev f378def0b3 Improve raw input GC 2015-09-02 20:33:12 +03:00
Leonid Bugaev cd83e6f9ba Formatting fixes 2015-09-01 22:43:36 +03:00
Leonid Bugaev 60ddd535bc Add test for large input-http payload 2015-09-01 22:43:04 +03:00
Leonid Bugaev 9ded255788 Merge pull request #195 from mre/patch-1
Fix some typos
2015-09-01 22:34:47 +03:00
Leonid Bugaev 323f85bcfb Merge pull request #194 from buger/fix-memory-leaks
Fix memory leaks
2015-09-01 22:21:13 +03:00
Leonid Bugaev 07a3c191d7 Speedup input-raw 2015-09-01 22:16:29 +03:00
Leonid Bugaev 4f3354507c Fix race 2015-09-01 22:10:06 +03:00
Leonid Bugaev 661dd2026f Fix grouting spawn loop and memory leaks 2015-09-01 20:27:26 +03:00
Leonid Bugaev 67505d99d8 Merge pull request #198 from justanshulsharma/fix-typo
Fix typo
2015-09-01 19:16:15 +03:00
Anshul Sharma ac0438995c Fix typo 2015-09-01 09:58:35 +05:30
Matthias Endler b5aa7d7c2d Fix some typos 2015-08-28 16:18:04 +02:00
Leonid Bugaev 8daa7fdcab Fix memory leaks 2015-08-26 22:25:58 +03:00
Leonid Bugaev 1fea397d54 Merge pull request #162 from buger/input-modifier
Middleware for custom request rewrite logic
2015-08-24 09:44:00 +03:00
Leonid Bugaev abde6ecfcb less verbose output 2015-08-24 09:40:15 +03:00
Leonid Bugaev 43262f3336 Increase timeouts 2015-08-24 09:32:31 +03:00
Leonid Bugaev fe91a20629 fix race 2015-08-24 09:24:31 +03:00
Leonid Bugaev 3c81723ac3 Increase timeout for large payload 2015-08-24 08:58:57 +03:00
Leonid Bugaev 929e027907 small formatting change 2015-08-23 13:08:51 +03:00
Leonid Bugaev f0b96af420 Add protection for malformed requests 2015-08-23 13:07:29 +03:00
Leonid Bugaev f3ea30c6df Add example of java echo middleware 2015-08-23 12:45:28 +03:00
Leonid Bugaev d5a1eb0b9d Increase input raw timeout 2015-08-22 11:37:01 +03:00
Leonid Bugaev 02bf7a86de Rollback to 1.4.2 in travis 2015-08-22 09:58:52 +03:00
Leonid Bugaev cbc27bd662 More debugging 2015-08-22 09:48:10 +03:00
Leonid Bugaev 16d7f23d98 New fixes 2015-08-22 09:41:22 +03:00
Leonid Bugaev 6533b50ab0 Travis should use 1.5 2015-08-20 09:51:44 +03:00
Leonid Bugaev 9309fb86ef Reduce debugging 2015-08-20 09:45:59 +03:00
Leonid Bugaev 76d5e22ba1 Enable packet debugging 2015-08-20 09:33:51 +03:00
Leonid Bugaev 81d3508653 Enable race testing for travis 2015-08-20 09:29:51 +03:00
Leonid Bugaev 3c45595a96 More race fixes 2015-08-20 09:27:44 +03:00
Leonid Bugaev 6974a6e278 Ensure that raw input gets closed 2015-08-20 08:56:10 +03:00
Leonid Bugaev 33cdcd4d13 Use httptest package and properly close servers 2015-08-20 07:28:13 +03:00
Leonid Bugaev 9550b31fde Fix plugin registration 2015-08-19 22:38:24 +03:00
Leonid Bugaev 6cb4c265dd Some debugging and race fixes 2015-08-19 21:46:45 +03:00
Leonid Bugaev e54f77f229 Try to return all responses 2015-08-19 09:27:16 +03:00
Leonid Bugaev 5d2f6eceea Fixes 2015-08-19 09:19:00 +03:00
Leonid Bugaev a6e29c684c Close connection 2015-08-18 21:25:56 +03:00
Leonid Bugaev 78456d6cd1 More timeout 2015-08-18 17:46:57 +03:00
Leonid Bugaev c4037e0c57 Increase travis timeout time 2015-08-18 17:42:55 +03:00
Leonid Bugaev 7cff78174a Remove verbose flag 2015-08-18 17:35:54 +03:00
Leonid Bugaev b53fba0415 Fix formatting issues 2015-08-18 17:28:09 +03:00
Leonid Bugaev d6c776fa0c Verbose output for travis 2015-08-18 17:27:26 +03:00
Leonid Bugaev ae35f88004 Remove magic numbers 2015-08-18 17:18:02 +03:00
Leonid Bugaev 8da4e54cbb Tcp communication should use same protocol as file based 2015-08-18 16:02:03 +03:00
Leonid Bugaev 7790b33cea Refactor protocol scanner 2015-08-18 15:52:23 +03:00
Leonid Bugaev a971d8a843 Change file format to be text based 2015-08-18 15:48:42 +03:00
Leonid Bugaev 3e763c43cf Unify all input/output plugins 2015-08-18 14:32:52 +03:00
Leonid Bugaev ea94dd0162 fmt changes 2015-08-18 08:20:08 +03:00
Leonid Bugaev d96e3393ec Handle HTTP error codes 2015-08-17 20:36:59 +03:00
Leonid Bugaev 69424bf670 Fix hound 2015-08-17 17:13:55 +03:00
Leonid Bugaev 211be0cddd Add request time and round-trip response time 2015-08-17 17:10:43 +03:00
Leonid Bugaev d1091102ba Ignore all release files 2015-08-15 21:46:09 +03:00
Leonid Bugaev 0d445722b9 Some fixes 2015-08-15 21:27:20 +03:00
Leonid Bugaev 879ed48b80 Doc changes 2015-08-15 21:05:51 +03:00
Leonid Bugaev ddd5190622 Improve docs 2015-08-15 21:05:10 +03:00
Leonid Bugaev a18079fa84 Improving docs 2015-08-15 10:33:50 +03:00
Leonid Bugaev 1a36374c2d Add some comments 2015-08-15 08:44:27 +03:00
Leonid Bugaev 41c1421a1b Simulate some real-life server by adding small response delay 2015-08-15 08:36:13 +03:00
Leonid Bugaev 4f2341b2d3 Remove more debug 2015-08-15 08:06:13 +03:00
Leonid Bugaev 56f0a3fcc0 Remove too verbose output 2015-08-15 07:57:25 +03:00
Leonid Bugaev 70e7d8dd29 Reduce delay of raw input 2015-08-14 23:07:46 +03:00
Leonid Bugaev bb319b5fd2 Add request ID and token modifier middleware 2015-08-14 20:42:23 +03:00
Leonid Bugaev 491541c2df Response object should be separate message 2015-08-13 22:11:23 +03:00
Leonid Bugaev 2990fab635 Track original responses 2015-08-11 17:37:37 +03:00
Leonid Bugaev 8046468ea4 Fix tests 2015-08-11 11:28:22 +03:00
Leonid Bugaev 0009555d96 Apply fmt 2015-08-11 11:08:14 +03:00
Leonid Bugaev 5098e388a2 Fix tests, now properly receive responses 2015-08-11 11:06:25 +03:00
Leonid Bugaev 5667cd35c6 Merge branch 'master' into input-modifier 2015-08-10 22:57:33 +03:00
Leonid Bugaev 9ab8b3c113 Add header to request and response 2015-08-10 22:57:18 +03:00
Leonid Bugaev 5e526af47b Set version dynamically via ldflags 2015-08-10 20:26:37 +03:00
Leonid Bugaev 3a7badc508 Merge pull request #190 from buger/fix-default-port
Fix default port
2015-08-09 11:13:10 +03:00
Leonid Bugaev 9a76e354c5 Fix tcp input test 2015-08-09 11:08:53 +03:00
Leonid Bugaev d6b5c675cf Do not add 80 port to host string 2015-08-09 11:07:27 +03:00
Leonid Bugaev de6c41c731 Update docs for Host header 2015-08-06 09:34:51 +03:00
Leonid Bugaev 08933e148a Merge pull request #188 from SaraRands/master
Added --http-original-host command line flag
2015-08-06 09:24:50 +03:00
SaraRands 259b70a7df Added --http-original-host flag 2015-08-05 14:05:59 -06:00
Leonid Bugaev 35854196f0 Fix tests 2015-08-03 20:07:28 +03:00
Leonid Bugaev a9be1811ea Merge branch 'master' into input-modifier
Conflicts:
	Makefile
2015-08-03 19:59:03 +03:00
Leonid Bugaev 9185453453 Merge pull request #176 from dt/dt.hexdecode
Avoid trailing null on hex encoded TCP
2015-08-03 18:38:53 +03:00
Leonid Bugaev 87ad851ad8 Merge pull request #185 from buger/fix-large-response
Fix large responses
2015-08-03 18:36:09 +03:00
Leonid Bugaev ce193d0d4f Fix travis config 2015-08-03 18:33:36 +03:00
Leonid Bugaev f92a0b1242 Make buffer size configurable 2015-08-03 18:31:09 +03:00
Leonid Bugaev f6864d05a0 More debugging 2015-08-03 18:20:59 +03:00
Leonid Bugaev 3316447bf5 Verbose output for travis 2015-08-03 18:13:36 +03:00
Leonid Bugaev 961d5a754c Style fixes 2015-08-03 18:08:35 +03:00
Leonid Bugaev dd68d07c75 Fix large responses 2015-08-03 18:01:46 +03:00
David Taylor 5c46db9220 avoid trailing null in encoded tcp
Fixes #175.
2015-07-31 21:13:46 +00:00
David Taylor ed7c5210be Print warning if hex decoding fails 2015-07-31 21:09:24 +00:00
Leonid Bugaev 00ad6bd92b Merge pull request #183 from buger/configurable-timeout
Option to configure timeout
2015-07-31 22:42:19 +03:00
Leonid Bugaev 587b9ad2d5 Update Readme 2015-07-31 22:41:32 +03:00
Leonid Bugaev 083c97a9c4 Option to configure timeout 2015-07-31 22:39:01 +03:00
Leonid Bugaev 8f2e9bd1dc Merge pull request #182 from buger/fix-set-header
Do not override http Host header  if it explicitly set via options
2015-07-31 21:42:41 +03:00
Leonid Bugaev a79e54c5f1 Do not set http header if it explicitly set 2015-07-31 21:41:06 +03:00
Leonid Bugaev 27f83a6c0c Improve debugging 2015-07-31 21:08:35 +03:00
Leonid Bugaev 5158f75dc8 Merge pull request #178 from jakubholynet/patch-1
Readme: Explain when `--stats` needs to be included
2015-07-30 15:09:32 +03:00
Jakub Holy 126957c599 Readme: Explain when --stats needs to be included
It isn't intuitive that when I specify e.g. `--output-http-stats`, it isn't enough and I need to explicitly enable also `--stats` (and that `--stats` on its own does not do anything, you need other flags to specify what to output)
2015-07-30 10:15:56 +02:00
Leonid Bugaev d62eccb655 Make raw message expiration configurable to improve tests time 2015-07-21 10:06:10 +05:00
Leonid Bugaev 5cc4228dcd Merge branch 'master' into input-modifier
Conflicts:
	Dockerfile
	emitter.go
	http_client.go
	plugins.go
	proto/proto.go
2015-07-21 09:49:37 +05:00
Leonid Bugaev 5e6f7e03a7 First middleware tests! :dance: 2015-07-17 20:58:31 +05:00
Leonid Bugaev 0a30582131 Fix tests by adding small delay 2015-07-17 12:57:36 +05:00
Leonid Bugaev 5c21600bf9 Fix timeout 2015-07-17 12:12:04 +05:00
Leonid Bugaev 107982394e Run all tests 2015-07-17 11:47:41 +05:00
Leonid Bugaev ac3e209787 One more fix 2015-07-17 11:38:42 +05:00
Leonid Bugaev e5d9f73937 Fix tests 2015-07-17 11:36:18 +05:00
Leonid Bugaev df3b410e98 Merge pull request #171 from buger/code-styling
Improve code documentation and styling
2015-07-17 11:33:26 +05:00
Leonid Bugaev 125d9db834 Next batch 2015-07-17 11:30:43 +05:00
Leonid Bugaev 6147e14f88 Merge pull request #173 from rgarcia/http-disallow-header
add --http-disallow-header option
2015-07-17 08:30:32 +05:00
Rafael Garcia fa003f5fec add --http-disallow-header option 2015-07-17 03:26:06 +00:00
Leonid Bugaev 28540f43a1 New portion of changes 2015-07-13 16:56:52 +05:00
Leonid Bugaev 6158ee3025 Remove debug 2015-07-13 16:20:57 +05:00
Leonid Bugaev 0859642b38 Update raw listener 2015-07-13 16:19:24 +05:00
Leonid Bugaev 32081b2d17 Improve byteutils 2015-07-13 09:36:54 +05:00
Leonid Bugaev 6647481fe0 Improve style and docs for proto package 2015-07-13 09:31:11 +05:00
Leonid Bugaev 0551b19ddd Add linter task 2015-07-12 19:08:12 +05:00
Leonid Bugaev a5f2d2fd6d Update README.md 2015-07-12 08:53:59 +05:00
Leonid Bugaev f1c341e2ac Update README.md 2015-07-12 08:52:59 +05:00
Leonid Bugaev becb4b958f Delete CHANGELOG.md 2015-07-12 08:47:39 +05:00
Leonid Bugaev db7f5c6a9c Update to use go 1.4.2 2015-07-11 19:34:20 +05:00
Leonid Bugaev 7af0eb2d65 Merge pull request #170 from buger/input-raw-performance
Improve performance of input-raw and improve handing of large payloads
2015-07-11 19:19:13 +05:00
Leonid Bugaev 32d0557a28 Reduce test file size 2015-07-11 19:07:35 +05:00
Leonid Bugaev 6ba0bfc614 Fix tests runner 2015-07-11 18:57:00 +05:00
Leonid Bugaev 34fe137d19 Improve message_id to handle multiple ports 2015-07-11 18:54:41 +05:00
Leonid Bugaev bb74704f9d Rollback to use net package 2015-07-11 18:46:35 +05:00
Leonid Bugaev d0873d1453 Try to add select 2015-07-11 18:36:00 +05:00
Leonid Bugaev 313c382adb By default use all cores 2015-07-11 09:58:10 +05:00
Leonid Bugaev 6b9c9b91e3 Improve performance of input-raw and improve handing of large payloads 2015-07-11 09:47:26 +05:00
Leonid Bugaev 531bd1da67 Merge pull request #169 from buger/http-client-bugfixes
Improve http-client reliability and improve debug
2015-07-10 17:19:06 +05:00
Leonid Bugaev acaf935cae Fix tests 2015-07-10 17:17:16 +05:00
Leonid Bugaev 0fe72cc432 Improve http-client reliability and improve debug 2015-07-10 17:13:11 +05:00
Leonid Bugaev f812120dfc Support only 1 middleware and rewrite tests 2015-07-10 10:24:00 +05:00
Leonid Bugaev e64aac9364 Rename input modifier to middleware 2015-07-09 20:24:27 +05:00
Leonid Bugaev 8db14e334d Merge branch 'master' into input-modifier
Conflicts:
	Dockerfile
	Makefile
	output_http.go
	output_http_test.go
	settings.go
2015-07-09 19:58:24 +05:00
Leonid Bugaev b38cb458ff Update version 2015-07-09 18:45:39 +05:00
Leonid Bugaev d380b71945 Merge pull request #165 from buger/refactor-settings
Settings improvements
2015-07-09 18:41:29 +05:00
Leonid Bugaev fd5388b6c9 Improve README 2015-07-09 18:39:07 +05:00
Leonid Bugaev 48492dc8cb Allow url param rewriting 2015-07-09 16:58:42 +05:00
Leonid Bugaev 29035d4518 Allow multiple url regexp and apply fmt 2015-07-09 16:05:00 +05:00
Leonid Bugaev 1ce10249be Percent based syntax for hash filters 2015-07-09 15:44:15 +05:00
Leonid Bugaev 5a23573cfe Add --http-allow-param-hash 2015-07-09 15:30:06 +05:00
Leonid Bugaev 413f50129f Add support for restricting certain urls 2015-07-08 20:27:35 +05:00
Leonid Bugaev 686d7436ae Merge setting files 2015-07-08 20:09:43 +05:00
Leonid Bugaev 18c0473239 Merge pull request #164 from buger/change-tcp-output-format
Change internal message format
2015-07-08 19:12:25 +05:00
Leonid Bugaev 4d00ff8757 Change internal message format 2015-07-08 19:07:50 +05:00
Leonid Bugaev 8f73233717 Merge pull request #163 from buger/fix-proxy-set-host
Handle proxy request format and HTTP 1.0 requests
2015-07-08 18:40:12 +05:00
Leonid Bugaev 07c65117ad Handle proxy request format and HTTP 1.0 requests 2015-07-08 18:26:14 +05:00
Leonid Bugaev 31fa612fef Add go tool coverage make task 2015-07-07 08:29:49 +05:00
Leonid Bugaev 9ddb718525 Merge pull request #160 from buger/raw-http-client
Send unmodified http request
2015-07-06 21:43:47 +05:00
Leonid Bugaev 4f114f067b Apply fmt 2015-07-06 21:09:06 +05:00
Leonid Bugaev 9a0d9166c3 Yay! http.Client replaced by own simple http client 2015-07-06 21:08:34 +05:00
Leonid Bugaev bc48e1ad49 Fix tests 2015-07-06 18:56:50 +05:00
Leonid Bugaev 53c27cf374 Add Header Modifier tests 2015-07-06 18:53:54 +05:00
Leonid Bugaev a859ae02ad More tests and simplify hashFilter 2015-07-06 18:36:12 +05:00
Leonid Bugaev 2b17989fd9 Move HTTP modifier from HTTP output plugin 2015-07-05 23:17:57 +05:00
Leonid Bugaev 96fd713453 Use separate config for modifier 2015-07-05 10:25:44 +05:00
Leonid Bugaev 43fd14b561 Merge pull request #159 from whitekid/master
add .dockerignore file
2015-07-05 10:02:52 +05:00
Leonid Bugaev 72b15db93f Add utilities for modifying HTTP payload 2015-07-05 09:42:59 +05:00
Leonid Bugaev 557cdbebb6 Update README.md 2015-07-04 22:05:23 +05:00
Leonid Bugaev 925ff151dc Update README.md 2015-07-04 19:59:14 +05:00
Leonid Bugaev 481e4f2e74 Refactor http output settings 2015-07-02 23:08:31 +05:00
Leonid Bugaev 416586a365 Add support for redirects 2015-07-02 20:41:25 +05:00
Leonid Bugaev a08ecc79fc Add support for timeouts and servers closing connections 2015-07-02 18:33:38 +05:00
Leonid Bugaev decb9483a5 Fix docker file path 2015-07-02 10:25:47 +05:00
Leonid Bugaev 21c544ef67 Fix tests and apply go fmt 2015-07-01 19:29:19 +05:00
Leonid Bugaev 122f06f6c2 Add raw http client 2015-07-01 19:06:49 +05:00
Choe, Cheng-Dae 3d3c6a34b1 add .dockerignore 2015-06-30 21:34:42 +09:00
Leonid Bugaev 04d727915d Merge pull request #158 from buger/fix-100-expect
Fix Expect: 100-continue requests and refactor chunked encoding
2015-06-29 17:29:59 +05:00
Leonid Bugaev 1e7b603ae0 Fix import path 2015-06-29 17:14:11 +05:00
Leonid Bugaev 41294f9470 Fix 100-Expect requests and refactor chunked encoding 2015-06-29 17:01:26 +05:00
Leonid Bugaev 3e86456e36 Add more debug 2015-06-28 22:00:55 +05:00
Leonid Bugaev 98f941b69a Add support for complex commands 2015-06-28 00:23:21 +05:00
Leonid Bugaev 674ffc6202 Start adding tests for traffic modifier 2015-06-28 00:16:19 +05:00
Leonid Bugaev 4f03f81d04 Working modifier implementation with examples 2015-06-27 21:09:06 +05:00
Leonid Bugaev dcb8a1dee4 Merge branch 'master' into input-modifier 2015-06-26 10:04:46 +05:00
Leonid Bugaev 451a1cd11a Update version number 2015-06-26 10:02:31 +05:00
Leonid Bugaev 6fe7ba8e86 Merge pull request #157 from buger/encoding-chunked
Handle Transfer-Encoding: chunked
2015-06-26 09:19:02 +05:00
Leonid Bugaev 534e9b29fa Merge branch 'master' into encoding-chunked
Conflicts:
	output_http.go
2015-06-26 09:12:29 +05:00
Leonid Bugaev 390f75fd3c Handle Transfer-Encoding: chunked 2015-06-26 09:08:16 +05:00
Leonid Bugaev a059648008 Merge pull request #150 from makern/64bit-align
Fix alignment crash on i386
2015-03-23 13:33:39 +05:00
Markus Kern b2e1eea6bf Fix alignment crash on i386 2015-03-22 21:22:44 +00:00
Leonid Bugaev 92ba321569 Merge pull request #148 from MartinNowak/pow2
simplify power of 2 test
2015-03-19 17:37:53 +05:00
Martin Nowak 2b497e6177 simplify power of 2 test 2015-03-19 11:08:49 +01:00
Leonid Bugaev 09f9cac6fb Merge pull request #145 from tarfu/master
Introduce possibility to enable redirects.
2015-03-15 08:40:29 +05:00
Tobias Breitwieser d05bc0d5e9 Introduce possibility to enable redirects. 2015-03-14 16:47:04 +01:00
Leonid Bugaev 1c0182188c Merge pull request #143 from falzm/fix-socket-perm-crash
Prevent crash if no permissions on port
2015-03-06 16:13:12 +05:00
Marc Falzon cef8b75496 Prevent crash if no permissions on port
This fix prevents Gor from crashing at startup if run without proper
permissions for listening on specified port.
2015-03-05 21:58:52 +01:00
Leonid Bugaev e9fd5eb273 Merge pull request #141 from wmoss/master
Properly handle errors on input sockets
2015-03-03 12:00:55 +05:00
Will Moss 85fbfff308 Properly handle errors on input sockets
`buf` is of length 0, so you never make it into
the loop to handle the errors. This means you end
up in a tight loop calling `ReadBytes` and always
getting back `io.EOF` and 0 bytes.
2015-03-02 21:52:40 -08:00
Leonid Bugaev a7aaf7df65 Merge pull request #140 from wmoss/master
Properly return from errors from ReadRequest
2015-02-28 09:57:33 +05:00
Will Moss c1c87ed4e2 Properly return from errors from ReadRequest 2015-02-26 16:07:52 -08:00
Leonid Bugaev 072f332956 Merge pull request #138 from wmoss/master
Make TCPOutput more robust to failures
2015-02-23 09:05:18 +05:00
Will Moss 7c68920a3b Make TCPOutput more robust to failures
This should allow for running a gor listener on a
production box and bringing up and down the replay
node without having to go restart the listener.
2015-02-22 15:49:35 -08:00
Leonid Bugaev b6351a8525 Fix travis test runner 2015-02-22 14:19:48 +05:00
Leonid Bugaev f557d412c4 Merge pull request #133 from buger/fix-post-requests
Fix POST requests
2015-01-11 20:04:23 +05:00
Leonid Bugaev ed5c2215f5 Fix POST requests 2015-01-06 17:50:36 +05:00
Leonid Bugaev 208faec7d2 Initial support for input modifiers 2014-12-16 16:25:17 +05:00
Leonid Bugaev ffe1646d8e Merge pull request #131 from chmac/patch-1
Minor typo correction
2014-12-07 20:37:26 +05:00
Callum Macdonald ae293320ad Minor typo correction 2014-12-07 16:20:49 +01:00
Leonid Bugaev eb7885cd56 Patch from @jcw9930
See https://github.com/buger/gor/pull/127#issuecomment-64538157
2014-11-26 16:30:17 +05:00
Leonid Bugaev b6977df90d Merge pull request #127 from jcw9930/url_regexp_rewrite
add regular expression matching to --output-http-rewrite-url
2014-10-29 15:24:42 +05:00
Jan Willies 15417894a9 add test that explicitly checks if rewrites.Rewrite(url) == /v2/user/joe/ping 2014-10-28 18:42:38 +01:00
Jan Willies 7f49314ec7 allow matched parts in -output-http-rewrite-url 2014-10-28 18:12:21 +01:00
Jan Willies 80572f5f18 add regular expression matching to --output-http-rewrite-url 2014-10-28 14:52:55 +01:00
Leonid Bugaev b7567bbd15 It should be 0.9.2 version 2014-10-27 16:42:48 +05:00
Leonid Bugaev e4b7c8c763 Merge pull request #126 from buger/limiter-extraction
Limiter improvements
2014-10-27 16:41:33 +05:00
Leonid Bugaev 62ced2e1ba Update version 2014-10-27 16:41:07 +05:00
Leonid Bugaev 79ed6a7548 Fix absolute limiting for file input 2014-10-26 21:21:00 +03:00
Leonid Bugaev 3793a84e59 Add docs on load testing using input-file 2014-10-26 15:08:29 +03:00
Leonid Bugaev f2cf81c5bf FileInput should have own limiter algorithm 2014-10-26 15:00:00 +03:00
Leonid Bugaev aae57733a8 Fix limiter for readers 2014-10-26 13:54:42 +03:00
Leonid Bugaev 00df525b6a Update docs 2014-10-26 13:33:06 +03:00
Leonid Bugaev 7864808e5e Some formatting fixes 2014-10-26 13:25:18 +03:00
Leonid Bugaev 58c7e12d1f Add percentage based limiting 2014-10-26 13:23:17 +03:00
Leonid Bugaev de143e4268 Make limiter work for Inputs 2014-10-26 13:07:10 +03:00
Leonid Bugaev 67cfca0ede Make limiter work for all inputs/outputs 2014-10-26 01:02:49 +04:00
Leonid Bugaev 43920a96c0 Added docs on running single test 2014-10-25 21:14:08 +04:00
Leonid Bugaev 4cf3bf0ae4 Refactor plugin registration 2014-10-25 21:08:54 +04:00
Leonid Bugaev 095c717f6a Update README.md 2014-10-21 15:43:53 +04:00
Leonid Bugaev abc44c2fa5 Fix tcp_message typo 2014-10-13 20:24:07 +04:00
Leonid Bugaev 2d66ccc62d Add limiter support to output-file 2014-10-13 19:37:43 +04:00
Leonid Bugaev b257231d51 Ensure that channel not closed 2 times in row
Fix #114
2014-10-13 19:24:42 +04:00
Leonid Bugaev 1cab1ecb0e Add EmitFile for test purpose 2014-10-13 18:54:47 +04:00
Leonid Bugaev 983bc728fa Increase buffer to 5 megabytes 2014-10-13 18:26:08 +04:00
Leonid Bugaev 4b592e0e2d Fix Makefile (it should use tabs) 2014-10-13 18:08:37 +04:00
Leonid Bugaev 1637dd491f Convert tabs to spaces and force go fmt 2014-10-13 18:05:16 +04:00
Leonid Bugaev 9e63fb5b36 Merge pull request #125 from buger/add-http-input
Add http input
2014-10-13 18:01:12 +04:00
Leonid Bugaev 04a8cceb35 Updated docs 2014-10-13 17:59:32 +04:00
Leonid Bugaev 6ddf4df21a Add comment to make 2014-10-13 17:42:08 +04:00
Leonid Bugaev 51f5a3e9ec Merge branch 'master' into add-http-input 2014-10-13 17:38:27 +04:00
Leonid Bugaev 4c0c9e97c5 Add http input 2014-10-13 17:37:22 +04:00
Leonid Bugaev 4f64b71adb Merge pull request #124 from buger/workers-pool-refactoring
Refactor http output
2014-10-13 16:52:06 +04:00
Leonid Bugaev be7e27010d Refactor http output 2014-10-13 15:24:43 +04:00
Leonid Bugaev 758995d8f5 Fix main goroutine 2014-10-09 23:16:56 +04:00
Leonid Bugaev 5f883e08ce Run race detection for tests 2014-10-09 22:45:15 +04:00
Leonid Bugaev 3a43e697d5 Update release task to work with docker 2014-10-09 13:43:12 +04:00
Leonid Bugaev 468d94610f Merge branch 'DamianZaremba-url-rewrite2' 2014-10-09 12:29:17 +04:00
Leonid Bugaev d0266303d1 Merge #119 2014-10-09 12:29:02 +04:00
Leonid Bugaev 82ed628d45 Merge pull request #112 from buger/rollback-elastic-search
Rollback Elasticsearch
2014-10-09 11:53:59 +04:00
Leonid Bugaev 97dd1520f1 Update README.md 2014-10-09 11:53:30 +04:00
Leonid Bugaev 972a80356d Add go get call to travisci 2014-10-09 11:44:27 +04:00
Leonid Bugaev 91a0282755 Update go version 2014-10-09 11:43:51 +04:00
Leonid Bugaev 2c03d3ee28 Run go get for docker image, and fix make file 2014-10-09 11:41:03 +04:00
Leonid Bugaev b2f90789d2 Instead of godep just clone elasticgo repo 2014-10-09 11:37:00 +04:00
Leonid Bugaev e68332b897 Update README.md 2014-10-08 21:10:34 +04:00
Leonid Bugaev cf0dfecac2 Merge pull request #116 from joekiller/scale_http_output_squash
Scale http output squash
2014-10-08 20:48:58 +04:00
Joseph Lawson 4f9c983bc7 Dynamic scaling by default 2014-10-05 20:03:50 -04:00
Joseph Lawson 988c6abdad Dynamic workers toggle. Separate stats toggles. README and FAQs
* Created separate toggles for output-http-stats and output-tcp-stats
  * Created HTTPWorkers option (defaults to 10) to allow larger number of HTTPWorkers to be spawned.
  * Refactored output_http to allow dynamic http worker scaling when httpworkers equals -1
  * Updated README.me to include updates and some common FAQs.
2014-10-05 15:53:50 -04:00
Damian Zaremba 864723fe47 First go at a basic test 2014-09-28 13:23:47 +01:00
Damian Zaremba 2c2d5439bf Add in --output-http-rewrite-url option 2014-09-28 01:15:18 +01:00
Leonid Bugaev c04b2528b8 Merge pull request #115 from Blank101/filefix
fixed file input sleep timer
2014-09-25 10:34:08 +04:00
Joseph Lawson 58944fd42d calling this version 0.9.0 2014-09-24 14:57:49 -04:00
Joseph Lawson 6e125a7b7b allow dynamic http workers with a signal channel for full queue 2014-09-24 14:31:16 -04:00
Sam MacPherson 1a7cf2bbab fixed file input sleep timer 2014-09-23 16:54:26 -04:00
Leonid Bugaev e022fdff98 Update travisci config 2014-09-04 23:41:05 +04:00
Leonid Bugaev c0dc1b3a53 Rollback elastic search, use godep for dependencies 2014-09-04 23:35:56 +04:00
Leonid Bugaev 674d6036d1 Revert "Remove elastic search functionality"
This reverts commit cd27667246.
2014-09-04 22:48:08 +04:00
Leonid Bugaev 6f6c6aba95 Fix readme 2014-09-04 22:43:10 +04:00
Leonid Bugaev 2a6e9f7a92 Merge pull request #111 from buger/docker-dev
Add Docker development environment
2014-09-04 22:35:50 +04:00
Leonid Bugaev 007e0f3019 Add Docker development environment 2014-09-04 22:32:58 +04:00
Leonid Bugaev 115a37e0e9 Update README.md 2014-08-21 16:39:45 +04:00
Leonid Bugaev b2c87ff2a4 Add TomTom to companies using Gor 2014-08-21 16:38:34 +04:00
Leonid Bugaev 3a1efccbca Update README.md 2014-08-20 21:11:26 +04:00
Leonid Bugaev a2873116a3 Update README.md 2014-08-20 21:10:58 +04:00
Leonid Bugaev ccb309170f Merge pull request #108 from matzhouse/master
gor issue 74
2014-08-12 12:44:59 +04:00
Mat Evans defc017ade Add a testable SetHeader function with associated tests
It seemed easier to pull this bit of functionality out and be able to test it on it's own than rely on the whole http tests
2014-08-07 10:22:04 +01:00
Mat Evans 9e2f7feec7 gor issue 74
explicitly set the Host on the request when using the --output-http-header option
2014-07-31 11:40:40 +01:00
Leonid Bugaev c56bbd98ce Merge pull request #107 from buger/readme_host_header
Remove example of injecting Host header
2014-07-30 14:29:13 +04:00
Dan Carley 787a906bb8 Remove --output-http-header typo from README
The ` -header "` was extraneous.
2014-07-30 07:50:23 +01:00
Dan Carley d608d18057 Remove example of injecting Host header
This doesn't work per the discussion in #74. So we shouldn't document it.
2014-07-30 07:49:03 +01:00
Leonid Bugaev cd27667246 Remove elastic search functionality 2014-07-22 22:50:04 +04:00
Leonid Bugaev bae1a84f40 Update README.md 2014-07-22 22:33:55 +04:00
Leonid Bugaev 057e642b87 Updated build instructions 2014-06-26 14:26:07 +04:00
Leonid Bugaev c94cc88608 Merge pull request #99 from mantasmatelis/filter-regex-and-header
Allow filtering by regex of URL or specific header, consistent filtering by hash of header
2014-06-19 18:48:42 +04:00
Mantas Matelis 731a3745a4 Add tests 2014-06-18 12:24:53 -04:00
Mantas Matelis c4307b750a Documentation and test fixes 2014-06-12 11:43:04 -04:00
Mantas Matelis 9d341738de Fix readme spacing 2014-06-11 15:46:39 -04:00
Mantas Matelis c8d623580a Update readme 2014-06-11 15:42:36 -04:00
Mantas Matelis 2e29e3ab9e Regex on string, not byte array 2014-05-27 17:26:28 -04:00
Mantas Matelis bf786e5922 minor changes 2014-05-27 15:18:24 -04:00
Mantas Matelis a9a08860b4 less, not greater 2014-05-27 14:58:49 -04:00
Mantas Matelis c6c021d65f Further fmting 2014-05-27 14:51:11 -04:00
Mantas Matelis 49da801b33 go fmt personal files 2014-05-27 14:50:21 -04:00
Mantas Matelis a4a4c605a5 Remove log statements 2014-05-27 14:45:17 -04:00
Mantas Matelis 11d9531829 Add ability to filter output_http by headers/regex
Can filter output_http by percentage of requests, constistent with a specific header value (FNV32-a hash-based)
Can filter output_http to those with header matching a specific regexp
Can filter output_http to those whose URL matches a specfic regexp
2014-05-27 14:23:51 -04:00
Leonid Bugaev a6af811c50 Merge pull request #95 from joekiller/queue_stats_output
Queue stats output
2014-04-24 14:04:26 +06:00
Joseph Lawson 7bf6ca4c87 adding count stat 2014-04-23 16:25:22 -04:00
Joseph Lawson 31aef9ee1d adding count stat 2014-04-23 16:22:27 -04:00
Joseph Lawson 41fe11c12f added output_tcp queue stats 2014-04-23 16:06:29 -04:00
Joseph Lawson 4720070996 finished stat for output_http 2014-04-23 14:05:42 -04:00
Joseph Lawson dbfea7ceac as many workers are their are channel 2014-04-23 14:02:33 -04:00
Joseph Lawson c49c19428d as many workers are their are channel 2014-04-23 12:58:41 -04:00
Joseph Lawson 7bf2015e90 fixing stat output 2014-04-23 12:52:01 -04:00
Joseph Lawson db14154eb9 fix typo 2014-04-23 12:48:18 -04:00
Joseph Lawson b52d562dad tweaking stat output 2014-04-23 12:47:16 -04:00
Joseph Lawson 9461217a0e write stat help when init 2014-04-23 12:43:15 -04:00
Joseph Lawson 40d835e143 update rate types 2014-04-23 12:23:15 -04:00
Joseph Lawson c97f02ff4c updated stat printer 2014-04-23 12:22:47 -04:00
Joseph Lawson 62254b6265 updated stat printer 2014-04-23 12:20:43 -04:00
Joseph Lawson d5535ee7f3 fixing pointers 2014-04-23 11:50:23 -04:00
Joseph Lawson 959ac29661 fixing pointers 2014-04-23 11:48:49 -04:00
Joseph Lawson b5c2d7747c fixing pointers 2014-04-23 11:47:06 -04:00
Joseph Lawson 610552be88 fixing stat errors 2014-04-23 11:45:39 -04:00
Joseph Lawson c250c3e30c add gor_stat 2014-04-23 11:34:51 -04:00
Leonid Bugaev ce5ee74d74 Merge pull request #94 from joekiller/sort_tcp_packets
Sort tcp packets
2014-04-23 20:19:43 +06:00
Joseph Lawson c4d0eb0ae1 revert accidental channel call 2014-04-22 19:58:39 -04:00
Joseph Lawson 840ca61de9 update input raw import 2014-04-22 16:22:30 -04:00
Joseph Lawson 5cb3562796 Merge branch 'can_not' into sort_tcp_packets 2014-04-22 16:21:02 -04:00
Joseph Lawson 384b3c5614 Merge branch 'message_sort_fix' into realistic_message_timeout 2014-04-22 16:07:35 -04:00
Joseph Lawson e97827d600 capping at 2 second maximum 2014-04-22 16:05:00 -04:00
Joseph Lawson 3eed7c2546 send message closed notification if channel closes. 2014-04-22 16:02:40 -04:00
Joseph Lawson fa8f612a4f 20 second timeout on a message 2014-04-22 14:01:34 -04:00
Joseph Lawson b00ea39d3e apache maximum timeout 2014-04-22 13:52:17 -04:00
Joseph Lawson 06b4892b33 switch raw socket listener 2014-04-22 13:42:05 -04:00
Joseph Lawson 06b08105bf 20 second message timeout 2014-04-22 13:37:36 -04:00
Joseph Lawson 8ccc0249ca typo fix. 2014-04-22 11:46:19 -04:00
Joseph Lawson e9bb6ef8f3 added sort by Seq for packets, updated Bytes to return data based on sorted t.packets 2014-04-22 11:06:16 -04:00
Joseph Lawson adf7ed6b84 return packets in Seq order 2014-04-22 10:45:05 -04:00
Joseph Lawson 0dc315b343 set m[k] from packets based on the Seq index 2014-04-21 15:43:06 -04:00
Joseph Lawson 48ae0e6812 wrap through the range of packets 2014-04-21 15:38:48 -04:00
Joseph Lawson 0d398dbf3d convert to proper int 2014-04-21 15:36:05 -04:00
Joseph Lawson e373073742 switch raw socket listener to local 2014-04-21 15:29:57 -04:00
Joseph Lawson 296034ef00 make message sort by packet's index 2014-04-21 15:29:21 -04:00
Joseph Lawson a786c78d26 Merge remote-tracking branch 'upstream/master' 2014-04-21 15:27:13 -04:00
Leonid Bugaev ed68b27153 Merge pull request #91 from MandaBrown/the-tiniest-typo-fix
Fixes a tiny typo in the README.
2014-04-14 10:20:29 +06:00
Mandy Brown e6fe38cfda Fixes a tiny typo in the README. 2014-04-13 21:45:26 -04:00
Joseph Lawson 441f0ade04 Merge remote-tracking branch 'upstream/master'
Conflicts:
	emitter.go
2014-04-02 14:50:17 -04:00
Leonid Bugaev 8d8c10f3ea Update .travis.yml 2014-04-02 17:24:04 +06:00
Leonid Bugaev fc52decebf Merge pull request #70 from buger/catch_redirect_errors
Catch RedirectNotAllowed correctly
2014-04-02 14:55:41 +06:00
Leonid Bugaev f5d74e84f6 Merge pull request #88 from joekiller/prebuf
Fix TCP Issues
2014-04-02 14:52:39 +06:00
Joseph Lawson 983eb7c6a8 revert buf 2014-04-01 15:42:11 -04:00
Joseph Lawson 8edbb7fb08 new buffer each loop 2014-04-01 15:40:30 -04:00
Joseph Lawson 89f1b50b8d new_buf_len needs to be > 0 as we already account for the control character. 2014-03-31 15:42:00 -04:00
Joseph Lawson 9b0153f45f prevent crash on quits 2014-03-31 11:43:33 -04:00
Joseph Lawson 832bff26d1 update input_tcp_test to reflect new way of sending messages 2014-03-31 10:48:13 -04:00
Joseph Lawson 3d3cb1dbf5 fixed a reader bug 2014-03-29 18:52:42 -04:00
Joseph Lawson ca952b7a8b overflow fix 2014-03-29 18:42:11 -04:00
Joseph Lawson 872a4dcae9 Update output_tcp_test.go 2014-03-29 18:38:41 -04:00
Joseph Lawson b70290274e Update output_tcp_test.go 2014-03-29 18:33:19 -04:00
Joseph Lawson 787d92d94a attempt to fix test 2014-03-29 18:23:14 -04:00
Joseph Lawson ae5f7e48b0 revert timeout change 2014-03-29 00:36:40 -04:00
Joseph Lawson 29deb996bd copy data buffer 2014-03-28 23:41:02 -04:00
Joseph Lawson 02fe5a976f Merge branch 'tcp_input_fix' of github.com:joekiller/gor into tcp_input_fix 2014-03-28 23:40:37 -04:00
Joseph Lawson c8e39b8f47 correct delimiter append 2014-03-28 23:40:28 -04:00
Joseph Lawson c5150cd911 fix append 2014-03-28 23:36:38 -04:00
Joseph Lawson 7a657e273e Merge branch 'tcp_input_fix' of github.com:joekiller/gor into tcp_input_fix
Conflicts:
	output_tcp.go
2014-03-28 23:35:55 -04:00
Joseph Lawson cc2dd53de8 write full message to new array for async buffer 2014-03-28 23:31:30 -04:00
Joseph Lawson cad94ead29 write full message to new array for async buffer 2014-03-28 23:21:47 -04:00
Joseph Lawson 28f7078dbb make tcpinput use readbytes and create new slice prior to copying to the buffer. 2014-03-28 23:09:49 -04:00
Joseph Lawson 841bba116a revert overflow check 2014-03-28 22:59:05 -04:00
Joseph Lawson 3a3ae5b283 revert overflow check 2014-03-28 22:57:39 -04:00
Joseph Lawson 3299955888 Merge remote-tracking branch 'upstream/master' 2014-03-25 11:27:46 -04:00
Leonid Bugaev 3aa04783f9 Fix tests 2014-03-22 17:11:21 +05:00
Leonid Bugaev 5a7c817f0b Fixed buffer overflow 2014-03-22 17:58:31 +06:00
Leonid Bugaev b800896b04 Incoming ip should be included into message ID 2014-03-19 19:33:24 +06:00
Joseph Lawson e7a50ac5d4 increasing MSG_EXPIRE
Attempting to decrease unexpected EOF errors on replay instance.
2014-03-17 13:22:02 -04:00
Leonid Bugaev 0fb1d83284 Simplify directory structure 2014-03-16 22:24:27 +06:00
Leonid Bugaev 1784516771 Bump version and add Makefile 2014-03-16 22:05:13 +06:00
Leonid Bugaev 9fa5ef74fb Quick fix for #61 2014-03-16 22:03:09 +06:00
Leonid Bugaev d67bea5e10 Fixed #82 2014-03-16 22:01:23 +06:00
Leonid Bugaev 263d1347a0 Update version 2014-01-29 21:29:46 +06:00
Leonid Bugaev 19008c2a2a Merge pull request #55 from buger/tcp_pool
Tcp pool
2014-01-29 07:26:51 -08:00
Leonid Bugaev 49cdbbe41b Removed unused package 2014-01-29 21:13:57 +06:00
Leonid Bugaev 59a2b7ca1d GOMAXPROCS should be set manually 2014-01-29 21:13:24 +06:00
Leonid Bugaev 9a32742653 Fixed tests 2014-01-29 21:10:35 +06:00
Leonid Bugaev 38b171d357 Merge branch 'master' into tcp_pool
Conflicts:
	output_http.go
	output_http_test.go
2014-01-29 14:57:47 +00:00
Dan Carley 90261550c4 Catch RedirectNotAllowed correctly
The error `RedirectNotAllowed` is wrapped by `url.Error`, causing it to not
currently be caught/ignored correctly for responses that issue redirects:
```
2014/01/06 12:17:17 Request error: Get https://example.com/foo: Redirects not allowed
```

It seems that two type assertions/conditions are required to unravel the
exact error. I can't see any way to write a test for this functionality --
the call to `defer()` or `log.Println()`.
2014-01-06 17:07:48 +00:00
Leonid Bugaev 7814bd8bc5 Merge pull request #66 from alphagov/replay_get_methods_only
Filter HTTP methods on output
2013-12-23 02:29:18 -08:00
Leonid Bugaev 40cd01630b Merge pull request #67 from mtrojanowski/elastigo-indexer-fix
Changed `Indexor` to `Indexer` to comply with the newest ver of elastigo.
2013-12-18 06:11:46 -08:00
mtrojanowski 19eadf49b9 Changed Indexor to Indexer to comply with newest ver of elastigo. 2013-12-18 14:55:51 +01:00
Leonid Bugaev 227e95467a Merge pull request #63 from robyoung/check-packet-size
Check packet has data via buffer size not PSH
2013-12-17 10:00:48 -08:00
Dan Carley 14d9ca6d54 Filter HTTP methods on output
Add a new CLI flag to specify which HTTP methods should be replayed by
HTTPOutput. If specified, any requests not matching will be dropped.

This can be useful for replaying requests against stateful environments.
e.g. You may not want to reproduce POST requests against an application if
it results in additional calls to the outside world.

Some variations I considered:

- Filtering on input instead of output. However we don't currently do any
  request parsing on input, and doing so would likely have an impact on
  performance.

- A request filtering plugin. We might want to revisit this if we add
  anymore options to HTTPOutput. It could also be used to modify requests in
  an existing file capture. Although because all plugins expect byte slices
  we'd potentially have to parse requests more than once.

I don't think this warrants a separate test for HTTPOutput yet. But, again,
if we add anymore then we should split them out, and DRY up if possible.
Because we don't want to overload the scenarios covered by that one test.
2013-12-17 17:51:35 +00:00
Leonid Bugaev b9c97eabaf Merge pull request #65 from alphagov/62-misbehaving_http_output_test
[Fixes #62] HTTPOutput take copy of request byte slice
2013-12-17 05:37:58 -08:00
Dan Carley d9c54d31ad [#62] HTTPOutput take copy of request byte slice
At the time `CopyMulty()` calls `HTTPOutput.Write(data)` the contents of the
byte slice `data` is correct/consistent. However by the time the goroutine
for `HTTPOutput.sendRequest(data)` is scheduled, the contents of `data` has
changed, which in the case of our tests results in two things happening:

- The same request gets repeated many times.
- A request with the length of `EmitGET()` is made but with the larger
  contents of `EmitPOST()`, causing it to be truncated and
  `HTTPOutput.ParseRequest()` fails.

As I understand it, this is because the slice header of `data` is passed by
value into the goroutine, but the contents referred to by that header are
pointers which subsequently get overwritten.

By taking a `copy()` of the request data into a new buffer variable and
passing that to the goroutine, we can ensure that it doesn't get modified
in-flight.
2013-12-17 10:47:49 +00:00
Dan Carley 796f192e71 [#62] Reverse order of GET/POST in HTTP out test
Swap the order of calls to `EmitGET()` and `EmitPOST()` for HTTP output
tests in order to surface the problems:

- GET requests appear to be repeated. For three iterations, 5 GETs and only
  1 POST request can be observed at `StartHTTP()`.
- POST requests are truncated somewhere along the line and cannot be parsed
  by `HTTPOutput.ParseRequest()`. Resulting in:

      Can not parse request POST /pub/WWW/ HTT malformed HTTP version "HTT"

There is an underlying problem with the test that it only checks the request
count, not the type/content of "good" requests.
2013-12-17 10:36:22 +00:00
Rob Young eb6d0cddd9 Check packet has data via buffer size not PSH
The PSH flag tells the receiver to flush it's buffer. While this will
never be set for packets that have no data it can be, and often is, not
set for packets that do. For example, when a message spans more than one
segment the earlier segments often do not have the PSH flag set.

This alternative solution checks that the buffer is larger than the TCP
header.
2013-12-02 21:22:27 +00:00
Leonid Bugaev f82dade127 Merge pull request #60 from waffleio/master
waffle.io Badge
2013-11-22 03:49:54 -08:00
waffle.io 5f35f41637 add waffle.io badge 2013-11-22 03:48:55 -08:00
Leonid Bugaev 26ddfcd3cd Update README.md 2013-11-18 14:34:08 +01:00
Leonid Bugaev ac3f255d38 Merge pull request #58 from tambet/master
Read requests from file
2013-11-15 14:36:09 -08:00
Tambet Masik 68ba87c19e Read requests from file 2013-11-15 22:36:29 +02:00
Leonid Bugaev fd9f6cd056 Connections pool for output_tcp 2013-11-02 21:45:49 +01:00
Leonid Bugaev 9bba1296bd Persistent connection support for input_tcp 2013-11-02 21:11:17 +01:00
Leonid Bugaev f7b3adc8cd Add delay to http server for proper testing 2013-11-02 19:46:46 +01:00
Leonid Bugaev dd806640f9 Remove debugging 2013-11-02 17:33:36 +01:00
Leonid Bugaev 824c51248c Use workers and increase GOMAXPROCS
Gives about 2x increase.
2013-11-02 17:26:59 +01:00
Leonid Bugaev f8a8444b27 Add basic benchmakrs 2013-11-02 16:53:59 +01:00
Leonid Bugaev c811dc017e Update README.md 2013-10-31 13:36:55 +01:00
Leonid Bugaev c2424b2b8f Update README.md 2013-10-31 13:36:33 +01:00
Leonid Bugaev ccf6723743 Merge pull request #46 from buger/module_architecture
Merge listener and replay functionality
2013-10-31 04:46:56 -07:00
Leonid Bugaev fa9c9c3387 Merge branch 'master' into module_architecture 2013-10-31 11:44:16 +00:00
Leonid Bugaev 8620e4a467 Updated README 2013-10-31 12:43:42 +01:00
Leonid Bugaev 457e92ed11 Updated Procfile 2013-10-31 12:43:07 +01:00
Leonid Bugaev 9da6f908fd Updated CHANGELOG 2013-10-31 12:39:41 +01:00
Leonid Bugaev 4406794a28 Rename dirrectory with runnable file 2013-10-31 12:15:06 +01:00
Leonid Bugaev 92c8dd19f4 Updated documentation 2013-10-31 12:11:56 +01:00
Leonid Bugaev 860189b1c5 Update ELASTICSEARCH.md 2013-10-31 10:40:54 +01:00
Leonid Bugaev 0f27a45fbb Update README.md 2013-10-31 10:38:06 +01:00
Leonid Bugaev 8ffdd10988 Added ElasticSearch statistics 2013-10-30 15:40:44 +01:00
Leonid Bugaev 6a136b4686 Add splitOutput option if have multiple outputs 2013-10-30 14:53:16 +01:00
Leonid Bugaev af3a7a7541 Addded limiting support to output_tcp 2013-10-30 14:35:40 +01:00
Leonid Bugaev 602448accd Added custome headers 2013-10-30 14:29:32 +01:00
Leonid Bugaev 8b9c72ef9e Don't panic if replay server is not responding 2013-10-30 12:48:07 +01:00
Leonid Bugaev 95d3676d83 Add delay between request for input_file 2013-10-29 20:49:59 +01:00
Leonid Bugaev 72952fddd2 Added input_file plugin 2013-10-29 18:53:35 +01:00
Leonid Bugaev faa3cb7307 Add limiter 2013-10-29 15:50:56 +01:00
Leonid Bugaev ce76453fa6 Added tests for all plugins 2013-10-29 11:42:15 +01:00
Leonid Bugaev 9dddab58d3 Fiix: Profiling never start 2013-10-29 08:07:27 +01:00
Leonid Bugaev c42a42928b Require at least 1 input and 1 output 2013-10-29 08:06:32 +01:00
Leonid Bugaev 2a4efa91af Initial commit 2013-10-27 18:49:00 +00:00
Leonid Bugaev 2fd36f03f1 Merge pull request #48 from alphagov/binary_file_format
[#47 #36] Serialize requests to file using gob
2013-10-25 07:28:14 -07:00
Leonid Bugaev 3b890c6d7f Merge pull request #51 from alphagov/document_basic_auth_injection
[#31] Document BasicAuth injection
2013-10-24 07:25:04 -07:00
Dan Carley bc4fabd0da [#31] Document BasicAuth injection
Has been asked about previously. `http.Client.Do` does this for us.
2013-10-24 13:02:14 +01:00
Dan Carley 24a240c819 [README] Stylise GOV.UK link
Use `https://www` to spare a redirect. And capped-up-cos-we-mean-business:
http://www.theregister.co.uk/2012/02/01/gov_uk_single_domain_release/
2013-10-24 12:42:47 +01:00
Dan Carley 2f049dddbd Rename ParsedRequest to RawRequest
Since it contains a raw byte slice of the request data rather than a
`http.Request` object.
2013-10-23 21:07:35 +01:00
Dan Carley e7c1d86bfa Move ParsedRequest{} to gor/utils sub-package
This de-dupes the type definition used in both `listener` and `replay`.
2013-10-23 17:17:32 +01:00
Dan Carley 714307890e [#47 #36] Serialize requests to file using gob
To replace the serial plaintext representation of request and timestamp.
This fixes a bug whereby we were unable to delimit POST requests with bodies
because they didn't end in `\r\n\r\n`, frequently resulting in:
```
--- FAIL: TestSavingRequestToFileAndReplayThem (2.80 seconds)
        integration_test.go:346: Timeout error
```

Now we don't need to play guesswork with `Content-Length` headers or
introduce a custom delimiter. As a bonus, the code required is also slightly
simpler.

It is no longer possible to manipulate the `.gor` file by hand; but it does
make it trivial to write a tool that can parse and modify.

There are some `go fmt` indent changes rolled into `replay_file_parser`.
2013-10-22 21:54:24 +01:00
Leonid Bugaev 69df96e55d Merge pull request #43 from alphagov/replay_header_injection
Allow injection of additional headers in replay
2013-10-21 05:42:10 -07:00
Dan Carley 9c6802f5e8 Integration test for header injection
Re-using one of the existing integration tests. If we were to refactor some
of the logic to send and receieve a single request then it would make sense
to split this, and the cookie validation, out to separate test cases.
2013-10-21 13:33:27 +01:00
Dan Carley d54da99667 Unit test the parsing of -header arguments
Per the features described in the preceding commit.
2013-10-21 13:31:15 +01:00
Dan Carley f4af3a9bd4 Allow injection of additional headers in replay
Similar to curl(1) and siege(1):

- Can be specified multiple times.
- Will overwrite headers of the same key name in the original request.
- An argument without a value (`Foo:`) will be set as empty.
- Leading and trailing whitespace will be stripped from the key and value,
  otherwise it's difficult to determine where the key or value begin/end.
2013-10-21 13:30:52 +01:00
Leonid Bugaev 1f9c9a6154 Merge pull request #44 from alphagov/run_all_tests
Run all tests + fix failing ES test
2013-10-20 13:25:55 -07:00
Dan Carley 9e175434d6 Fix failing Elasticsearch test
Use the local instance of `ReplaySettings` rather than `Settings` which is
initialised as an empty struct and then populated by flag. Since we're not
calling flag, this remains empty, and `esp.Init()` is passed an empty
string.

For the same reason the call to `settings.Parse()` is actually redundant.
`Parse()` could be changed to use `r.ElastiSearchURI`, but it results in the
plugin begin setup/registered twice, because it doesn't give us access to
the host/port/index properties.
2013-10-20 21:18:25 +01:00
Dan Carley 9a126103fc Ensure that TravisCI tests all subpackages
Previously this was only running the integration tests in the root
directory. `go test` needs to be given wildcard in order to pickup tests in
sub directories/packages.
2013-10-20 20:53:09 +01:00
Leonid Bugaev 9a978422b2 Update README.md 2013-10-19 20:35:47 +02:00
Leonid Bugaev e02c145ac6 Do not count redirects as errors 2013-10-19 10:53:36 +02:00
Leonid Bugaev 7d482d47de Update README.md 2013-10-18 14:15:08 +02:00
Leonid Bugaev f7cf05c257 Merge pull request #41 from alphagov/readme_file_based_timings
Document time delay in file-based replay
2013-10-18 03:16:58 -07:00
Leonid Bugaev 4af1230d83 Merge pull request #40 from alphagov/rename_reply_to_replay
Rename instances of "reply" to "replay"
2013-10-18 03:16:39 -07:00
Dan Carley 18597d9e7a Rename instances of "reply" to "replay"
This looks to have been a typo. Limited to file-based playback only. The
word "replay" makes more sense here, and is consistent with TCP playback.
2013-10-18 11:01:37 +01:00
Dan Carley fe02bfa8c5 Document time delay in file-based replay
This is an awesome feature that I've been looking for, for sometime. But I
had to dig through the code to verify that it did such. It should be called
out in the README instead!
2013-10-18 10:57:28 +01:00
Sławosz 48d4406893 Merge pull request #39 from alphagov/garbled_file_parsing
Fix garbled request input from file
2013-10-18 01:48:25 -07:00
Dan Carley f07c7f5eaf Merge branch 'master' into garbled_file_parsing 2013-10-18 09:35:08 +01:00
Leonid Bugaev db4b2c26b0 Fixed #36. Replaying requests to mutiple hosts 2013-10-17 20:55:18 +02:00
Dan Carley 8ecda0fdb5 Fix garbled request input from file
Buffer a copy of `scanner.Bytes()` when appending to a slice of requests.
Otherwise the data may be overwritten in subsequent loops. This results in
garbled requests, without truncated output and sometimes random characters.
This may not be apparent when a small number of requests are used.

Ref: http://golang.org/pkg/bufio/#Scanner.Bytes
```
Bytes returns the most recent token generated by a call to Scan. The
underlying array may point to data that will be overwritten by a subsequent
call to Scan. It does no allocation.
```

This fixes the tests errors like:
```
2013/10/17 15:26:28 Starting file reply2013/10/17 15:26:28 Can not parse request =b&c=d
1382023587787798594
POST /test HTTP/1.1
Host: localhost:50030
User-Agent: Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.1 Safari/534.34
Content-Length: 7
Accept: */*
Accept-Language: en-GB,*
Cookie: test=value
Referer: http://localhost/test
X-Forwarded-For: 1.1.1.1, 2.2.2.2, 3.3.3.3
X-Fo malformed HTTP request "=b&c=d"
2013/10/17 15:26:28 Can't parse request...:malformed HTTP request "=b&c=d"
```
2013-10-17 16:51:38 +01:00
Dan Carley 06befe3b4b Integration test for garbled requests from file
Increase the number of iterations and size requests written to file in order
to trigger a bug when parsing requests back in.

This test will currently fail with: `Can't parse request...`
2013-10-17 16:40:58 +01:00
Leonid Bugaev 8c41c01d4b Update README.md 2013-10-13 19:53:40 +02:00
Leonid Bugaev 4e41151963 Update README.md 2013-10-13 19:51:07 +02:00
Leonid Bugaev 18ec957e62 Merge pull request #37 from gottwald/es-docs
Added elasticsearch documentation
2013-10-13 10:48:07 -07:00
Ingo Gottwald 857a9b4835 Updated README.md linked to ELASTICSEARCH.md 2013-10-13 17:34:34 +02:00
Ingo Gottwald 12ae1455f8 Added elasticsearch documentation 2013-10-13 17:21:30 +02:00
Leonid Bugaev da2478ca3c Fix Reply From File test 2013-10-12 14:16:14 +02:00
Leonid Bugaev c32deec006 Tests: Added second host for replaying 2013-10-12 09:52:27 +02:00
Leonid Bugaev f5a8274fcd One more fix 2013-10-12 09:44:57 +02:00
Leonid Bugaev d1708ff1f3 Fixed test 2013-10-12 09:42:25 +02:00
Leonid Bugaev fd642bded1 Improve debugging 2013-10-10 11:33:31 +02:00
Leonid Bugaev 40203d2519 Turn on verbose mode for tests 2013-10-10 11:27:48 +02:00
Leonid Bugaev fd27e13e85 Turn on verbose mode for go test 2013-10-10 11:26:34 +02:00
Leonid Bugaev d46e587c08 Added tests for POST requests 2013-10-10 11:09:50 +02:00
Leonid Bugaev fa2dedceb3 Merge pull request #35 from buger/add_procfile
Added Procfile to simplify debuging
2013-10-10 00:04:46 -07:00
Leonid Bugaev 983e2a0e79 Merge pull request #33 from buger/elasticsearch_refactoring
ElasticSearch refactoring and updated docs
2013-10-09 23:56:28 -07:00
Leonid Bugaev 42173e4687 Some minor changes 2013-10-10 08:47:19 +02:00
Leonid Bugaev 8757373a7a Fix typo 2013-10-10 08:44:38 +02:00
Leonid Bugaev b6e7b18803 Added Procfile to simplify debuging 2013-10-10 08:33:45 +02:00
Leonid Bugaev e21f9b024d Fix replay. It should not exit if single request is not parsed.
Fix #34
2013-10-09 20:32:24 +02:00
Leonid Bugaev 20901ec6ae Some refactoring and updated docs 2013-10-09 12:58:17 +02:00
Leonid Bugaev 327ee32395 Fix same settings parse bug on replay side
Added basic settings tests
2013-10-09 09:19:57 +02:00
Leonid Bugaev e32b985df2 Fixed settings parse bug
Fix #32
2013-10-09 08:56:03 +02:00
Leonid Bugaev 737ea9fc68 Merge branch 'elasticsearch' of https://github.com/gottwald/gor into gottwald-elasticsearch
Conflicts:
	replay/replay.go
	replay/request_factory.go
2013-10-08 22:20:06 +02:00
Leonid Bugaev 509b27c476 Merge pull request #25 from slawosz/save-request-to-reply-later
Save request to file for later replay
2013-10-08 13:12:42 -07:00
Ingo Gottwald 94199fcb25 Fixed elasicsearch plugin
Don't try to export failed requests
2013-10-08 20:32:35 +02:00
Sławosz bba9637eed remove comment 2013-10-08 19:54:37 +02:00
Sławosz 685c998e8e remove MessageLogger 2013-10-08 19:47:30 +02:00
Sławosz 8adeda9a98 finish replay, when all requests got replayed 2013-10-08 19:41:24 +02:00
Sławosz 9077656bdf Information about replaying in README 2013-10-08 12:59:41 +02:00
Sławosz 830ae237c9 better messages on listener start 2013-10-08 12:54:54 +02:00
Ingo Gottwald 88dd2602df More data for elasticsearch
- Removed extension based mime analysis
- Added more data fields for elasticsearch
- ESResponse is now a ESRequestResponse struct
(holds combined data from requests and responses)
2013-10-06 14:36:16 +02:00
Ingo Gottwald 27582841fe Added elasticsearch response analyze plugin 2013-10-05 23:35:49 +02:00
Ingo Gottwald b53218e729 Added timing information to HTTP responses 2013-10-05 23:09:49 +02:00
Ingo Gottwald 54e9de5088 Implemented support for Response Analyze Plugins 2013-10-05 23:07:54 +02:00
Sławosz Sławiński 5782d486f9 Parse request with timestamp properly 2013-10-04 04:56:48 +00:00
Sławosz Sławiński 8b66a99665 Save request timestamp
WIP
2013-10-03 21:44:26 +00:00
Sławosz 30547f2a41 Embed log.Logger in MessageLogger 2013-10-02 20:07:19 +02:00
Sławosz 140267b6a6 Merge branch 'master' into save-request-to-reply-later
Conflicts:
	listener/raw_tcp_listener.go
	replay/replay.go
	replay/settings.go
2013-10-02 19:47:28 +02:00
Sławosz e4807b7abb Merge branch 'master' of https://github.com/buger/gor 2013-10-02 19:36:05 +02:00
Sławosz 20ea55e6e7 remove debug statement 2013-10-02 19:34:54 +02:00
Sławosz 47b498d4d9 fix request reading 2013-10-02 19:27:52 +02:00
Leonid Bugaev 4305b72608 Merge pull request #24 from buger/refactoring
Refactoring and speed improvements
2013-09-30 03:18:33 -07:00
Leonid Bugaev 578d785c27 Fixed previous merge
oops :)
2013-09-30 11:32:26 +02:00
Leonid Bugaev 6946fc6036 Merge branch 'master' into refactoring
Conflicts:
	listener/raw_tcp_listener.go
	listener/tcp_message.go
	listener/tcp_packet.go
2013-09-30 11:26:35 +02:00
Leonid Bugaev 8535872b10 Merge pull request #23 from fern4lvarez/review
General review
2013-09-30 01:22:18 -07:00
Fernando Álvarez a1f9cc501b General review:
- Fix typos
- Follow some Go good practices
- Better documentation, more consistent godoc.org
- Refactoring
2013-09-30 10:00:30 +02:00
Leonid Bugaev f07586a12e isIncomingDataPacket should be struct function 2013-09-30 09:26:07 +02:00
Leonid Bugaev fa684d4645 Used maps instead of slices for storing messages 2013-09-30 09:24:47 +02:00
Leonid Bugaev c3330cb4be Use close(channel) instead of creating new channel 2013-09-30 09:17:32 +02:00
Leonid Bugaev 3cb98aaf94 Use less buffer 2013-09-30 09:12:22 +02:00
Leonid Bugaev cbc4204e50 Some minor changes 2013-09-30 09:02:27 +02:00
Sławosz 207eea1ba7 file replay partialy working 2013-09-29 14:36:43 +02:00
Leonid Bugaev de93abeab8 Added RawTCPListener test 2013-09-29 13:39:55 +02:00
Leonid Bugaev 9908e8d4d9 Update README.md 2013-09-27 23:04:13 +02:00
Sławosz e7b2866ca9 remove nasty debug 2013-09-23 19:44:57 +02:00
Sławosz b562a6b62d test is not working 2013-09-23 19:43:04 +02:00
Sławosz 0ac36b4fbf Merge branch 'master' into save-request-to-reply-later 2013-09-23 19:38:25 +02:00
Sławosz 16ba3d1514 Merge branch 'master' of https://github.com/buger/gor 2013-09-23 19:36:34 +02:00
Sławosz 5b6b8a53c1 better file formating 2013-09-23 19:36:23 +02:00
Sławosz 1a35a2c651 faulty listener test 2013-09-23 19:34:53 +02:00
Leonid Bugaev 5a4c27dc9e Update README.md 2013-09-15 13:12:45 +04:00
Leonid Bugaev e3d1fb4e72 Update CHANGELOG.md 2013-09-15 12:59:48 +04:00
Leonid Bugaev 0233ef7efb Update CHANGELOG.md 2013-09-15 12:59:25 +04:00
Leonid Bugaev 4a68bea49c Fixed tests 2013-09-15 12:58:29 +04:00
Leonid Bugaev fd47cc1144 Update version 2013-09-15 12:49:41 +04:00
Leonid Bugaev 26455e4e52 Updated tests debugging 2013-09-15 12:47:10 +04:00
Leonid Bugaev 5aca51e5b1 Update README.md 2013-09-15 12:39:24 +04:00
Leonid Bugaev af45f8246e Update README.md 2013-09-15 12:38:36 +04:00
Leonid Bugaev 5bae7c5de5 Don't exit on panic 2013-09-15 10:59:15 +04:00
Sławosz 335c86c6e9 log messages 2013-08-28 18:43:36 +02:00
Sławosz f1eedc78a1 debugging and improving 2013-08-28 18:40:32 +02:00
Sławosz cfb65c06ac some temporary debug 2013-08-28 18:39:01 +02:00
Sławosz 02abcfdf74 message logger 2013-08-28 18:38:08 +02:00
Sławosz 1e08ec3953 gofmt 2013-08-28 18:11:31 +02:00
Sławosz db369cfc89 gofmt 2013-08-28 18:10:07 +02:00
Sławosz 54a3d73a98 better name 2013-08-21 18:29:21 +02:00
Sławosz ae792afa5e gofmt test 2013-08-20 18:40:27 +02:00
Sławosz 700523e0c3 proper test for reader writing request to file 2013-08-20 18:38:38 +02:00
Sławosz 95841d597e wrap request buffer around reader 2013-08-20 09:05:41 +02:00
Sławosz Sławiński 5ccebd008d test for saving listened requests to file wip 2013-08-19 20:08:38 +00:00
Sławosz Sławiński e5cb5d959d add flags for file in replay 2013-08-19 20:07:47 +00:00
Sławosz Sławiński 4f7b201ef1 use empty string as default value 2013-08-19 19:24:30 +00:00
Sławosz 6bb24697b2 add flags for file to listener 2013-08-19 19:00:08 +02:00
Sławosz 719fd471f3 failing integration spec 2013-08-19 18:53:28 +02:00
Leonid Bugaev af2d47817b Add error logging for http server 2013-08-16 12:53:16 +04:00
Sławosz Sławiński 2c34f291fb ignore vim files 2013-08-09 21:07:23 +00:00
Leonid Bugaev 041c20ef38 Add concurrency settings to test 2013-08-09 19:25:46 +04:00
Leonid Bugaev d425a7c9a8 Merge pull request #19 from buger/listener_limit
Fixed listener
2013-08-07 06:06:37 -07:00
Leonid Bugaev 528980c87e Fixed listener 2013-08-07 17:05:06 +04:00
Leonid Bugaev c899791d4c Merge pull request #18 from buger/listener_limit
Listener limit
2013-08-06 23:31:57 -07:00
Leonid Bugaev b6cce83b1b Update README.md 2013-08-05 20:59:37 +04:00
Leonid Bugaev 09175eade0 Updated README 2013-08-05 20:51:23 +04:00
Leonid Bugaev 3c84a0c0d9 Remove debugging 2013-08-05 20:48:01 +04:00
Leonid Bugaev 77751af316 Added listener limit option 2013-08-05 20:42:16 +04:00
Leonid Bugaev 00d3103451 Add rate-limit tests 2013-08-05 19:03:06 +04:00
Leonid Bugaev e42c3a96e2 Make tests more modular 2013-08-05 18:42:37 +04:00
Leonid Bugaev a9ca7ea7ff Make tests more configurable 2013-08-05 18:18:39 +04:00
Leonid Bugaev 40a48863fb Refactored tests 2013-08-05 18:05:40 +04:00
Leonid Bugaev 97f2bb7740 Disable redirects
Fix #15
2013-08-05 12:38:31 +04:00
Leonid Bugaev 6ac803454b Fix #15 2013-08-02 20:39:00 +04:00
Leonid Bugaev ec106e4b4e Update README.md 2013-08-02 20:24:11 +04:00
Leonid Bugaev 1f9a1ac3db Update .travis.yml 2013-08-02 20:22:50 +04:00
Leonid Bugaev 4c9cf3fa6a Update .travis.yml 2013-08-02 20:18:53 +04:00
Leonid Bugaev a89f1c75c8 Update .travis.yml 2013-08-02 19:51:16 +04:00
Leonid Bugaev 0bb7e9f7b8 Update .travis.yml 2013-08-02 19:48:57 +04:00
Leonid Bugaev 3b68ae27a6 Update .travis.yml 2013-08-02 19:45:48 +04:00
Leonid Bugaev 476da0f1e6 Update .travis.yml 2013-08-02 19:41:43 +04:00
Leonid Bugaev f6038b26b7 Update .travis.yml 2013-08-02 19:40:11 +04:00
Leonid Bugaev 668e33c128 Update .travis.yml 2013-08-02 19:37:32 +04:00
Leonid Bugaev 4066c24960 Specify go version 2013-08-02 19:32:02 +04:00
Leonid Bugaev 1686c701bf Update .travis.yml 2013-08-02 19:28:37 +04:00
Leonid Bugaev 8fac086d02 Create .travis.yml 2013-08-02 19:25:10 +04:00
Leonid Bugaev 1cc94bc7ac Added some tests 2013-08-02 19:07:39 +04:00
Leonid Bugaev d231d64abb Merge pull request #13 from bobthecow/patch-1
s/coma/comma/g
2013-07-17 21:30:28 -07:00
Justin Hileman 9a3c3f1e6d s/coma/comma/g 2013-07-17 12:26:27 -07:00
Leonid Bugaev c6fa4b8332 Create LICENSE.txt 2013-07-16 17:41:36 +06:00
Leonid Bugaev 85b54627ae Removed unused debugging. Refactored variable names. 2013-06-24 12:23:46 +06:00
Leonid Bugaev 97a5e99c6b Updated version 2013-06-22 20:36:16 +06:00
Leonid Bugaev 9490c743c3 Update README.md 2013-06-22 20:29:34 +06:00
Leonid Bugaev bc65507c8d Merge pull request #10 from buger/use_tcp
Used TCP instead of UDP
2013-06-22 07:26:36 -07:00
Leonid Bugaev 203f282bad Fixed buffer sharing 2013-06-22 19:12:58 +06:00
Leonid Bugaev 88cb352353 Removed unused debugging 2013-06-22 19:12:25 +06:00
Leonid Bugaev 2ba6dacb64 Remove binary 2013-06-22 18:27:57 +06:00
Leonid Bugaev 8defc2062e Updated README 2013-06-22 18:27:33 +06:00
Leonid Bugaev 76e5981f49 Proper conn closing and settings refactoring 2013-06-22 18:16:23 +06:00
Leonid Bugaev 5910409379 Used TCP instead of UDP 2013-06-22 17:24:10 +06:00
Leonid Bugaev 83f16946c7 Fixed docs 2013-06-20 20:16:25 +06:00
Leonid Bugaev 28702cd503 Updated docs 2013-06-20 18:43:31 +06:00
Leonid Bugaev 35f2f71199 Fixed replaying (forgot to add Query to url) 2013-06-19 21:27:05 +06:00
Leonid Bugaev 15f23270df Fixed replaying to multiple addreses 2013-06-19 17:07:48 +06:00
Leonid Bugaev 6ba587e82e Don't block socket reading 2013-06-19 13:34:01 +06:00
Leonid Bugaev cad13f4233 Refactor concurrency to use more channels 2013-06-18 20:32:47 +06:00
Leonid Bugaev fcadc57696 Optimize packet parsing 2013-06-18 17:21:35 +06:00
Leonid Bugaev 28bbb9abf9 Fixed settings and small typo. 2013-06-18 16:20:54 +06:00
Leonid Bugaev 2709bba3c2 Add setting to specify IP to bind 2013-06-18 16:06:46 +06:00
Leonid Bugaev 2e13a7930b More optimizations. Don't acclocat unneded memory. 2013-06-16 17:25:21 +06:00
Leonid Bugaev c62ce5513f Speed optimizations. v0.3.1 2013-06-16 13:45:38 +06:00
Leonid Bugaev 4bcb3e1ca6 Added building from source section
fixed #7
2013-06-14 13:02:54 +06:00
Leonid Bugaev 5384aaf21b Update README.md 2013-06-11 13:48:37 +06:00
Leonid Bugaev 2944c84b1e Merge pull request #6 from buger/rewrite
v0.3 Big rewrite
2013-06-11 00:44:24 -07:00
Leonid Bugaev f0d5aa11dd Added changelog 2013-06-10 22:07:52 +06:00
Leonid Bugaev 3cf7be8408 Big rewrite
* Use RAW_SOCKETS instead of tcpdump
* Own TCP stack
* All HTTP request types support
* Use standard http.ParseRequest for parsing requests
2013-06-10 22:01:27 +06:00
Leonid Bugaev f5cc6021d2 Merge pull request #5 from kuriharak93/master
Small grammar fixes in README.md
2013-06-09 21:25:21 -07:00
Kyle Kurihara dd3d8d8de5 small grammar fixes 2013-06-08 15:01:40 -05:00
Leonid Bugaev b10615e3d3 Update README.md 2013-06-04 20:49:54 +06:00
Leonid Bugaev 9f2652303c Update README.md 2013-06-04 19:40:41 +06:00
493 changed files with 165590 additions and 656 deletions
+3
View File
@@ -0,0 +1,3 @@
*.tar.gz
gor
gor.test
+26
View File
@@ -0,0 +1,26 @@
*.swp
*.gor
*.out
*.bin
*.gz
*.zip
*.class
*.test
.idea
*.iml
gor
*.mprof
*.pcap
.DS_Store
corpus
crashers
suppressions
+15
View File
@@ -0,0 +1,15 @@
[submodule "vendor/github.com/mattbaird/elastigo"]
path = vendor/github.com/mattbaird/elastigo
url = https://github.com/mattbaird/elastigo
[submodule "vendor/github.com/araddon/gou"]
path = vendor/github.com/araddon/gou
url = https://github.com/araddon/gou
[submodule "vendor/github.com/bitly/go-hostpool"]
path = vendor/github.com/bitly/go-hostpool
url = https://github.com/bitly/go-hostpool
[submodule "vendor/github.com/bmizerany/assert"]
path = vendor/github.com/bmizerany/assert
url = https://github.com/bmizerany/assert
[submodule "vendor/github.com/google/gopacket"]
path = vendor/github.com/google/gopacket
url = https://github.com/google/gopacket
+5
View File
@@ -0,0 +1,5 @@
POST /post HTTP/1.1
Content-Length: 7
Host: www.w3.org
a=1&b=2
+6
View File
@@ -0,0 +1,6 @@
language: go
go: 1.6
script: sudo -E bash -c "source /etc/profile && eval '$(gimme 1.6)' && export GOPATH=$HOME/gopath:$GOPATH && go get && GORACE='halt_on_error=1' go test ./... -v -timeout 120s -race"
before_install:
- sudo apt-get install libpcap-dev -y
+94
View File
@@ -0,0 +1,94 @@
END-USER LICENSE AGREEMENT
------------------------------------------------------------------------------
IMPORTANT: THIS SOFTWARE END-USER LICENSE AGREEMENT ("EULA") IS A LEGAL AGREEMENT (“Agreement”) BETWEEN YOU (THE CUSTOMER, EITHER AS AN INDIVIDUAL OR, IF PURCHASED OR OTHERWISE ACQUIRED BY OR FOR AN ENTITY, AS AN ENTITY) AND GoReplay LLC. READ IT CAREFULLY BEFORE COMPLETING THE INSTALLATION PROCESS AND USING GOREPLAY PRO AND RELATED SOFTWARE COMPONENTS (“SOFTWARE”). IT PROVIDES A LICENSE TO USE THE SOFTWARE AND CONTAINS WARRANTY INFORMATION AND LIABILITY DISCLAIMERS. BY INSTALLING AND USING THE SOFTWARE, YOU ARE CONFIRMING YOUR ACCEPTANCE OF THE SOFTWARE AND AGREEING TO BECOME BOUND BY THE TERMS OF THIS AGREEMENT.
------------------------------------------------------------------------------
In order to use the Software under this Agreement, you must receive a “Source URL” at the time of purchase, in accordance with the scope of use and other terms specified for each type of Software and as set forth in this Section 1 of this Agreement.
1. License Grant
1.1 General Use. This Agreement grants you a non-exclusive, non-transferable, limited license to the use rights for the Software, without the right to grant sublicenses, subject to the terms and conditions in this Agreement. The Software is licensed, not sold.
1.2 Unlimited Organization License. If you purchased an Organization License (included with the GoReplay Pro Software), you may install the Software on an unlimited number of Hosts. “Host” means any physical or virtual machine which is controlled by you. You may concurrently run the software on an unlimited number of Hosts.
1.3 Appliance License. If you purchased an Appliance License, you may distribute the Software in any applications, frameworks, or elements (collectively referred to as an “Application” or “Applications”) that you develop using the Software in accordance with this EULA, provided that such distribution does not violate the restrictions set forth in section 3 of this EULA. You must not remove, obscure or interfere with any copyright, acknowledgment, attribution, trademark, warning or disclaimer statement affixed to, incorporated in or otherwise applied in connection with the Software. You are required to ensure that the Software is not reused by or with any applications other than those with which you distribute it as permitted herein. For example, if You install the Software on a customer’s server, that customer is not permitted to use the Software independently of your Application. You must inform GoReplay LLC of your knowledge of any infringing use of the Software by any of your customers. You are liable for compliance by those third parties with the terms and conditions of this EULA. You will not owe GoReplay LLC any royalties for your distribution of the Software in accordance with this EULA.
1.4 Archive Copies. You are entitled to make a reasonable amount of copies of the Software for archival purposes. Each copy must reproduce all copyright and other proprietary rights notices on or in the Software Product.
1.5 Electronic Delivery. All Software and license documentation shall be delivered by electronic means unless otherwise specified on the applicable invoice or at the time of purchase. Software shall be deemed delivered when it is made available for download by you (“Delivery”).
2. Modifications. GoReplay LLC shall provide you with source code so that you can create Modifications of the original software. “Modification” means: (a) any addition to or deletion from the contents of a file included in the original Software or previous Modifications created by You, or (b) any new file that contains any part of the original Software or previous Modifications. While you retain all rights to any original work authored by you as part of the Modifications, We continue to own all copyright and other intellectual property rights in the Software.
3. Restricted Uses.
3.1 You shall not (and shall not allow any third party to): (a) decompile, disassemble, or otherwise reverse engineer the Software or attempt to reconstruct or discover any source code, underlying ideas, algorithms, file formats or programming interfaces of the Software by any means whatsoever (except and only to the extent that applicable law prohibits or restricts reverse engineering restrictions); (b) distribute, sell, sublicense, rent, lease or use the Software for time sharing, hosting, service provider or like purposes, except as expressly permitted under this Agreement; (c) redistribute the Software or Modifications other than by including the Software or a portion thereof within your own product, which must have substantially different functionality than the Software or Modifications and must not allow any third party to use the Software or Modifications, or any portions thereof, for software development or application development purposes; (d) redistribute the Software as part of a product, "appliance" or "virtual server"; (e) redistribute the Software on any server which is not directly under your control; (f) remove any product identification, proprietary, copyright or other notices contained in the Software; (g) modify any part of the Software, create a derivative work of any part of the Software (except as permitted in Section 4), or incorporate the Software, except to the extent expressly authorized in writing by GoReplay LLC; (h) publicly disseminate performance information or analysis (including, without limitation, benchmarks) from any source relating to the Software; (i) utilize any equipment, device, software, or other means designed to circumvent or remove any form of Source URL or copy protection used by GoReplay LLC in connection with the Software, or use the Software together with any authorization code, Source URL, serial number, or other copy protection device not supplied by GoReplay LLC; (j) use the Software to develop a product which is competitive with any GoReplay LLC product offerings; or (k) use unauthorized Source URLS or keycode(s) or distribute or publish Source URLs or keycode(s), except as may be expressly permitted by GoReplay LLC in writing. If your unique Source URL is ever published, GoReplay LLC reserves the right to terminate your access without notice.
3.2 UNDER NO CIRCUMSTANCES MAY YOU USE THE SOFTWARE AS PART OF A PRODUCT OR SERVICE THAT PROVIDES SIMILAR FUNCTIONALITY TO THE SOFTWARE ITSELF.
The Open Source version of the Software (“LGPL Version”) is licensed
under the terms of the GNU Lesser General Public License versions 3.0
(“LGPL”) and not under this EULA.
4. Ownership. Notwithstanding anything to the contrary contained herein, except for the limited license rights expressly provided herein, GoReplay LLC and its suppliers have and will retain all rights, title and interest (including, without limitation, all patent, copyright, trademark, trade secret and other intellectual property rights) in and to the Software and all copies, modifications and derivative works thereof (including any changes which incorporate any of your ideas, feedback or suggestions). You acknowledge that you are obtaining only a limited license right to the Software, and that irrespective of any use of the words “purchase”, “sale” or like terms hereunder no ownership rights are being conveyed to you under this Agreement or otherwise.
5. Fees and Payment. The Software license fees will be due and payable in full as set forth in the applicable invoice or at the time of purchase. If the Software does not function properly within two weeks of purchase, please contact us within those two weeks for a refund. You shall be responsible for all taxes, withholdings, duties and levies arising from the order (excluding taxes based on the net income of GoReplay LLC).
6. Support, Maintenance and Services. Subject to the terms and conditions of this Agreement, as set forth in your invoice, and as set forth on the GoReplay Pro support page (https://github.com/buger/goreplay/wiki/Pro-Support), support and maintenance services may be included with the purchase of your license subscription.
7. Term of Agreement.
7.1 Term. This Agreement is effective as of the Delivery of the Software and expires at such time as all license and service subscriptions hereunder have expired in accordance with their own terms (the “Term”). For clarification, the term of your license under this Agreement may be perpetual, limited for Evaluation Version, or designated as a fixed-term license in the Invoice, and shall be specified at your time of purchase. Either party may terminate this Agreement (including all related Invoices) if the other party: (a) fails to cure any material breach of this Agreement within thirty (30) days after written notice of such breach, provided that GoReplay LLC may terminate this Agreement immediately upon any breach of Section 3 or if you exceed any other restrictions contained in Section 1, unless otherwise specified in this agreement; (b) ceases operation without a successor; or (c) seeks protection under any bankruptcy, receivership, trust deed, creditors arrangement, composition or comparable proceeding, or if any such proceeding is instituted against such party (and not dismissed within sixty (60) days)). Termination is not an exclusive remedy and the exercise by either party of any remedy under this Agreement will be without prejudice to any other remedies it may have under this Agreement, by law, or otherwise.
7.2 Termination. Upon any termination of this Agreement, you shall cease any and all use of any Software and destroy all copies thereof.
7.3 Expiration of License. Upon the expiration of any term under this Agreement, (a) all Software updates and services pursuant to the license shall cease, (b) you may only continue to run existing installations of the Software, (c) you may not install the Software on any additional Hosts, and (d) any new installation of the Software shall require the purchase of a new license subscription from GoReplay LLC.
8. Disclaimer of Warranties. The Software is provided "as is," with all faults, defects and errors, and without warranty of any kind. GoReplay LLC does not warrant that the Software will be free of bugs, errors, viruses or other defects, and GoReplay LLC shall have no liability of any kind for the use of or inability to use the Software, the Software content or any associated service, and you acknowledge that it is not technically practicable for GoReplay LLC to do so.
To the maximum extent permitted by applicable law, GoReplay LLC disclaims all warranties, express, implied, arising by law or otherwise, regarding the Software, the Software content and their respective performance or suitability for your intended use, including without limitation any implied warranty of merchantability, fitness for a particular purpose.
Notwithstanding the foregoing, GoReplay LLC represents and warrants that it either owns the entire right to, title to, interest in, or has the right to license, the Software, and your proper use of the same will not violate any intellectual property or proprietary rights of another.
9. Limitation of Liability.
In no event will either party be liable for any direct, indirect, consequential, incidental, special, exemplary, or punitive damages or liabilities whatsoever arising from or relating to the Software, the Software content or this Agreement, whether based on contract, tort (including negligence), strict liability or other theory, even if such party has been advised of the possibility of such damages.
In no event will GoReplay LLC liability exceed the Software license price as indicated in the invoice. The existence of more than one claim will not enlarge or extend this limit.
10. Remedies. Your exclusive remedy and GoReplay LLC’ entire liability for breach of this Agreement shall be limited, at GoReplay LLC’ sole and exclusive discretion, to (a) replacement of any defective software or documentation; or (b) refund of the license fee paid to GoReplay LLC, payable in accordance with GoReplay LLC' refund policy.
11. Acknowledgements.
11.1 Consent to the Use of Data. You agree that GoReplay LLC and its affiliates may collect and use technical information gathered as part of the product support services to be used in an anonymized manner. GoReplay LLC may use this information solely to improve products and services and will not disclose this information in a form that personally identifies you.
11.2 Verification. We or a certified auditor acting on our behalf, may, upon its reasonable request and at its expense, audit you with respect to the use of the Software, subject to your reasonable information security and confidentiality protections. Such audit may be conducted by mail, electronic means or through an in-person visit to your place of business. Any such in-person audit shall be conducted during regular business hours at your facilities and shall not unreasonably interfere with your business activities. We shall not remove, copy, or redistribute any electronic material during the course of an audit. If an audit reveals that you are using the Software in a way that is in material violation of the terms of the EULA, then you shall pay our reasonable costs of conducting the audit. In the case of a material violation, you agree to pay Us any amounts owing that are attributable to the unauthorized use. In the alternative, We reserve the right, at our sole option, to terminate the licenses for the Software.
11.3 Government End Users. If the Software and related documentation are supplied to or purchased by or on behalf of the United States Government, then the Software is deemed to be "commercial software" as that term is used in the Federal Acquisition Regulation system. Rights of the United States shall not exceed the minimum rights set forth in FAR 52.227-19 for "restricted computer software". All other terms and conditions of this Agreement apply.
12. Third Party Software. Examples included in Software may provide links to third party libraries or code (collectively “Third Party Software”) to implement various functions. Third Party Software does not comprise part of the Software. In some cases, access to Third Party Software may be included along with the Software delivery as a convenience for demonstration purposes. Such source code and libraries may be included in the “…/examples” source tree delivered with the Software and do not comprise the Software. Licensee acknowledges (1) that some part of Third Party Software may require additional licensing of copyright and patents from the owners of such, and (2) that distribution of any of the Software referencing or including any portion of a Third Party Software may require appropriate licensing from such third parties.
13. Miscellaneous
13.1 Entire Agreement. This Agreement sets forth our entire agreement with respect to the Software and the subject matter hereof and supersedes all prior and contemporaneous understandings and agreements whether written or oral.
13.2 Amendment. GoReplay LLC reserves the right, in its sole discretion, to amend this Agreement from time. Amendments to this Agreement can be located at: https://github.com/buger/goreplay/blob/master/COMM-LICENSE.
13.3 Assignment. You may not assign this Agreement or any of its rights under this Agreement without the prior written consent of GoReplay LLC and any attempted assignment without such consent shall be void.
13.4 Export Compliance. Each party agrees to comply with all applicable laws and regulations, including laws, regulations, orders or other restrictions on export, re-export or redistribution of software.
13.5 Indemnification. You agree to defend, indemnify, and hold harmless GoReplay LLC from and against any lawsuits, claims, losses, damages, fines and expenses (including attorneys' fees and costs) arising out of your use of the Software or breach of this Agreement.
13.6 Governing Law. This Agreement is governed by the laws of the State of Oregon and the United States without regard to conflicts of laws provisions thereof, and without regard to the United Nations Convention on the International Sale of Goods or the Uniform Computer Information Transactions Act, as currently enacted by any jurisdiction or as may be codified or amended from time to time by any jurisdiction. The jurisdiction and venue for actions related to the subject matter hereof shall be the state of Oregon and United States federal courts located in Portland, Oregon, and both parties hereby submit to the personal jurisdiction of such courts.
13.7 Attorneys’ Fees and Costs. The prevailing party in any action to enforce this Agreement will be entitled to recover its attorneys’ fees and costs in connection with such action.
13.8 Severability. If any provision of this Agreement is held by a court of competent jurisdiction to be invalid, illegal, or unenforceable, the remainder of this Agreement will remain in full force and effect.
13.9 Waiver. Failure or neglect by either party to enforce at any time any of the provisions of this licence Agreement shall not be construed or deemed to be a waiver of that party's rights under this Agreement.
13.10 Headings. The headings of sections and paragraphs of this Agreement are for convenience of reference only and are not intended to restrict, affect or be of any weight in the interpretation or construction of the provisions of such sections or paragraphs.
14. Contact Information. If you have any questions about this EULA, or if you want to contact GoReplay LLC for any reason, please direct correspondence to info@gortool.com
+8
View File
@@ -0,0 +1,8 @@
FROM alpine:latest as builder
RUN apk add --no-cache ca-certificates openssl
RUN wget https://github.com/buger/goreplay/releases/download/v0.16.1/gor_0.16.1_x64.tar.gz -O gor.tar.gz
RUN tar xzf gor.tar.gz
FROM scratch
COPY --from=builder /goreplay .
ENTRYPOINT ["./goreplay"]
+26
View File
@@ -0,0 +1,26 @@
FROM golang:latest
RUN apt-get update && apt-get install ruby vim-common -y
# Install Java for middleware testing
RUN echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee /etc/apt/sources.list.d/webupd8team-java.list
RUN echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
RUN apt-get update -y
RUN echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections
RUN apt-get install oracle-java8-installer -y
RUN apt-get install flex bison -y
RUN wget http://www.tcpdump.org/release/libpcap-1.8.1.tar.gz && tar xzf libpcap-1.8.1.tar.gz && cd libpcap-1.8.1 && ./configure && make install
RUN go get github.com/google/gopacket
RUN go get -u golang.org/x/lint/golint
WORKDIR /go/src/github.com/buger/goreplay/
RUN wget http://archive.apache.org/dist/commons/io/binaries/commons-io-2.4-bin.tar.gz && tar xzf commons-io-2.4-bin.tar.gz && cd commons-io-2.4 && mv commons-io-2.4.jar /tmp/
RUN wget http://archive.apache.org/dist/commons/codec/binaries/commons-codec-1.9-bin.tar.gz && tar xzf commons-codec-1.9-bin.tar.gz
ADD . /go/src/github.com/buger/goreplay/
RUN javac -cp commons-io-2.4/commons-io-2.4.jar -cp commons-codec-1.9/commons-codec-1.9.jar ./examples/middleware/echo.java
RUN go get
+65
View File
@@ -0,0 +1,65 @@
gor & elasticsearch
===================
Prerequisites
-------------
- elasticsearch
- kibana (Get it here: http://www.elasticsearch.org/overview/kibana/)
- gor
elasticsearch
-------------
The default elasticsearch configuration is just fine for most workloads. You won't need clustering, sharding or something like that.
In this example we're installing it on our gor replay server which gives us the elasticsearch listener on _http://localhost:9200_
kibana
------
Kibana (elasticsearch analytics web-ui) is just as simple.
Download it, extract it and serve it via a simple webserver.
(Could be nginx or apache)
You could also use a shell, ```cd``` into the kibana directory and start a little quick and dirty python webserver with:
```
python -m SimpleHTTPServer 8000
```
In this example we're also choosing the gor replay server as our kibana host. If you choose a different server you'll have to point kibana to your elasticsearch host.
gor
---
Start your gor replay server with elasticsearch option:
```
./gor --input-raw :8000 --output-http http://staging.com --output-http-elasticsearch localhost:9200/gor
```
(You don't have to create the index upfront. That will be done for you automatically)
Now visit your kibana url, load the predefined dashboard from the gist https://gist.github.com/gottwald/b2c875037f24719a9616 and watch the data rush in.
Troubleshooting
---------------
The replay process may complain about __too many open files__.
That's because your typical linux shell has a small open files soft limit at 1024.
You can easily raise that when you do this before starting your _gor replay_ process:
```
ulimit -n 64000
```
Please be aware, this is not a permanent setting. It's just valid for the following jobs you start from that shell.
We reached the 1024 limit in our tests with a ubuntu box replaying about 9000 requests per minute. (We had very slow responses there, should be way more with fast responses)
+19
View File
@@ -0,0 +1,19 @@
GoReplay is an Open Source project licensed under the terms of
the LGPLv3 license. Please see <http://www.gnu.org/licenses/lgpl-3.0.html>
for license text.
As a special exception to the GNU Lesser General Public License version 3
("LGPL3"), the copyright holders of this Library give you permission to
convey to a third party a Combined Work that links statically or dynamically
to this Library without providing any Minimal Corresponding Source or
Minimal Application Code as set out in 4d or providing the installation
information set out in section 4e, provided that you comply with the other
provisions of LGPL3 and provided that you meet, for the Application the
terms and conditions of the license(s) which apply to the Application.
TLDR: You are free to use Gor subpackages like `byteutils` or `proto` in your commercial projects.
GoReplay Pro has a commercial-friendly license allowing private forks
and modifications of GoReplay. Please see https://goreplay.org/pro.html for
more detail. You can find the commercial license terms in COMM-LICENSE.
+95
View File
@@ -0,0 +1,95 @@
SOURCE = $(shell ls -1 *.go | grep -v _test.go)
SOURCE_PATH = /go/src/github.com/buger/goreplay/
PORT = 8000
FADDR = :8000
RUN = docker run -v `pwd`:$(SOURCE_PATH) -p 0.0.0.0:$(PORT):$(PORT) -i -t gor
BENCHMARK = BenchmarkRAWInput
TEST = TestRawListenerBench
VERSION = DEV-$(shell date +%s)
LDFLAGS = -ldflags "-X main.VERSION=$(VERSION) -extldflags \"-static\""
MAC_LDFLAGS = -ldflags "-X main.VERSION=$(VERSION)"
FADDR = ":8000"
release: release-x64 release-mac
release-bin:
docker run -v `pwd`:$(SOURCE_PATH) -t --env GOOS=linux --env GOARCH=amd64 -i gor go build -o gor -tags netgo $(LDFLAGS)
release-x64:
docker run -v `pwd`:$(SOURCE_PATH) -t --env GOOS=linux --env GOARCH=amd64 -i gor go build -o gor -tags netgo $(LDFLAGS) && tar -czf gor_$(VERSION)_x64.tar.gz gor && rm gor
release-x86:
docker run -v `pwd`:$(SOURCE_PATH) -t --env GOOS=linux --env GOARCH=386 -i gor go build -o gor -tags netgo $(LDFLAGS) && tar -czf gor_$(VERSION)_x86.tar.gz gor && rm gor
release-mac:
go build $(MAC_LDFLAGS) -o gor && tar -czf gor_$(VERSION)_mac.tar.gz gor && rm gor
install:
go install $(MAC_LDFLAGS)
build:
docker build -t gor -f Dockerfile.dev .
profile:
go build && ./gor --output-http="http://localhost:9000" --input-dummy 0 --input-raw :9000 --input-http :9000 --memprofile=./mem.out --cpuprofile=./cpu.out --stats --output-http-stats --output-http-timeout 100ms
lint:
$(RUN) golint $(PKG)
race:
$(RUN) go test ./... $(ARGS) -v -race -timeout 15s
test:
$(RUN) go test ./. -timeout 60s $(LDFLAGS) $(ARGS) -v
test_all:
$(RUN) go test ./... -timeout 60s $(LDFLAGS) $(ARGS) -v
testone:
$(RUN) go test ./... -timeout 4s $(LDFLAGS) -run $(TEST) $(ARGS) -v
cover:
$(RUN) go test $(ARGS) -race -v -timeout 15s -coverprofile=coverage.out
go tool cover -html=coverage.out
fmt:
$(RUN) gofmt -w -s ./..
vet:
$(RUN) go vet
bench:
$(RUN) go test $(LDFLAGS) -v -run NOT_EXISTING -bench $(BENCHMARK) -benchtime 5s
profile_test:
$(RUN) go test $(LDFLAGS) -run $(TEST) ./raw_socket_listener/. $(ARGS) -memprofile mem.mprof -cpuprofile cpu.out
$(RUN) go test $(LDFLAGS) -run $(TEST) ./raw_socket_listener/. $(ARGS) -c
# Used mainly for debugging, because docker container do not have access to parent machine ports
run:
$(RUN) go run $(LDFLAGS) $(SOURCE) --input-dummy=0 --output-http="http://localhost:9000" --input-raw-track-response --input-raw 127.0.0.1:9000 --verbose --debug --middleware "./examples/middleware/echo.sh" --output-file requests.gor
run-2:
$(RUN) go run $(LDFLAGS) $(SOURCE) --input-raw :8000 --input-raw-bpf-filter "dst port 8000" --output-stdout --output-http "http://localhost:8000" --input-dummy=0
run-3:
sudo -E go run $(SOURCE) --input-tcp :27001 --output-stdout
run-arg:
sudo -E go run $(SOURCE) $(ARGS)
file-server:
go run $(SOURCE) file-server $(FADDR)
readpcap:
go run $(SOURCE) --input-raw $(FILE) --input-raw-track-response --input-raw-engine pcap_file --output-stdout
record:
$(RUN) go run $(SOURCE) --input-dummy=0 --output-file=requests.gor --verbose --debug
replay:
$(RUN) go run $(SOURCE) --input-file=requests.bin --output-tcp=:9000 --verbose -h
bash:
$(RUN) /bin/bash
+4
View File
@@ -0,0 +1,4 @@
web: python -m SimpleHTTPServer 8000
replayed_web: python -m SimpleHTTPServer 8001
listener: sudo -E go run ./bin/gor.go --input-raw :8000 --output-tcp :8002 --verbose
replay: go run ./bin/gor.go --input-tcp :8002 --output-http localhost:8001 --verbose
+75 -75
View File
@@ -1,75 +1,75 @@
## About
Gor is simple http traffic replication tool written in Go.
Its main goal to replay traffic from production servers to staging and dev environments.
Now you can test your code on real user sessions in an automated and repeatable fashion.
**No more falling down in production!**
Gor consists of 2 parts: listener and replay servers.
Listener catch http traffic from given port in real-time and send it to replay server via UDP.
Replay server forwards traffic to given address.
## Basic example
```bash
# Run on servers where you want to catch traffic. You can run it on each `web` machine.
sudo gor listen -p 80 -r replay.server.local:28020
# Replay server (replay.server.local).
gor replay -f http://staging.server
```
## Advanced use
### Rate limiting
Replay server support rate limiting. It can be useful if you want forward only part of production traffic, not to overload staging environment. You can specify desired request per second using "|" operator after server address:
```
# staging.server not get more than 10 requests per second
gor replay -f "http://staging.server|10"
```
### Forward to multiple addresses
You can forward traffic to multiple endpoints. Just separate addresses by coma.
```
gor replay -f "http://staging.server|10,http://dev.server|5"
```
## Additional help
```
$ gor listen -h
Usage of ./bin/gor-linux:
-i="any": By default it try to listen on all network interfaces.To get list of interfaces run `ifconfig`
-p=80: Specify the http server port whose traffic you want to capture
-r="localhost:28020": Address of replay server.
```
```
$ gor replay -h
Usage of ./bin/gor-linux:
-f="http://localhost:8080": http address to forward traffic.
You can limit requests per second by adding `|#{num}` after address.
If you have multiple addresses with different limits. For example: http://staging.example.com|100,http://dev.example.com|10
-ip="0.0.0.0": ip addresses to listen on
-p=28020: specify port number
```
## FAQ
### Why `gor listener` requires sudo or root access?
Listener works by sniffing traffic from given port. Its accessible only using sudo or root access.
### Do you support all http request types?
Right now it support only "GET" requests.
## TODO
Use buffering for request throttling instead of simple rate limiting.
Better stats
Optimize for load testing cases
[![GitHub release](https://img.shields.io/github/release/buger/gor.svg?maxAge=3600)](https://github.com/buger/goreplay/releases) [![codebeat](https://codebeat.co/badges/6427d589-a78e-416c-a546-d299b4089893)](https://codebeat.co/projects/github-com-buger-gor) [![Go Report Card](https://goreportcard.com/badge/github.com/buger/gor)](https://goreportcard.com/report/github.com/buger/gor) [![Join the chat at https://gitter.im/buger/gor](https://badges.gitter.im/buger/gor.svg)](https://gitter.im/buger/gor?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com)
![Go Replay](http://i.imgur.com/ZG2ki5n.png)
## https://goreplay.org/
## We just released a new version, see announcement https://leonsbox.com/goreplay-v0-16-and-4th-anniversary-5408b1fd72e0
## About
GoReplay is the simplest and safest way to test your app using real traffic before you put it into production.
As your application grows, the effort required to test it also grows exponentially. GoReplay offers you the simple idea of reusing your existing traffic for testing, which makes it incredibly powerful. Our state of art technique allows you to analyze and record your application traffic without affecting it. This eliminates the risks that come with putting a third party component in the critical path.
GoReplay increases your confidence in code deployments, configuration changes and infrastructure changes. Did we mention that no coding is required?
Here is basic workflow: The listener server catches http traffic and sends it to the replay server or saves to file. The replay server forwards traffic to a given address.
![Diagram](http://i.imgur.com/9mqj2SK.png)
Check [latest documentation](http://github.com/buger/goreplay/wiki).
## Installation
Download latest binary from https://github.com/buger/goreplay/releases or [compile by yourself](https://github.com/buger/goreplay/wiki/Compilation).
## Getting started
The most basic setup will be `sudo ./gor --input-raw :8000 --output-stdout` which acts like tcpdump.
If you already have test environment you can start replaying: `sudo ./gor --input-raw :8000 --output-http http://staging.env`.
See the our [documentation](https://github.com/buger/goreplay/wiki/) and [Getting started](https://github.com/buger/goreplay/wiki/Getting-Started) page for more info.
## Newsletter
Subscribe to our [newsletter](https://www.getdrip.com/forms/89690474/submissions/new) to stay informed about the latest features and changes to Gor project.
## Want to Upgrade?
We have created a [GoReplay PRO](https://goreplay.org/pro.html) extension which provides additional features such as support for binary protocols like Thrift or ProtocolBuffers, saving and replaying from cloud storage, TCP sessions replication, etc. The PRO version also includes a commercial-friendly license, dedicated support, and it also allows you to support high-quality open source development.
## Problems?
If you have a problem, please review the [FAQ](https://github.com/buger/goreplay/wiki/FAQ) and [Troubleshooting](https://github.com/buger/goreplay/wiki/Troubleshooting) wiki pages. Searching the [issues](https://github.com/buger/goreplay/issues) for your problem is also a good idea.
All bug-reports and suggestions should go through Github Issues or our [Google Group](https://groups.google.com/forum/#!forum/gor-users) (you can just send email to gor-users@googlegroups.com).
If you have a private question feel free to send email to support@gortool.com.
## Contributing
1. Fork it
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Added some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create new Pull Request
## Companies using Gor
* [GOV.UK](https://www.gov.uk) - UK Government Digital Service
* [theguardian.com](http://theguardian.com) - Most popular online newspaper in the UK
* [TomTom](http://www.tomtom.com/) - Global leader in navigation, traffic and map products, GPS Sport Watches and fleet management solutions.
* [3SCALE](http://www.3scale.net/) - API infrastructure to manage your APIs for internal or external users
* [Optionlab](http://www.opinionlab.com) - Optimize customer experience and drive engagement across multiple channels
* [TubeMogul](http://tubemogul.com) - Software for Brand Advertising
* [Videology](http://www.videologygroup.com/) - Video advertising platform
* [ForeksMobile](http://foreksmobile.com/) - One of the leading financial application development company in Turkey
* [Granify](http://granify.com) - AI backed SaaS solution that enables online retailers to maximise their sales
* And many more!
If you are using Gor, we are happy to add you to the list and share your story, just write to: hello@goreplay.org
## Author
Leonid Bugaev, [@buger](https://twitter.com/buger), https://leonsbox.com
+43
View File
@@ -0,0 +1,43 @@
// Package byteutils probvides helpers for working with byte slices
package byteutils
// Cut elements from slice for a given range
func Cut(a []byte, from, to int) []byte {
copy(a[from:], a[to:])
a = a[:len(a)-to+from]
return a
}
// Insert new slice at specified position
func Insert(a []byte, i int, b []byte) []byte {
a = append(a, make([]byte, len(b))...)
copy(a[i+len(b):], a[i:])
copy(a[i:i+len(b)], b)
return a
}
// Replace function unlike bytes.Replace allows you to specify range
func Replace(a []byte, from, to int, new []byte) []byte {
lenDiff := len(new) - (to - from)
if lenDiff > 0 {
// Extend if new segment bigger
a = append(a, make([]byte, lenDiff)...)
copy(a[to+lenDiff:], a[to:])
copy(a[from:from+len(new)], new)
return a
}
if lenDiff < 0 {
copy(a[from:], new)
copy(a[from+len(new):], a[to:])
return a[:len(a)+lenDiff]
}
// same size
copy(a[from:], new)
return a
}
+32
View File
@@ -0,0 +1,32 @@
package byteutils
import (
"bytes"
"testing"
)
func TestCut(t *testing.T) {
if !bytes.Equal(Cut([]byte("123456"), 2, 4), []byte("1256")) {
t.Error("Should properly cut")
}
}
func TestInsert(t *testing.T) {
if !bytes.Equal(Insert([]byte("123456"), 2, []byte("abcd")), []byte("12abcd3456")) {
t.Error("Should insert into middle of slice")
}
}
func TestReplace(t *testing.T) {
if !bytes.Equal(Replace([]byte("123456"), 2, 4, []byte("ab")), []byte("12ab56")) {
t.Error("Should replace when same length")
}
if !bytes.Equal(Replace([]byte("123456"), 2, 4, []byte("abcd")), []byte("12abcd56")) {
t.Error("Should replace when replacement length bigger")
}
if !bytes.Equal(Replace([]byte("123456"), 2, 5, []byte("ab")), []byte("12ab6")) {
t.Error("Should replace when replacement length bigger")
}
}
+7
View File
@@ -0,0 +1,7 @@
dependencies:
pre:
- sudo apt-get install libpcap-dev -y
test:
override:
- sudo bash -l -c "export GOPATH='/home/ubuntu/.go_workspace:/usr/local/go_workspace:/home/ubuntu/.go_project' && GORACE='halt_on_error=1' /usr/local/go/bin/go test ./... -v -timeout 120s -race"
+1
View File
@@ -0,0 +1 @@
docs.goreplay.org
+49
View File
@@ -0,0 +1,49 @@
Think about Gor more like a network analyzer or tcpdump on steroids, it is not a proxy and does not affect your app anyhow. You specify application port, and it will capture and replay incoming data.
Simplest setup will be:
```bash
# Run on servers where you want to catch traffic. You can run it on every `web` machine.
sudo gor --input-raw :80 --output-http http://staging.com
```
It will record and replay traffic from the same machine. However, it is possible to use [[Aggregator-forwarder setup]], when Gor on your web machines forward traffic to Gor aggregator instance running on the separate server.
> You may notice that it require `sudo`: to analyze network Gor need permissions which available only to root users. However, it is possible to configure Gor [beign run for non-root users](Running as a non-root user).
### Forwarding to multiple addresses
You can forward traffic to multiple endpoints.
```
gor --input-tcp :28020 --output-http "http://staging.com" --output-http "http://dev.com"
```
### Splitting traffic
By default, it will send same traffic to all outputs, but you have options to equally split it (round-robin) using `--split-output` option.
```
gor --input-raw :80 --output-http "http://staging.com" --output-http "http://dev.com" --split-output true
```
### Tracking responses
By default `input-raw` does not intercept responses, only requests. You can turn response tracking using `--input-raw-track-response` option. When enable you will be able to access response information in middleware and `output-file`.
### Traffic interception engine
By default, Gor will use `libpcap` for intercepting traffic, it should work in most cases. If you have any troubles with it, you may try alternative engine: `raw_socket`.
```
sudo gor --input-raw :80 --input-raw-engine "raw_socket" --output-http "http://staging.com"
```
You can read more about [[Replaying HTTP traffic]].
### Tracking original IP addresses
You can use `--input-raw-realip-header` option to specify header name: If not blank, injects header with given name and real IP value to the request payload. Usually, this header should be named: `X-Real-IP`, but you can specify any name.
`gor --input-raw :80 --input-raw-realip-header "X-Real-IP" ...`
***
Also you may want to know about [[Rate limiting]], [[Request rewriting]] and [[Request filtering]]
+30
View File
@@ -0,0 +1,30 @@
We provide pre-compiled binaries for Mac and Linux, but you are free to compile Gor by yourself.
Gor is written using Go, so first you need to download it from here https://golang.org/, use the latest stable version.
The only Gor dependency is [libpcap](https://github.com/the-tcpdump-group/libpcap), which is the interface to various kernel packet capture mechanisms, and https://github.com/google/gopacket, which is a Go wrapper around libpcap. Latest libpcap version can be obtained at http://www.tcpdump.org/release/. Libpcap itself depend on `flex` and `bison` packages, many operating systems already have them installed.
```bash
# Fetch libpcap dependencies. Depending on your OS, instead of `apt` you will use `yum` or `rpm`, or `brew` on Mac.
sudo apt-get install flex bison -y
# Download latest stable release, compile and install it
wget http://www.tcpdump.org/release/libpcap-1.7.4.tar.gz && tar xzf libpcap-1.7.4.tar.gz
cd libpcap-1.7.4
./configure && make install
# Lets fetch Gor source code
mkdir $HOME/gocode
# See more information about GOPATH https://github.com/golang/go/wiki/GOPATH
export GOPATH=$HOME/gocode
# Fetch code from the Github
go get github.com/buger/gor
# Compile from source
cd $HOME/gocode/src/github.com/buger/gor
go build LDFLAGS = -ldflags "-extldflags \"-static\""
```
After you finished, you should see `gor` binary in current directory.
+39
View File
@@ -0,0 +1,39 @@
## STEP 1: Install Docker
For local development we recommend to use Docker.
If you don’t have it you can read how to install it here:
https://docs.docker.com/engine/getstarted/step_one/#step-3-verify-your-installation
## STEP 2: Download repository
`git clone git@github.com:buger/goreplay.git`
## STEP 3: Setup container
```
cd ./goreplay
make build
```
## Testing
To run tests execute next command:
```
make test
```
You can copy the command that is produced and modify it. For example, if you need to run one test copy the command and add `-run TestName`, e.g.:
```
docker run -v `pwd`:/go/src/github.com/buger/gor/ -p 0.0.0.0:8000:8000 -t -i gor:go go test ./. -run TestEmitterFiltered -timeout 60s -ldflags "-X main.VERSION=DEV-1482398347 -extldflags \"-static\"" -v
```
## Building
To get a binary file run
```
make release-bin
```
+26
View File
@@ -0,0 +1,26 @@
Sometimes it makes sense to use separate Gor instance for replaying traffic and performing things like load testing, so your production machines do not spend precious resources. It is possible to configure Gor on your web machines forward traffic to Gor aggregator instance running on the separate server.
```bash
# Run on servers where you want to catch traffic. You can run it on each `web` machine.
sudo gor --input-raw :80 --output-tcp replay.local:28020
# Replay server (replay.local).
gor --input-tcp replay.local:28020 --output-http http://staging.com
```
If you have multiple replay machines you can split traffic among them using `--split-output` option: it will equally split all incoming traffic to all outputs using round robin algorithm.
```
gor --input-raw :80 --split-output --output-tcp replay1.local:28020 --output-tcp replay2.local:28020
```
[GoReplay PRO](https://goreplay.org/pro.html) support accurate recording and replaying of tcp sessions, and when `--recognize-tcp-sessions` option is passed, instead of round-robin it will use a smarter algorithm which ensures that same sessions will be sent to the same replay instance.
In case if you are planning a large load testing, you may consider use separate master instance which will control Gor slaves which actually replay traffic. For example:
```
# This command will read multiple log files, replay them on 10x speed and loop them if needed for 30 seconds, and will distributed traffic (tcp session aware) among multiple workers
gor --input-file logs_from_multiple_machines.*|1000% --input-file-loop --exit-after 30s --recognize-tcp-sessions --split-output --output-tcp worker1.local --output-tcp worker2.local:27017 --output-tcp worker3.local:27017 ... --output-tcp workerN.local:27017
# worker
gor --input-tcp :27017 --ouput-http load_test.target
```
+38
View File
@@ -0,0 +1,38 @@
Gor can export requests and replayed response data to ElasticSearch:
```
./gor --input-raw :8000 --output-http http://staging.com --output-http-elasticsearch localhost:9200/gor
```
You don't have to create the index upfront. That will be done for you automatically.
### Format
Following structure represents ES format:
```
type ESRequestResponse struct {
ReqURL string `json:"Req_URL"`
ReqMethod string `json:"Req_Method"`
ReqUserAgent string `json:"Req_User-Agent"`
ReqAcceptLanguage string `json:"Req_Accept-Language,omitempty"`
ReqAccept string `json:"Req_Accept,omitempty"`
ReqAcceptEncoding string `json:"Req_Accept-Encoding,omitempty"`
ReqIfModifiedSince string `json:"Req_If-Modified-Since,omitempty"`
ReqConnection string `json:"Req_Connection,omitempty"`
ReqCookies string `json:"Req_Cookies,omitempty"`
RespStatus string `json:"Resp_Status"`
RespStatusCode string `json:"Resp_Status-Code"`
RespProto string `json:"Resp_Proto,omitempty"`
RespContentLength string `json:"Resp_Content-Length,omitempty"`
RespContentType string `json:"Resp_Content-Type,omitempty"`
RespTransferEncoding string `json:"Resp_Transfer-Encoding,omitempty"`
RespContentEncoding string `json:"Resp_Content-Encoding,omitempty"`
RespExpires string `json:"Resp_Expires,omitempty"`
RespCacheControl string `json:"Resp_Cache-Control,omitempty"`
RespVary string `json:"Resp_Vary,omitempty"`
RespSetCookie string `json:"Resp_Set-Cookie,omitempty"`
Rtt int64 `json:"RTT"`
Timestamp time.Time
}
```
+32
View File
@@ -0,0 +1,32 @@
### What OS are supported?
Gor will run everywhere where [libpcap](http://www.tcpdump.org/) works, and it works on most of the platforms. However, currently, we test it on Linux and Mac. See more about [[Compilation]].
### Why does the `--input-raw` requires sudo or root access?
Listener works by sniffing traffic from a given port. It's accessible
only by using sudo or root access. But it is possible to [[Running as non root user]].
### How do you deal with user session to replay the traffic correctly?
You can rewrite session related headers/params to match your staging environment. If you require custom logic (e.g random token based auth) follow this discussion: https://github.com/buger/gor/issues/154
### Can I use Gor to intercept SSL traffic?
Basic idea is that SSL was made to protect itself from traffic interception. There 2 options:
1. Move SSL handling to proxy like Nginx or Amazon ELB. And allow Gor to listen on upstreams.
2. Use `--input-http` so you can duplicate request payload directly from your app to Gor, but it will require your app modifications.
More can be find here: https://github.com/buger/gor/issues/85
### Is there a limit for size of HTTP request when using output-http?
Due to the fact that Gor can't guarantee interception of all packets, for large payloads > 200kb there is chance of missing some packets and corrupting body. Treat it as a feature and chance to test broken bodies handling :)
The only way to guarantee delivery is using `--input-http`, but you will miss some features.
### I'm getting 'too many open files' error
Typical Linux shell has a small open files soft limit at 1024. You can easily raise that when you do this before starting your gor replay process:
ulimit -n 64000
More about ulimit: http://www.thecodingmachine.com/solving-the-too-many-open-files-exception-in-red5-or-any-other-application/
### The CPU average across my load-balanced targets is higher than the source
If you are replaying traffic from multiple listeners to a load-balanced target and you use sticky sessions, you may observe that the target servers have a higher CPU load than the listener servers. This may be because the sticky session cookie of the original load balancer is not honored by the target load balancer thus resulting in requests that would normally hit the same target server hitting different servers on the backend thus reducing some caching benefits gained via the load balancing. Try running just one listener against one replay target and see if the CPU utilization comparison is more accurate.
Also see [[Troubleshooting]].
+74
View File
@@ -0,0 +1,74 @@
#### Overview
Middleware is a program that accepts request and response payload at STDIN and emits modified requests at STDOUT. You can implement any custom logic like stripping private data, advanced rewriting, support for oAuth and etc. Check examples [included into our repo](https://github.com/buger/gor/tree/master/examples/middleware).
```
Original request +--------------+
+-------------+----------STDIN---------->+ |
| Gor input | | Middleware |
+-------------+----------STDIN---------->+ |
Original response (1) +------+---+---+
| ^
+-------------+ Modified request v |
| Gor output +<---------STDOUT-----------------+ |
+-----+-------+ |
| |
| Replayed response |
+------------------STDIN----------------->----+
```
(1): Original responses will only be sent to the middleware if the `--input-raw-track-response` option is specified.
Middleware can be written in any language, see `examples/middleware` folder for examples.
Middleware program should accept the fact that all communication with Gor is asynchronous, there is no guarantee that original request and response messages will come one after each other. Your app should take care of the state if logic depends on original or replayed response, see `examples/middleware/token_modifier.go` as example.
Simple bash echo middleware (returns same request) will look like this:
```bash
while read line; do
echo $line
done
```
Middleware can be enabled using `--middleware` option, by specifying path to executable file:
```
gor --input-raw :80 --middleware "/opt/middleware_executable" --output-http "http://staging.server"
```
#### Communication protocol
All messages should be hex encoded, new line character specifieds the end of the message, eg. new message per line.
Decoded payload consist of 2 parts: header and HTTP payload, separated by new line character.
Example request payload:
```
1 932079936fa4306fc308d67588178d17d823647c 1439818823587396305
GET /a HTTP/1.1
Host: 127.0.0.1
```
Example response payload (note: you will only receive this if you specify `--input-raw-track-response`)
```
2 8e091765ae902fef8a2b7d9dd960e9d52222bd8c 1439818823587996305 2782013
HTTP/1.1 200 OK
Date: Mon, 17 Aug 2015 13:40:23 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8
```
Header contains request meta information separated by spaces. First value is payload type, possible values: `1` - request, `2` - original response, `3` - replayed response.
Next goes request id: unique among all requests (sha1 of time and Ack), but remain same for original and replayed response, so you can create associations between request and responses. The third argument is the time when request/response was initiated/received. Forth argument is populated only for responses and means latency.
HTTP payload is unmodified HTTP requests/responses intercepted from network. You can read more about request format [here](http://www.jmarshall.com/easy/http/), [here](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) and [here](http://www.w3.org/Protocols/rfc2616/rfc2616.html). You can operate with payload as you want, add headers, change path, and etc. Basically you just editing a string, just ensure that it is RCF compliant.
At the end modified (or untouched) request should be emitted back to STDOUT, keeping original header, and hex-encoded. If you want to filter request, just not send it. Emitting responses back is required, even if you did not touch them.
#### Advanced example
Imagine that you have auth system that randomly generate access tokens, which used later for accessing secure content. Since there is no pre-defined token value, naive approach without middleware (or if middleware use only request payloads) will fail, because replayed server have own tokens, not synced with origin. To fix this, our middleware should take in account responses of replayed and origin server, store `originalToken -> replayedToken` aliases and rewrite all requests using this token to use replayed alias. See [examples/middleware/token_modifier.go](https://github.com/buger/gor/tree/master/examples/middleware/token_modifier.go) and [middleware_test.go#TestTokenMiddleware](https://github.com/buger/gor/tree/master/middleware_test.go) as example of described scheme.
***
You may also read about [[Request filtering]], [[Rate limiting]] and [[Request rewriting]].
+37
View File
@@ -0,0 +1,37 @@
Rate limiting can be useful if you only want to forward parts of incoming traffic, for example, to not overload your test environment. There are two strategies: dropping random requests or dropping fractions of requests based on Header or URL param value.
### Dropping random requests
Every input and output support random rate limiting.
There are two limiting algorithms: absolute or percentage based.
**Absolute**: If for current second it reached specified requests limit - disregard the rest, on next second counter reset.
**Percentage**: For input-file it will slowdown or speedup request execution, for the rest it will use the random generator to decide if request pass or not based on the chance you specified.
You can specify your desired limit using the "|" operator after the server address, see examples below.
#### Limiting replay using absolute number
```
# staging.server will not get more than ten requests per second
gor --input-tcp :28020 --output-http "http://staging.com|10"
```
#### Limiting listener using percentage based limiter
```
# replay server will not get more than 10% of requests
# useful for high-load environments
gor --input-raw :80 --output-tcp "replay.local:28020|10%"
```
### Consistent limiting based on Header or URL param value
If you have unique user id (like API key) stored in header or URL you can consistently forward specified percent of traffic only for the fraction of this users.
Basic formula looks like this: `FNV32-1A_hashing(value) % 100 >= chance`. Examples:
```
# Limit based on header value
gor --input-raw :80 --output-tcp "replay.local:28020|10%" --http-header-limiter "X-API-KEY: 10%"
# Limit based on header value
gor --input-raw :80 --output-tcp "replay.local:28020|10%" --http-param-limiter "api_key: 10%"
```
When limiting based on header or param only percentage based limiting supported.
+46
View File
@@ -0,0 +1,46 @@
Gor can replay HTTP traffic using `--output-http` option:
```bash
sudo ./gor --input-raw :8000 --output-http="http://staging.env"
```
You can [filter](Request filtering), [rate limit](Rate limiting) and [rewrite](Request rewriting) requests on the fly.
### HTTP output workers
By default Gor creates a dynamic pool of workers: it starts with 10 and creates more HTTP output workers when the HTTP output queue length is greater than 10. The number of workers created (N) is equal to the queue length at the time which it is checked and found to have a length greater than 10. The queue length is checked every time a message is written to the HTTP output queue. No more workers will be spawned until that request to spawn N workers is satisfied. If a dynamic worker cannot process a message at that time, it will sleep for 100 milliseconds. If a dynamic worker cannot process a message for 2 seconds it dies.
You may specify fixed number of workers using `--output-http-workers=20` option.
### Following redirects
By default Gor will ignore all redirects since they are handled by clients using your app, but in scenarios where your replayed environment introduces new redirects, you can enable them like this:
```
gor --input-tcp replay.local:28020 --output-http http://staging.com --output-http-redirects 2
```
The given example will follow up to 2 redirects per request.
### HTTP timeouts
By default http timeout for both request and response is 5 seconds. You can override it like this:
```
gor --input-tcp replay.local:28020 --output-http http://staging.com --output-http-timeout 30s
```
### Response buffer
By default, to reduce memory consumption, internal HTTP client will fetch max 200kb of the response body (used if you use middleware), by you can increase limit using `--output-http-response-buffer` option (accepts number of bytes).
### Basic Auth
If your development or staging environment is protected by Basic Authentication then those credentials can be injected in during the replay:
```
gor --input-raw :80 --output-http "http://user:pass@staging.com"
```
Note: This will overwrite any Authorization headers in the original request.
### Multiple domains support
If you app accepts traffic from multiple domains, and you want to keep original headers, there is specific `--http-original-host` with tells Gor do not touch Host header at all.
***
You may also read about [[Saving and Replaying from file]]
+35
View File
@@ -0,0 +1,35 @@
Filtering is useful when you need to capture only specific part of traffic, like API requests. It is possible to filter by URL, HTTP header or HTTP method.
#### Allow url regexp
```
# only forward requests being sent to the /api endpoint
gor --input-raw :8080 --output-http staging.com --http-allow-url /api
```
#### Disallow url regexp
```
# only forward requests NOT being sent to the /api... endpoint
gor --input-raw :8080 --output-http staging.com --http-disallow-url /api
```
#### Filter based on regexp of header
```
# only forward requests with an api version of 1.0x
gor --input-raw :8080 --output-http staging.com --http-allow-header api-version:^1\.0\d
# only forward requests NOT containing User-Agent header value "Replayed by Gor"
gor --input-raw :8080 --output-http staging.com --http-disallow-header "User-Agent: Replayed by Gor"
```
#### Filter based on HTTP method
Requests not matching a specified whitelist can be filtered out. For example to strip non-nullipotent requests:
```
gor --input-raw :80 --output-http "http://staging.server" \
--http-allow-method GET \
--http-allow-method OPTIONS
```
-----
You may also read about [[Request rewriting]], [[Rate limiting]] and [[Middleware]]
+38
View File
@@ -0,0 +1,38 @@
Gor supports rewriting of URLs, URL params and headers, see below.
Rewriting may be useful if you test environment does not have the same data as your production, and you want to perform all actions in the context of `test` user: for example rewrite all API tokens to some test value. Other possible use cases are toggling features on/off using custom headers or rewriting URL's if they changed in the new environment.
For more complex logic you can use [Middleware](middleware.md).
#### Rewrite URL based on a mapping
`--http-rewrite-url` expects value in "<search>:<replace>" format: ":" is a dilimiter. In `<replace>` section you may use captured regexp group values. This works similar to `replace` method in Javascript or `gsub` in Ruby.
```
# Rewrites all `/v1/user/<user_id>/ping` requests to `/v2/user/<user_id>/ping`
gor --input-raw :8080 --output-http staging.com --http-rewrite-url /v1/user/([^\\/]+)/ping:/v2/user/$1/ping
```
#### Set URL param
Set request url param, if param already exists it will be overwritten.
```
gor --input-raw :8080 --output-http staging.com --http-set-param api_key=1
```
#### Set Header
Set request header, if header already exists it will be overwritten. May be useful if you need to identify requests generated by Gor or enable feature flagged functionality in an application:
```
gor --input-raw :80 --output-http "http://staging.server" \
--http-set-header "User-Agent: Replayed by Gor" \
--http-set-header "Enable-Feature-X: true"
```
#### Host header
Host header gets special treatment. By default Host get set to the value specified in --output-http. If you manually set --http-set-header "Host: anonther.com", Gor will not override Host value.
If you app accepts traffic from multiple domains, and you want to keep original headers, there is specific `--http-original-host` with tells Gor do not touch Host header at all.
***
You may also read about [[Request filtering]], [[Rate limiting]] and [[Middleware]]
+17
View File
@@ -0,0 +1,17 @@
You can enable Gor for non-root users in a secure method by using the following commands
```
# Following commands assume that you put `gor` binary to /usr/local/bin
add gor
addgroup <username> gor
chgrp gor /usr/local/bin/gor
chmod 0750 /usr/local/bin/gor
setcap "cap_net_raw,cap_net_admin+eip" /usr/local/bin/gor
```
As a brief explanation of the above.
* We create a group called gor.
* We then add the user you want to the new group so they will be able to use gor without sudo
* We then change the user/group of gor binary the new group.
* We then make sure the permissions are set on gor binary so that members of the group can execute it but other normal users cannot.
* We then use `setcap` to give the CAP_NET_RAW and CAP_NET_ADMIN privilege to the executable when it runs. This is so that Gor can open its raw socket which is not normally permitted unless you are root.
+105
View File
@@ -0,0 +1,105 @@
You can save requests to file, and replay them later. While replaying it will preserve the original time differences between requests. If you apply [percentage based limiting](Rate Limiting) timing between requests will be reduced or increased appropriately: this approach opens possibilities like load testing, see below.
```bash
# write to file
gor --input-raw :80 --output-file requests.log
# read from file
gor --input-file requests.gor --output-http "http://staging.com"
```
By default Gor writes files in chunks. This configurable using `--output-file-append` option: the flushed chunk is appended to existence file or not. The default is **false**. By default, `--output-file` flushes each chunk to a different path.
```bash
gor ... --output-file %Y%m%d.log
# append false
20140608_0.log
20140608_1.log
20140609_0.log
20140609_1.log
```
This makes parallel file processing easy. But if you want to disable this behavior, you can disable it by adding `--output-file-append` option:
```bash
gor ... --output-file %Y%m%d.log --output-file-append
# append true
20140608.log
20140609.log
```
If you run gor multiple times, and it finds existing files, it will continue from last known index.
### Chunk size
You can set chunk limits using `--output-file-size-limit` and `--output-file-queue-limit` options.
The length of the chunk queue and the size of each chunk, respectively. The default values are 256 and 32mb, respectively. The suffixes “k” (KB), “m” (MB), and “g” (GB) can be used for `output-file-size-limit`.
If you want to have only size constraint, you can set `--output-file-queue-limit` to 0, and vice versa.
```bash
gor --input-raw :80 --output-file %Y-%m-%d.gz --output-file-size-limit 256m --output-file-queue-limit 0
```
### Using date variables in file names
For example, you can tell to create new file each hour: `--output-file /mnt/logs/requests-%Y-%m-%d-%H.log`
It will create new file for each hour: requests-2016-06-01-12.log, requests-2016-06-01-13.log, ...
The time format used as part of the file name. The following characters are replaced with actual values when the file is created:
* `%Y`: year including the century (at least 4 digits)
* `%m`: month of the year (01..12)
* `%d`: Day of the month (01..31)
* `%H`: Hour of the day, 24-hour clock (00..23)
* `%M`: Minute of the hour (00..59)
* `%S`: Second of the minute (00..60)
The default format is `%Y%m%d%H`, which creates one file per hour.
### GZIP compression
To read or write GZIP compressed files ensure that file extension ends with ".gz": `--output-file log.gz`
### Replaying from multiple files
`--input-file` accepts file pattern, for example: `--input-file logs-2016-05-*`: it will replay all the files, sorting them in lexicographical order.
### Buffered file output
Gor has memory buffer when it writes to file, and continuously flush changes to the file. Flushing to file happens if the buffer is filled, forced flush every 1 second, or if Gor is closed. You can change it using `--output-file-flush-interval` option. It most cases it should not be touched.
### File format
HTTP requests stored as it is, plain text: headers and bodies. Requests separated by `\n🐵🙈🙉\n` line (using such sequence for uniqueness and fun). Before each request goes single line with meta information containing payload type (1 - request, 2 - response, 3 - replayed response), unique request ID (request and response have the same) and timestamp when request was made. An example of 2 requests:
```
1 d7123dasd913jfd21312dasdhas31 127345969\n
GET / HTTP/1.1\r\n
\r\n
\n
🐵🙈🙉
\n
POST /upload HTTP/1.1\r\n
Content-Length: 7\r\n
Host: www.w3.org\r\n
\r\n
a=1&b=2
```
Note that technically \r and \n symbols are invisible, and indicate new lines. I made them visible in example just to show how it looks on byte level.
Making it text friendly allows writing simple parsers and use console tools like `grep` to do an analysis. You can even edit them manually, but be sure that your file editor does not change line endings.
## Performance testing
Currently, this functionality supported only by `input-file` and only when using percentage based limiter. Unlike default limiter for `input-file` instead of dropping requests it will slowdown or speedup request emitting. Note that **limiter is applied to input**:
```
# Replay from file on 2x speed
gor --input-file "requests.gor|200%" --output-http "staging.com"
```
Use `--stats --output-http-stats` to see latency stats.
### Looping files for replaying indefinitely
You can loop the same set of files, so when the last one replays all the requests, it will not stop, and will start from first one again. Having the only small amount of requests you can do extensive performance testing.
Pass `--input-file-loop` to make it work.
***
You may also read about [[Capturing and replaying traffic]] and [[Rate limiting]]
+90
View File
@@ -0,0 +1,90 @@
Gor can report stats on the `output-tcp` and `output-http` request queues. Stats are reported to the console every 5 seconds in the form `latest,mean,max,count,count/second` by using the `--output-http-stats` and `--output-tcp-stats` options.
Examples:
```
2014/04/23 21:17:50 output_tcp:latest,mean,max,count,count/second
2014/04/23 21:17:50 output_tcp:0,0,0,0,0
2014/04/23 21:17:55 output_tcp:1,1,2,68,13
2014/04/23 21:18:00 output_tcp:1,1,2,92,18
2014/04/23 21:18:05 output_tcp:1,1,2,119,23
```
```
2014/04/23 21:19:46 output_http:latest,mean,max,count,count/second
2014/04/23 21:19:46 output_http:0,0,0,0,0
2014/04/23 21:19:51 output_http:0,0,0,0,0
2014/04/23 21:19:56 output_http:0,0,0,0,0
2014/04/23 21:20:01 output_http:1,0,1,50,10
2014/04/23 21:20:06 output_http:1,1,4,72,14
2014/04/23 21:20:11 output_http:1,0,1,179,35
2014/04/23 21:20:16 output_http:1,0,1,148,29
2014/04/23 21:20:21 output_http:1,1,2,91,18
2014/04/23 21:20:26 output_http:1,1,2,150,30
2014/04/23 21:18:15 output_http:100,99,100,70,14
2014/04/23 21:18:21 output_http:100,99,100,55,11
```
### How can I tell if I have bottlenecks?
Key areas that sometimes experience bottlenecks are the output-tcp and output-http functions which have internal queues for requests. Each queue has an upper limit of 100. Enable stats reporting to see if any queues are experiencing bottleneck behavior.
#### Output HTTP bottlenecks
When running a Gor replay the output-http feature may bottleneck if:
* the replay has inadequate bandwidth. If the replay is receiving or sending more messages than its network adapter can handle the output-http-stats may report that the output-http queue is filling up. See if there is a way to upgrade the replay's bandwidth.
* with `--output-http-workers` set to anything other than `-1` the `-output-http` target is unable to respond to messages in a timely manner. The http output workers which take messages off the output-http queue, process the request, and ensure that the request did not result in an error may not be able to keep up with the number of incoming requests. If the replay is not using dynamic worker scaling (`--output-http-workers=-1`) The optimal number of output-http-workers can be determined with the formula `output-workers = (Average number of requests per second)/(Average target response time per second)`.
#### Output TCP bottlenecks
When using the Gor listener the output-tcp feature may bottleneck if:
* the replay is unable to accept and process more requests than the listener is able generate. Prior to troubleshooting the output-tcp bottleneck, ensure that the replay target is not experiencing any bottlenecks.
* the replay target has inadequate bandwidth to handle all its incoming requests. If a replay target's incoming bandwidth is maxed out the output-tcp-stats may report that the output-tcp queue is filling up. See if there is a way to upgrade the replay's bandwidth.
#### Tuning
To achieve the top most performance you should tune the source server system limits:
net.ipv4.tcp_max_tw_buckets = 65536
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 0
net.ipv4.tcp_max_syn_backlog = 131072
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_synack_retries = 3
net.ipv4.tcp_retries1 = 3
net.ipv4.tcp_retries2 = 8
net.ipv4.tcp_rmem = 16384 174760 349520
net.ipv4.tcp_wmem = 16384 131072 262144
net.ipv4.tcp_mem = 262144 524288 1048576
net.ipv4.tcp_max_orphans = 65536
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_low_latency = 1
net.ipv4.tcp_syncookies = 0
***
### Gor is crashing with following stacktrace
```
fatal error: unexpected signal during runtime execution
[signal 0xb code=0x1 addr=0x63 pc=0x7ffcdfdf8b2c]
runtime stack:
runtime.throw(0xad8380, 0x2a)
/usr/local/go/src/runtime/panic.go:547 +0x90
runtime.sigpanic()
/usr/local/go/src/runtime/sigpanic_unix.go:12 +0x5a
goroutine 103 [syscall, locked to thread]:
runtime.cgocall(0x7b35a0, 0xc82121f1e8, 0x0)
/usr/local/go/src/runtime/cgocall.go:123 +0x11b fp=0xc82121f188 sp=0xc82121f158
net._C2func_getaddrinfo(0x7ffcec0008c0, 0x0, 0xc821b221e0, 0xc8217b2b18, 0x0, 0x0, 0x0)
??:0 +0x55 fp=0xc82121f1e8 sp=0xc82121f188
net.cgoLookupIPCNAME(0x7fffb17208ab, 0x12, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xb17200)
```
There is a chance that you hit Go bug. The crash comes from the CGO version of DNS resolver.
By default Go based version used, but ins some cases [it switches to CGO based](https://golang.org/pkg/net/#hdr-Name_Resolution). It is possible to force Go based DNS resolver using GODEBUG environment variable:
`sudo GODEBUG="netdns=go" ./gor --input-raw :80 --output-http staging.env`
Also, see [[FAQ]]
+1
View File
@@ -0,0 +1 @@
[Website](https://goreplay.org) | [PRO version](https://goreplay.org/pro.html) | [[Getting started]] | [[FAQ]] | [Join newsletter](https://www.getdrip.com/forms/89690474/submissions/new)
+1
View File
@@ -0,0 +1 @@
theme: jekyll-theme-cayman
+19
View File
@@ -0,0 +1,19 @@
Collaboration is difficult with commercial closed source but I do want to keep as much of the OSS ethos as possible available to customers who want to fix it themselves.
## Legal
In order to unambiguously own and sell Gor commercial products, I must have the copyright associated with the entire codebase. Any code you create which is merged must be owned by me. That's not me trying to be a jerk, that's just the way it works.
## Application
If you wish access to the product repository so you can send a PR, just open a new Gor issue and include the following info:
1. the email address that bought the license, a max of one collaborator per license
1. the following statement "I assign all rights, including copyright, to any future Gor work by myself to Leonid Bugaev"
You should be granted access to the private repo soon after.
## Notes
1. You should **never** work on the master branch. Only I may merge changes.
1. I may revoke access for any reason at any time. Access is not guaranteed with purchase.
+58
View File
@@ -0,0 +1,58 @@
### What are GoReplay PRO and GoReplay Enterprise?
[GoReplay PRO](https://goreplay.org/pro.html) and GoReplay Enterprise are extensions to GoReplay which add more functionality and provide additional support options for customers.
### Is there a trial version?
There's no free trial but we do offer a 14 day period with full refund if it does not work for you.
### What is the license?
See [COMM-LICENSE](https://github.com/buger/gor/blob/master/COMM-LICENSE) in the root of the GoReplay repo.
### How does PRO licensing work?
Every organization running GoReplay Pro on its own servers must have a license. There's no limit to the amount of servers or environments used by that organization.
### How does Enterprise licensing work?
Every organization running Gor Enterprise on its own servers must have a license. There's **no limit** to the amount of servers or environments used by that organization.
### What happens if my subscription lapses?
You must have an active subscription to run GoReplay Pro or Enterprise. After a one week grace period, you'll lose access to binaries and priority support. You won't get any more updates or bug fixes.
### How do I buy GoReplay Enterprise?
Send email to [support&#64;gortool.com](mailto:support&#64;gortool.com) with your info. A PDF quote will be emailed to you with the price. Reply to that email with your purchase order or just "Sounds good" and we will send an invoice which can be paid with a credit card, ACH bank transfer or a paper check.
### Can I upgrade from GoReplay Pro?
Yes! Current subscribers can upgrade by [requesting a quote](mailto:support&#64;gortool.com). **Please note that you are an existing Pro subscriber.** We will add a one-time discount on your first invoice to reflect any remaining Pro subscription credit. If you purchased GoReplay Pro 6 months ago for $950, you'll get a $475 discount.
### Can I distribute GoReplay PRO or Enterprise to my customers?
This is a common requirement for "on-site installs" or "appliances" sold to large corporations.
The standard license is appropriate for SaaS usage as it does not allow distribution. GoReplay PRO and Enterprise have an Appliance license option which **does** allow you to distribute them. The Appliance license is $9,500/yr for Pro and $19,500/yr for Enterprise. It allows you to distribute the Pro or Enterprise binaries as part of your application and each of your customers to run GoReplay Pro or Enterprise. Email [support&#64;gortool.com](mailto:support&#64;gortool.com) to purchase.
### Can you transfer a license?
Licenses are **not** transferable to another company. We will transfer the license from a user-specific email to a group email address (e.g. john_smith@example.com -> tech@example.com) but only for **the same domain**. It is strongly recommended that you buy the license using a group email address so the license is not attached to any one employee's email address.
### What does the license require me to do?
Your purchase gets you a unique access URL for downloading the Pro and/or Enterprise binaries. The license agreement requires you to keep this access URL private. If we find your access URL is ever publicized:
1. We'll send you a warning email with details. You need to remove the content and send a new email address so we can generate a new access URL for you. The old access URL will stop working immediately so you'll need to update your apps.
2. If your access URL is publicized a second time, we reserve the right to permanently remove access.
### Can I get a refund?
Yes, up to two weeks after purchase. Let us know the reason and maybe we can help but either way it's not a problem. Email [support&#64;gortool.com](mailto:support&#64;gortool.com).
### How do I update my credit card info?
If you purchased GoReplay Enterprise, there's nothing to do. Each annual invoice is paid separately.
If you purchased GoReplay PRO, log into [Gumroad](https://gumroad.com) with your email address, click the Billing tab and enter your new card. I can't provide support for the Gumroad website and don't have the ability to edit customer info - if you can't log in or change your credit card, you can always let your current subscription expire and purchase a new subscription.
+11
View File
@@ -0,0 +1,11 @@
Gor offers only community support. Gor Pro and Enterprise offer priority support via email.
## Priority Support
Covers 1 incident per quarter, with a max response time of 2 working days. Scope is limited to Gor and Gor Pro and Enterprise features and APIs, not the application or infrastructure. For support, email **support** AT **gortool.com**. Please email using the same domain as the original license email or explain your connection to the licensed company.
More aggressive support contracts (phone, quicker response time) are available separately, email with your needs.
## Onboarding
Enterprise customers may request a one hour video chat session with @buger to discuss their application(s), requirements and how best to leverage the various Gor features. Contact support to set up your session.
+39
View File
@@ -0,0 +1,39 @@
.wy-breadcrumbs li {
display: inline-block;
}
.wy-breadcrumbs li.wy-breadcrumbs-aside {
float: right;
}
.wy-breadcrumbs li a {
display: inline-block;
padding: 5px;
}
.wy-breadcrumbs li a:first-child {
padding-left: 0;
}
.wy-breadcrumbs-extra {
margin-bottom: 0;
color: #b3b3b3;
font-size: 80%;
display: inline-block;
}
@media screen and (max-width: 480px) {
.wy-breadcrumbs-extra {
display: none;
}
.wy-breadcrumbs li.wy-breadcrumbs-aside {
display: none;
}
}
@media print {
.wy-breadcrumbs li.wy-breadcrumbs-aside {
display: none;
}
}
+355
View File
@@ -0,0 +1,355 @@
.codeblock-example {
border: 1px solid #e1e4e5;
border-bottom: none;
padding: 24px;
padding-top: 48px;
font-weight: 500;
background: #fff;
position: relative;
}
.codeblock-example:after {
content: "Example";
position: absolute;
top: 0;
left: 0;
background: #9B59B6;
color: #fff;
padding: 6px 12px;
}
.codeblock-example.prettyprint-example-only {
border: 1px solid #e1e4e5;
margin-bottom: 24px;
}
.codeblock,
pre.literal-block,
.rst-content .literal-block,
.rst-content pre.literal-block,
div[class^='highlight'] {
border: 1px solid #e1e4e5;
padding: 0;
overflow-x: auto;
background: #fff;
margin: 1px 0 24px;
}
.codeblock div[class^='highlight'],
pre.literal-block div[class^='highlight'],
.rst-content .literal-block div[class^='highlight'],
div[class^='highlight'] div[class^='highlight'] {
border: none;
background: none;
margin: 0;
}
div[class^='highlight'] td.code {
width: 100%;
}
.linenodiv pre {
border-right: solid 1px #e6e9ea;
margin: 0;
padding: 12px;
font-family: "Source Code Pro","Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;
font-size: 12px;
line-height: 1.5;
color: #d9d9d9;
}
div[class^='highlight'] pre {
white-space: pre;
margin: 0;
padding: 12px;
font-family: "Source Code Pro","Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;
font-size: 12px;
line-height: 1.5;
display: block;
overflow: auto;
color: #404040;
}
@media print {
.codeblock,
pre.literal-block,
.rst-content .literal-block,
.rst-content pre.literal-block,
div[class^='highlight'],
div[class^='highlight'] pre {
white-space: pre-wrap;
}
}
.hll {
background-color: #ffc;
margin: 0 -12px;
padding: 0 12px;
display: block;
}
.c {
color: #998;
font-style: italic;
}
.err {
color: #a61717;
background-color: #e3d2d2;
}
.k {
font-weight: 700;
}
.o {
font-weight: 700;
}
.cm {
color: #998;
font-style: italic;
}
.cp {
color: #999;
font-weight: 700;
}
.c1 {
color: #998;
font-style: italic;
}
.cs {
color: #999;
font-weight: 700;
font-style: italic;
}
.gd {
color: #000;
background-color: #fdd;
}
.gd .x {
color: #000;
background-color: #faa;
}
.ge {
font-style: italic;
}
.gr {
color: #a00
}
.gh {
color: #999;
}
.gi {
color: #000;
background-color: #dfd;
}
.gi .x {
color: #000;
background-color: #afa;
}
.go {
color: #888;
}
.gp {
color: #555;
}
.gs {
font-weight: 700;
}
.gu {
color: purple;
font-weight: 700;
}
.gt {
color: #a00;
}
.kc {
font-weight: 700;
}
.kd {
font-weight: 700;
}
.kn {
font-weight: 700;
}
.kp {
font-weight: 700;
}
.kr {
font-weight: 700;
}
.kt {
color: #458;
font-weight: 700;
}
.m {
color: #099;
}
.s {
color: #d14;
}
.n {
color: #333;
}
.na {
color: teal;
}
.nb {
color: #0086b3;
}
.nc {
color: #458;
font-weight: 700;
}
.no {
color: teal;
}
.ni {
color: purple;
}
.ne {
color: #900;
font-weight: 700;
}
.nf {
color: #900;
font-weight: 700;
}
.nn {
color: #555;
}
.nt {
color: navy;
}
.nv {
color: teal;
}
.ow {
font-weight: 700;
}
.w {
color: #bbb;
}
.mf {
color: #099;
}
.mh {
color: #099;
}
.mi {
color: #099;
}
.mo {
color: #099;
}
.sb {
color: #d14;
}
.sc {
color: #d14;
}
.sd {
color: #d14;
}
.s2 {
color: #d14
}
.se {
color: #d14;
}
.sh {
color: #d14;
}
.si {
color: #d14;
}
.sx {
color: #d14;
}
.sr {
color: #009926;
}
.s1 {
color: #d14;
}
.ss {
color: #990073;
}
.bp {
color: #999;
}
.vc {
color: teal;
}
.vg {
color: teal;
}
.vi {
color: teal;
}
.il {
color: #099;
}
.gc {
color: #999;
background-color: #EAF2F5;
}
+3442
View File
File diff suppressed because it is too large Load Diff
+171
View File
@@ -0,0 +1,171 @@
code {
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace !important;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
background-color: #f7f7f7 !important;
color: #333 !important;
font-size: 14px !important;
border: none !important;
padding: 5px !important;
}
pre > code {
line-height: 20px;
padding: 16px !important;
}
blockquote {
color: #777 !important;
border-left: 4px solid rgb(221, 221, 221);
padding-left: 16px;
padding-right: 16px;
margin-left: 0px !important;
}
/* Visited links purple is not a good idea */
a:visited {
color: #008BF3;
}
a {
color: #008BF3;
}
h3, h4, h5, h6 {
color: #333 !important;
}
.rst-versions {
display: none !important;
}
/* The next and previous button we don't need */
.rst-footer-buttons {
display: none;
}
/* Foldable parts */
details > * {
margin-left: 20px;
}
details > summary {
margin-left: 0px; /* To overwrite the margin from above */
font-size: 120%;
cursor: pointer
}
/* Fix the design not having the correct spacing */
.wy-menu-vertical .subnav li.current > a {
padding: 0.4045em 2.427em;
}
.toctree-l3 {
padding-left: 1.0em;
}
footer .fastlane {
margin: 20px 0;
}
footer .fastlane iframe {
vertical-align: middle;
}
/* Custom Syntax highlighting to look more like GitHub.com */
.hljs-symbol {
color: #0086b3;
}
.hljs-keyword {
font-weight: normal;
color: #a71d5d;
}
.hljs-string {
color: #183691;
}
/* Header Anchors */
/* From https://github.com/facelessuser/pymdown-extensions/blob/bf18d0635e9d91b0f98eacdcaa10f26e0ace0f20/doc_theme/css/theme_custom.css#L322-L395 */
.rst-content .headeranchor-link {
position: absolute;
top: 0;
bottom: 0;
left: 0;
display: block;
padding-right: 6px;
padding-left: 30px;
margin-left: -30px;
}
.rst-content .headeranchor-link:focus {
outline: none;
}
.rst-content h1,
.rst-content h2,
.rst-content h3,
.rst-content h4,
.rst-content h5,
.rst-content h6 {
position: relative;
}
.rst-content h1 .headeranchor,
.rst-content h2 .headeranchor,
.rst-content h3 .headeranchor,
.rst-content h4 .headeranchor,
.rst-content h5 .headeranchor,
.rst-content h6 .headeranchor {
display: none;
color: #000;
vertical-align: middle;
}
.rst-content h1:hover .headeranchor-link,
.rst-content h2:hover .headeranchor-link,
.rst-content h3:hover .headeranchor-link,
.rst-content h4:hover .headeranchor-link,
.rst-content h5:hover .headeranchor-link,
.rst-content h6:hover .headeranchor-link {
height: 1em;
padding-left: 8px;
margin-left: -30px;
text-decoration: none;
}
.rst-content h1:hover .headeranchor-link .headeranchor,
.rst-content h2:hover .headeranchor-link .headeranchor,
.rst-content h3:hover .headeranchor-link .headeranchor,
.rst-content h4:hover .headeranchor-link .headeranchor,
.rst-content h5:hover .headeranchor-link .headeranchor,
.rst-content h6:hover .headeranchor-link .headeranchor {
display: inline-block;
}
.rst-content .headeranchor {
font: normal normal 16px FontAwesome;
line-height: 1;
display: inline-block;
text-decoration: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.rst-content .headeranchor:before {
content: '\f0c1';
}
/* index.md badges */
@media screen and (max-width: 768px) {
.badge img {
width: auto;
}
}
+435
View File
@@ -0,0 +1,435 @@
.wy-affix {
position: fixed;
top: 1.618em;
}
.wy-menu a:hover {
text-decoration: none;
}
.wy-menu-vertical header,
.wy-menu-vertical p.caption {
height: 32px;
display: inline-block;
line-height: 32px;
padding: 0 1.618em;
margin-bottom: 0;
margin-top: 14px;
display: block;
font-weight: 700;
text-transform: uppercase;
font-size: 85%;
color: #ccc;
white-space: nowrap;
}
.wy-menu-vertical span {
color: #666;
}
.wy-menu-vertical ul {
margin-bottom: 0;
}
.wy-menu-vertical li.divide-top {
border-top: solid 1px #404040;
}
.wy-menu-vertical li.divide-bottom {
border-bottom: solid 1px #404040;
}
.wy-menu-vertical li.current {
background-color: #e5e5e5;
}
.wy-menu-vertical li.current a {
color: rgba(0, 93, 255, 0.7);
border-right: none;
}
.wy-menu-vertical li.current a:hover {
color: rgba(0, 93, 255, 0.9);
}
.wy-menu-vertical li code,
.wy-menu-vertical li .rst-content tt,
.rst-content .wy-menu-vertical li tt {
border: none;
background: inherit;
color: inherit;
padding-left: 0;
padding-right: 0
}
.wy-menu-vertical li span.toctree-expand {
display: block;
float: left;
margin-left: -1.2em;
font-size: .8em;
line-height: 1.6em;
color: #999;
}
.wy-menu-vertical li.on a,
.wy-menu-vertical li.current>a {
color: rgba(0, 93, 255, 0.9);
font-weight: 700;
position: relative;
background: #fafafa;
border: none;
}
/*.wy-menu-vertical li.on a:hover span.toctree-expand,
.wy-menu-vertical li.current>a:hover span.toctree-expand {
color: gray;
}*/
.wy-menu-vertical li.on a span.toctree-expand,
.wy-menu-vertical li.current>a span.toctree-expand {
display: block;
font-size: .8em;
line-height: 1.6em;
color: #333;
}
.wy-menu-vertical li.toctree-l1.current li.toctree-l2>ul,
.wy-menu-vertical li.toctree-l2.current li.toctree-l3>ul {
display: none;
}
.wy-menu-vertical li.toctree-l1.current li.toctree-l2.current>ul,
.wy-menu-vertical li.toctree-l2.current li.toctree-l3.current>ul {
display: block;
}
.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a {
display: block;
padding: .4045em 4.045em;
}
.wy-menu-vertical li.toctree-l2 a:hover span.toctree-expand {
color: #999;
}
.wy-menu-vertical li.toctree-l2 span.toctree-expand {
color: #999;
}
.wy-menu-vertical li.toctree-l3 {
background-color: #eee;
font-size: .9em;
}
.wy-menu-vertical li.toctree-l3.current>a {
padding: .4045em 4.045em;
}
.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a {
display: block;
padding: .4045em 5.663em;
border-top: none;
border-bottom: none;
}
.wy-menu-vertical li.toctree-l3 a:hover span.toctree-expand {
color: rgba(0, 93, 255, 0.9);
}
.wy-menu-vertical li.toctree-l3 span.toctree-expand {
color: #999;
}
.wy-menu-vertical li.toctree-l4 {
font-size: .9em;
}
.wy-menu-vertical li.current ul {
display: block;
}
.wy-menu-vertical .local-toc li ul {
display: block;
}
.wy-menu-vertical li ul li a {
margin-bottom: 0;
color: rgba(0, 93, 255, 0.7);
font-weight: 400;
}
.wy-menu-vertical a {
display: inline-block;
line-height: 18px;
padding: .4045em 1.618em;
display: block;
position: relative;
font-size: 90%;
color: rgba(0, 93, 255, 0.7);
}
.wy-menu-vertical li.on a:hover,
.wy-menu-vertical li.current>a:hover {
background-color: #fafafa;
}
.wy-menu-vertical a:hover {
color: rgba(0, 93, 255, 0.9);
cursor: pointer;
background-color: #fafafa;
}
.wy-menu-vertical a:hover span.toctree-expand {
color: rgba(0, 93, 255, 0.5);
}
.wy-menu-vertical a:active span.toctree-expand {
color: rgba(0, 93, 255, 0.7);
}
/* Search */
.wy-side-nav-search {
z-index: 200;
background-color: #fafafa;
border-bottom: #333;
text-align: center;
padding: .809em;
display: block;
color: #333;
margin-bottom: .809em
}
.wy-side-nav-search input[type=text] {
width: 100%;
color: #333;
border-radius: 3px;
outline: 0;
padding: 10px;
background-color: #fff;
border: solid 1px #6d6d6d;
box-shadow: none
}
.wy-side-nav-search img {
display: block;
margin: auto auto .809em;
height: 45px;
width: 45px;
background-color: #2980B9;
padding: 5px;
border-radius: 100%
}
.wy-side-nav-search>a,
.wy-side-nav-search .wy-dropdown>a {
color: #333;
font-size: 100%;
font-weight: 700;
display: inline-block;
padding: 4px 6px;
margin-bottom: .809em
}
.wy-side-nav-search>a:hover,
.wy-side-nav-search .wy-dropdown>a:hover {
background: rgba(255,255,255,0.1)
}
.wy-side-nav-search>a img.logo,
.wy-side-nav-search .wy-dropdown>a img.logo {
display: block;
margin: 0 auto;
height: auto;
width: auto;
border-radius: 0;
max-width: 100%;
background: transparent
}
.wy-side-nav-search>a.icon img.logo,
.wy-side-nav-search .wy-dropdown>a.icon img.logo {
margin-top: .85em
}
.wy-nav .wy-menu-vertical header {
color: #2980B9
}
.wy-nav .wy-menu-vertical a {
color: #b3b3b3
}
.wy-nav .wy-menu-vertical a:hover {
background-color: #2980B9;
color: #fff
}
[data-menu-wrap] {
-webkit-transition: all .2s ease-in;
-moz-transition: all .2s ease-in;
transition: all .2s ease-in;
position: absolute;
opacity: 1;
width: 100%;
opacity: 0
}
[data-menu-wrap].move-center {
left: 0;
right: auto;
opacity: 1
}
[data-menu-wrap].move-left {
right: auto;
left: -100%;
opacity: 0
}
[data-menu-wrap].move-right {
right: -100%;
left: auto;
opacity: 0
}
.wy-body-for-nav {
background: left repeat-y #fcfcfc;
background-image: url(data:image/png;
base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoxOERBMTRGRDBFMUUxMUUzODUwMkJCOThDMEVFNURFMCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoxOERBMTRGRTBFMUUxMUUzODUwMkJCOThDMEVFNURFMCI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjE4REExNEZCMEUxRTExRTM4NTAyQkI5OEMwRUU1REUwIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjE4REExNEZDMEUxRTExRTM4NTAyQkI5OEMwRUU1REUwIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+EwrlwAAAAA5JREFUeNpiMDU0BAgwAAE2AJgB9BnaAAAAAElFTkSuQmCC);
background-size: 300px 1px
}
.wy-grid-for-nav {
position: absolute;
width: 100%;
height: 100%
}
.wy-nav-side {
position: fixed;
top: 0;
bottom: 0;
left: 0;
padding-bottom: 2em;
width: 300px;
overflow-x: hidden;
overflow-y: scroll;
min-height: 100%;
background-color: #fafafa;
z-index: 200;
border-right: 2px solid #eee;
}
.wy-nav-top {
display: none;
background-color: #333;
color: #fff;
padding: .4045em .809em;
position: relative;
line-height: 50px;
text-align: center;
font-size: 100%;
*zoom: 1
}
.wy-nav-top:before,
.wy-nav-top:after {
display: table;
content: ""
}
.wy-nav-top:after {
clear: both
}
.wy-nav-top a {
color: #fff;
font-weight: 700
}
.wy-nav-top img {
margin-right: 12px;
height: 45px;
width: 45px;
background-color: #2980B9;
padding: 5px;
border-radius: 100%
}
.wy-nav-top i {
font-size: 30px;
line-height: 50px;
float: left;
cursor: pointer
}
.wy-nav-content-wrap {
margin-left: 300px;
background: #fcfcfc;
min-height: 100%
}
.wy-nav-content {
padding: 1.618em 3.236em;
height: 100%;
max-width: 1100px;
margin: auto
}
.wy-body-mask {
position: fixed;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.2);
display: none;
z-index: 499
}
.wy-body-mask.on {
display: block
}
@media screen and (max-width: 768px) {
.wy-body-for-nav {
background: #fcfcfc
}
.wy-nav-top {
display: block
}
.wy-nav-side {
left: -300px
}
.wy-nav-side.shift {
width: 85%;
left: 0
}
.wy-nav-content-wrap {
margin-left: 0
}
.wy-nav-content-wrap .wy-nav-content {
padding: 1.618em
}
.wy-nav-content-wrap.shift {
position: fixed;
min-width: 100%;
left: 85%;
top: 0;
height: 100%;
overflow: hidden
}
}
@media screen and (min-width: 1400px) {
.wy-nav-content {
margin: 0;
background: #fcfcfc
}
}
+17
View File
@@ -0,0 +1,17 @@
### Overview
Gor architecture tries to follow UNIX philosophy: everything made of pipes, various inputs multiplexing data to outputs.
You can [rate limit](/rate-limiting.md), [filter](request-filtering.md), [rewrite](request-rewriting.md) requests or even use your own [middleware](middleware.md) to implement custom logic. Also, it is possible to replay requests at the higher rate for [load testing](saving-and-replaying-from-file.md).
### Available inputs
* `--input-raw` - used to capture HTTP traffic, you should specify IP address or interface and application port. More about [[Capturing and replaying traffic]].
* `--input-file` - accepts file which previously was recorded using ` --output-file`. More about [[Saving and Replaying from file]]
* `--input-tcp` - used by Gor aggregation instance if you decided forward traffic from multiple forwarder Gor instances to it. Read about using [[Aggregator-forwarder setup]].
### Available outputs
* `--output-http` - replay HTTP traffic to given endpoint, accepts base url. Read [more about it](Replaying HTTP traffic)
* `--output-file` - records incoming traffic to the file. More about [[Saving and Replaying from file]]
* `--output-tcp` - forward incoming data to another Gor instance, used in conjunction with `--input-tcp`. Read more about [[Aggregator-forwarder setup]].
* `--output-stdout` - used for debugging, outputs all data to stdout.
+44
View File
@@ -0,0 +1,44 @@
### Dependencies
To start working with Gor, you need to have a web server running on your machine, and a terminal to run commands. If you are just poking around, you can quickly start the server by calling `gor file-server :8000`, this will start a simple file server of the current directory on port `8000`.
### Installing Gor
Download the latest Gor binary from https://github.com/buger/gor/releases (we provide precompiled binaries for Windows, Linux x64 and Mac OS), or you can compile by yourself [[Compilation]].
Once the archive is downloaded and uncompressed, you can run Gor from the current directory, or you may want to copy binary to your PATH (for Linux and Mac OS it can be `/usr/local/bin`).
### Capturing web traffic
Now run this command in terminal: `sudo ./gor --input-raw :8000 --output-stdout`
This command says to listen for all network activity happening on port 8000 and log it to stdout.
If you are familiar with `tcpdump`, we are going to implement similar functionality.
> You may notice that it uses `sudo` and asks for the password: to analyze network, Gor needs permissions which are available only to super users.
> However, it is possible to configure Gor [being run for non-root users](Running-as-non-root-user).
Make a few requests by opening `http://localhost:8000` in your browser, or just by calling curl in terminal `curl http://localhost:8000`. You should see that `gor` outputs all the HTTP requests and responses right to the terminal window where it is running.
**Gor is not a proxy:** you do not need to put 3-rd party tool to your critical path. Instead Gor just silently analyzes the traffic of your application and does not affect it anyhow.
### Replaying
Now it's time to replay your original traffic to another environment. Let's start the same file web server but on a different port: `gor file-server :8001`.
Instead of `--output-stdout` we will use `--output-http` and provide URL of second server: `sudo ./gor --input-raw :8000 --output-http="http://localhost:8001"`
Make few requests to first server. You should see them replicated to the second one, voila!
### Saving requests to file and replaying them later
Sometimes it's not possible to replay requests in real time; Gor allows you to save requests to the file and replay them later.
First use `--output-file` to save them: `sudo ./gor --input-raw :8000 --output-file=requests.gor`. This will create new file and continuously write all captured requests to it.
Let's re-run Gor, but now to replay requests from file: `./gor --input-file requests.gor --output-http="http://localhost:8001"`. You should see all the recorded requests coming to the second server, and they will be replayed in the same order and with exactly same timing as they were recorded.
Next: [[The Basics]]
### Watch an overview:
![YOUTUBE](https://www.youtube.com/watch?v=CxuKZcMKaW4)
+29
View File
@@ -0,0 +1,29 @@
Gor is an open-source tool for capturing and replaying live HTTP traffic into a test environment in order to continuously test your system with real data. It can be used to increase confidence in code deployments, configuration changes and infrastructure changes.
Read for more info:
* [[Getting Started]]
* [[The Basics]]
* [[Capturing and replaying traffic]]
* [[Replaying HTTP traffic]]
* [[[PRO] Replaying Binary protocols]]
* [[[PRO] Recording and replaying keep alive TCP sessions]]
* [[Saving and Replaying from file]]
* [Performance testing](https://github.com/buger/gor/wiki/Saving-and-Replaying-from-file#performance-testing)
* [[Rate limiting]]
* [[Request filtering]]
* [[Request rewriting]]
* [[Middleware]]
* [[Distributed configuration]]
* [[Exporting to ElasticSearch]]
* [[FAQ]]
* [[Troubleshooting]]
## Commercial Aspects
* [[Commercial Support]]
* [[Commercial FAQ]]
* [[Commercial collaboration]]
Next: [Getting Started](Getting-Started)
+7
View File
@@ -0,0 +1,7 @@
$(document).ready(function () {
$('img[alt="YOUTUBE"]').each(function () {
var id = $(this).attr('src').split('/')[$(this).attr('src').split('/').length - 1].split("=")[1];
var video = '<iframe style="width: 100%;height: 450px;" src="https://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe>';
$(this).replaceWith(video);
});
});
File diff suppressed because one or more lines are too long
@@ -0,0 +1,11 @@
> **This feature available only in PRO version. See https://goreplay.org/pro.html for details.**
By default, GoReplay does not guarantee that when you record keep-alive TCP session, it will be replayed in the same TCP connection as well. This is ok for most of the cases, but it does not give an accurate number of TCP sessions while replaying, also may cause issues if your application state depends on TCP session (do not mess with HTTP session).
[GoReplay PRO](https://goreplay.org/pro.html) extension adds support for accurate recording and replaying of keep-alive TCP sessions. Separate connection to your server is created per original session and it makes benchmarks and tests incredibly accurate. To enable session recognition you just need to pass `--recognize-tcp-sessions` option.
```
gor --input-raw :80 --recognize-tcp-sessions --output-http http://test.target
```
Note that enabling this option also change algorithm of distributing traffic when using `--split-output`, see [Distributed configuration].
+14
View File
@@ -0,0 +1,14 @@
> **This feature available only in PRO version. See https://goreplay.org/pro.html for details.**
Gor includes basic support for working with binary formats like `thrift` or `protocol-buffers`. To start set `--input-raw-protocol` to 'binary' (by default 'http'). For replaying, you should use `--output-binary`, example:
```
gor --input-raw :80 --input-raw-protocol binary --output-binary staging:8081
```
While working with `--input-raw` you may notice a 2-second delay before messages are emitted to the outputs. This behaviour is expected and happening because for general binary protocol it is impossible to know when TCP message ends, so Gor has to set inactivity timeout. Each protocol has own rules (for example write message length as first bytes), and require individual handling to know message length. We consider improving detailed protocol support for `thrift`, `protocol-buffer` and etc.
Note that you can use all load testing features for binary protocols. For example, the following command will loop and replay recorded payload on 10x speed for 30 seconds:
```
gor --input-file './binary*.gor|1000%' --output-binary staging:9091 --input-file-loop --exit-after 30s
```
+171
View File
@@ -0,0 +1,171 @@
package main
import (
"encoding/json"
"log"
"net/url"
"strings"
//"regexp"
"time"
"github.com/buger/goreplay/proto"
"github.com/mattbaird/elastigo/lib"
)
type ESUriErorr struct{}
func (e *ESUriErorr) Error() string {
return "Wrong ElasticSearch URL format. Expected to be: scheme://host/index_name"
}
type ESPlugin struct {
Active bool
ApiPort string
eConn *elastigo.Conn
Host string
Index string
indexor *elastigo.BulkIndexer
done chan bool
}
type ESRequestResponse struct {
ReqURL string `json:"Req_URL"`
ReqMethod string `json:"Req_Method"`
ReqUserAgent string `json:"Req_User-Agent"`
ReqAcceptLanguage string `json:"Req_Accept-Language,omitempty"`
ReqAccept string `json:"Req_Accept,omitempty"`
ReqAcceptEncoding string `json:"Req_Accept-Encoding,omitempty"`
ReqIfModifiedSince string `json:"Req_If-Modified-Since,omitempty"`
ReqConnection string `json:"Req_Connection,omitempty"`
ReqCookies string `json:"Req_Cookies,omitempty"`
RespStatus string `json:"Resp_Status"`
RespStatusCode string `json:"Resp_Status-Code"`
RespProto string `json:"Resp_Proto,omitempty"`
RespContentLength string `json:"Resp_Content-Length,omitempty"`
RespContentType string `json:"Resp_Content-Type,omitempty"`
RespTransferEncoding string `json:"Resp_Transfer-Encoding,omitempty"`
RespContentEncoding string `json:"Resp_Content-Encoding,omitempty"`
RespExpires string `json:"Resp_Expires,omitempty"`
RespCacheControl string `json:"Resp_Cache-Control,omitempty"`
RespVary string `json:"Resp_Vary,omitempty"`
RespSetCookie string `json:"Resp_Set-Cookie,omitempty"`
Rtt int64 `json:"RTT"`
Timestamp time.Time
}
// Parse ElasticSearch URI
//
// Proper format is: scheme://[userinfo@]host/index_name
// userinfo is: user[:password]
// net/url.Parse() does not fail if scheme is not provided but actualy does not
// handle URI properly.
// So we must 'validate' URI format to match requirements to use net/url.Parse()
func parseURI(URI string) (err error, index string) {
parsedUrl, parseErr := url.Parse(URI)
if parseErr != nil {
err = new(ESUriErorr)
}
// check URL validity by extracting host and undex values.
host := parsedUrl.Host
urlPathParts := strings.Split(parsedUrl.Path, "/")
index = urlPathParts[len(urlPathParts)-1]
// force index specification in uri : ie no implicit index
if host == "" || index == "" {
err = new(ESUriErorr)
}
return
}
func (p *ESPlugin) Init(URI string) {
var err error
err, p.Index = parseURI(URI)
if err != nil {
log.Fatal("Can't initialize ElasticSearch plugin.", err)
}
p.eConn = elastigo.NewConn()
p.eConn.SetFromUrl(URI)
p.indexor = p.eConn.NewBulkIndexerErrors(50, 60)
p.done = make(chan bool)
p.indexor.Start()
if Settings.verbose {
// Only start the ErrorHandler goroutine when in verbose mode
// no need to burn ressources otherwise
go p.ErrorHandler()
}
log.Println("Initialized Elasticsearch Plugin")
return
}
func (p *ESPlugin) IndexerShutdown() {
p.indexor.Stop()
return
}
func (p *ESPlugin) ErrorHandler() {
for {
errBuf := <-p.indexor.ErrorChannel
log.Println(errBuf.Err)
}
}
func (p *ESPlugin) RttDurationToMs(d time.Duration) int64 {
sec := d / time.Second
nsec := d % time.Second
fl := float64(sec) + float64(nsec)*1e-6
return int64(fl)
}
func (p *ESPlugin) ResponseAnalyze(req, resp []byte, start, stop time.Time) {
if len(resp) == 0 {
// nil http response - skipped elasticsearch export for this request
return
}
t := time.Now()
rtt := p.RttDurationToMs(stop.Sub(start))
req = payloadBody(req)
esResp := ESRequestResponse{
ReqURL: string(proto.Path(req)),
ReqMethod: string(proto.Method(req)),
ReqUserAgent: string(proto.Header(req, []byte("User-Agent"))),
ReqAcceptLanguage: string(proto.Header(req, []byte("Accept-Language"))),
ReqAccept: string(proto.Header(req, []byte("Accept"))),
ReqAcceptEncoding: string(proto.Header(req, []byte("Accept-Encoding"))),
ReqIfModifiedSince: string(proto.Header(req, []byte("If-Modified-Since"))),
ReqConnection: string(proto.Header(req, []byte("Connection"))),
ReqCookies: string(proto.Header(req, []byte("Cookie"))),
RespStatus: string(proto.Status(resp)),
RespStatusCode: string(proto.Status(resp)),
RespProto: string(proto.Method(resp)),
RespContentLength: string(proto.Header(resp, []byte("Content-Length"))),
RespContentType: string(proto.Header(resp, []byte("Content-Type"))),
RespTransferEncoding: string(proto.Header(resp, []byte("Transfer-Encoding"))),
RespContentEncoding: string(proto.Header(resp, []byte("Content-Encoding"))),
RespExpires: string(proto.Header(resp, []byte("Expires"))),
RespCacheControl: string(proto.Header(resp, []byte("Cache-Control"))),
RespVary: string(proto.Header(resp, []byte("Vary"))),
RespSetCookie: string(proto.Header(resp, []byte("Set-Cookie"))),
Rtt: rtt,
Timestamp: t,
}
j, err := json.Marshal(&esResp)
if err != nil {
log.Println(err)
} else {
p.indexor.Index(p.Index, "RequestResponse", "", "", "", &t, j)
}
return
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"testing"
)
const expectedIndex = "gor"
func assertExpectedGorIndex(index string, t *testing.T) {
if expectedIndex != index {
t.Fatalf("Expected index %s but got %s", expectedIndex, index)
}
}
func assertExpectedIndex(expectedIndex string, index string, t *testing.T) {
if expectedIndex != index {
t.Fatalf("Expected index %s but got %s", expectedIndex, index)
}
}
func assertExpectedError(returnedError error, t *testing.T) {
expectedError := new(ESUriErorr)
if expectedError != returnedError {
t.Errorf("Expected err %s but got %s", expectedError, returnedError)
}
}
func assertNoError(returnedError error, t *testing.T) {
if nil != returnedError {
t.Errorf("Expected no err but got %s", returnedError)
}
}
// Argument host:port/index_name
// i.e : localhost:9200/gor
// Fail because scheme is mandatory
func TestElasticConnectionBuildFailWithoutScheme(t *testing.T) {
uri := "localhost:9200/" + expectedIndex
err, _ := parseURI(uri)
assertExpectedError(err, t)
}
// Argument scheme://host:port
// i.e : http://localhost:9200
// Fail : explicit index is required
func TestElasticConnectionBuildFailWithoutIndex(t *testing.T) {
uri := "http://localhost:9200"
err, index := parseURI(uri)
assertExpectedIndex("", index, t)
assertExpectedError(err, t)
}
// Argument scheme://host/index_name
// i.e : http://localhost/gor
func TestElasticConnectionBuildFailWithoutPort(t *testing.T) {
uri := "http://localhost/" + expectedIndex
err, index := parseURI(uri)
assertNoError(err, t)
assertExpectedGorIndex(index, t)
}
// Argument scheme://host:port/index_name
// i.e : http://localhost:9200/gor
func TestElasticLocalConnectionBuild(t *testing.T) {
uri := "http://localhost:9200/" + expectedIndex
err, index := parseURI(uri)
assertNoError(err, t)
assertExpectedGorIndex(index, t)
}
// Argument scheme://host:port/index_name
// i.e : http://localhost.local:9200/gor or https://localhost.local:9200/gor
func TestElasticSimpleLocalWithSchemeConnectionBuild(t *testing.T) {
uri := "http://localhost.local:9200/" + expectedIndex
err, index := parseURI(uri)
assertNoError(err, t)
assertExpectedGorIndex(index, t)
}
// Argument scheme://host:port/index_name
// i.e : http://localhost.local:9200/gor or https://localhost.local:9200/gor
func TestElasticSimpleLocalWithHTTPSConnectionBuild(t *testing.T) {
uri := "https://localhost.local:9200/" + expectedIndex
err, index := parseURI(uri)
assertNoError(err, t)
assertExpectedGorIndex(index, t)
}
// Argument scheme://host:port/index_name
// i.e : localhost.local:9200/pathtoElastic/gor
func TestElasticLongPathConnectionBuild(t *testing.T) {
uri := "http://localhost.local:9200/pathtoElastic/" + expectedIndex
err, index := parseURI(uri)
assertNoError(err, t)
assertExpectedGorIndex(index, t)
}
// Argument scheme://host:userinfo@port/index_name
// i.e : http://user:password@localhost.local:9200/gor
func TestElasticBasicAuthConnectionBuild(t *testing.T) {
uri := "http://user:password@localhost.local:9200/" + expectedIndex
err, index := parseURI(uri)
assertNoError(err, t)
assertExpectedGorIndex(index, t)
}
// Argument scheme://host:port/path/index_name
// i.e : http://localhost.local:9200/path/gor or https://localhost.local:9200/path/gor
func TestElasticComplexPathConnectionBuild(t *testing.T) {
uri := "http://localhost.local:9200/path/" + expectedIndex
err, index := parseURI(uri)
assertNoError(err, t)
assertExpectedGorIndex(index, t)
}
+182
View File
@@ -0,0 +1,182 @@
package main
import (
"bytes"
"io"
"log"
"time"
)
// Start initialize loop for sending data from inputs to outputs
func Start(stop chan int) {
if Settings.middleware != "" {
middleware := NewMiddleware(Settings.middleware)
for _, in := range Plugins.Inputs {
middleware.ReadFrom(in)
}
// We are going only to read responses, so using same ReadFrom method
for _, out := range Plugins.Outputs {
if r, ok := out.(io.Reader); ok {
middleware.ReadFrom(r)
}
}
go func() {
if err := CopyMulty(middleware, Plugins.Outputs...); err != nil {
log.Println("Error during copy: ", err)
close(stop)
}
}()
} else {
for _, in := range Plugins.Inputs {
go func() {
if err := CopyMulty(in, Plugins.Outputs...); err != nil {
log.Println("Error during copy: ", err)
close(stop)
}
}()
}
for _, out := range Plugins.Outputs {
if r, ok := out.(io.Reader); ok {
go func() {
if err := CopyMulty(r, Plugins.Outputs...); err != nil {
log.Println("Error during copy: ", err)
close(stop)
}
}()
}
}
}
for {
select {
case <-stop:
finalize()
return
case <-time.After(100 * time.Millisecond):
}
}
}
// CopyMulty copies from 1 reader to multiple writers
func CopyMulty(src io.Reader, writers ...io.Writer) (err error) {
buf := make([]byte, Settings.copyBufferSize)
wIndex := 0
modifier := NewHTTPModifier(&Settings.modifierConfig)
filteredRequests := make(map[string]time.Time)
filteredRequestsLastCleanTime := time.Now()
i := 0
for {
nr, er := src.Read(buf)
if er == io.EOF {
return nil
}
if er != nil {
return err
}
_maxN := nr
if nr > 500 {
_maxN = 500
}
if nr > 0 && len(buf) > nr {
payload := buf[:nr]
meta := payloadMeta(payload)
if len(meta) < 3 {
if Settings.debug {
Debug("[EMITTER] Found malformed record", string(payload[0:_maxN]), nr, "from:", src)
}
continue
}
requestID := string(meta[1])
if nr >= 5*1024*1024 {
log.Println("INFO: Large packet... We received ", len(payload), " bytes from ", src)
}
if Settings.debug {
Debug("[EMITTER] input:", string(payload[0:_maxN]), nr, "from:", src)
}
if modifier != nil {
if isRequestPayload(payload) {
headSize := bytes.IndexByte(payload, '\n') + 1
body := payload[headSize:]
originalBodyLen := len(body)
body = modifier.Rewrite(body)
// If modifier tells to skip request
if len(body) == 0 {
filteredRequests[requestID] = time.Now()
continue
}
if originalBodyLen != len(body) {
payload = append(payload[:headSize], body...)
}
if Settings.debug {
Debug("[EMITTER] Rewritten input:", len(payload), "First 500 bytes:", string(payload[0:_maxN]))
}
} else {
if _, ok := filteredRequests[requestID]; ok {
delete(filteredRequests, requestID)
continue
}
}
}
if Settings.prettifyHTTP {
payload = prettifyHTTP(payload)
if len(payload) == 0 {
continue
}
}
if Settings.splitOutput {
// Simple round robin
if _, err := writers[wIndex].Write(payload); err != nil {
return err
}
wIndex++
if wIndex >= len(writers) {
wIndex = 0
}
} else {
for _, dst := range writers {
if _, err := dst.Write(payload); err != nil {
return err
}
}
}
} else if nr > 0 {
log.Println("WARN: Packet", nr, "bytes is too large to process. Consider increasing --copy-buffer-size")
}
// Run GC on each 1000 request
if i%1000 == 0 {
// Clean up filtered requests for which we didn't get a response to filter
now := time.Now()
if now.Sub(filteredRequestsLastCleanTime) > 60*time.Second {
for k, v := range filteredRequests {
if now.Sub(v) > 60*time.Second {
delete(filteredRequests, k)
}
}
filteredRequestsLastCleanTime = time.Now()
}
}
i++
}
return err
}
+147
View File
@@ -0,0 +1,147 @@
package main
import (
"io"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestEmitter(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
output := NewTestOutput(func(data []byte) {
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
for i := 0; i < 1000; i++ {
wg.Add(1)
input.EmitGET()
}
wg.Wait()
close(quit)
}
func TestEmitterFiltered(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
input.skipHeader = true
output := NewTestOutput(func(data []byte) {
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
methods := HTTPMethods{[]byte("GET")}
Settings.modifierConfig = HTTPModifierConfig{methods: methods}
go Start(quit)
wg.Add(2)
id := uuid()
reqh := payloadHeader(RequestPayload, id, time.Now().UnixNano(), -1)
reqb := append(reqh, []byte("GET / HTTP/1.1\r\nHost: www.w3.org\r\nUser-Agent: Go 1.1 package http\r\nAccept-Encoding: gzip\r\n\r\n")...)
resh := payloadHeader(ResponsePayload, id, time.Now().UnixNano()+1, 1)
respb := append(resh, []byte("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")...)
input.EmitBytes(reqb)
input.EmitBytes(respb)
id = uuid()
reqh = payloadHeader(RequestPayload, id, time.Now().UnixNano(), -1)
reqb = append(reqh, []byte("POST / HTTP/1.1\r\nHost: www.w3.org\r\nUser-Agent: Go 1.1 package http\r\nAccept-Encoding: gzip\r\n\r\n")...)
resh = payloadHeader(ResponsePayload, id, time.Now().UnixNano()+1, 1)
respb = append(resh, []byte("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")...)
input.EmitBytes(reqb)
input.EmitBytes(respb)
wg.Wait()
close(quit)
Settings.modifierConfig = HTTPModifierConfig{}
}
func TestEmitterRoundRobin(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
var counter1, counter2 int32
output1 := NewTestOutput(func(data []byte) {
atomic.AddInt32(&counter1, 1)
wg.Done()
})
output2 := NewTestOutput(func(data []byte) {
atomic.AddInt32(&counter2, 1)
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output1, output2}
Settings.splitOutput = true
go Start(quit)
for i := 0; i < 1000; i++ {
wg.Add(1)
input.EmitGET()
}
wg.Wait()
close(quit)
if counter1 == 0 || counter2 == 0 {
t.Errorf("Round robin should split traffic equally: %d vs %d", counter1, counter2)
}
Settings.splitOutput = false
}
func BenchmarkEmitter(b *testing.B) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
output := NewTestOutput(func(data []byte) {
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
b.ResetTimer()
for i := 0; i < b.N; i++ {
wg.Add(1)
input.EmitGET()
}
wg.Wait()
close(quit)
}
+53
View File
@@ -0,0 +1,53 @@
(ns echo.core
(:gen-class)
(:require [clojure.string :as cs]
[clojure.java.io :as io])
(:import org.apache.commons.codec.binary.Hex
java.io.BufferedReader
java.io.IOException
java.io.InputStreamReader))
(defn transform-http-msg
"Function that transforms/filters the incoming HTTP messages."
[headers body]
;; do actual transformations here
[headers body])
(defn decode-hex-string
"Decode an Hex-encoded string."
[s]
(String. (Hex/decodeHex (.toCharArray s))))
(defn encode-hex-string
"Encode a string to a hex-encoded string."
[^String s]
(String. (Hex/encodeHex (.getBytes s))))
(defn -main
[& args]
(let [br (BufferedReader. (InputStreamReader. System/in))]
(try
(loop [hex-line (.readLine br)]
(let [decoded-req (decode-hex-string hex-line)
;; empty line separates headers from body
http-request (partition-by empty? (cs/split-lines decoded-req))
headers (first http-request)
;; HTTP messages can contain no body:
body (when (= 3 (count http-request)) (last http-request))
[new-headers new-body] (transform-http-msg headers body)]
(println (encode-hex-string (str (cs/join "\n" headers)
(when body
(str "\n\n"
(cs/join "\n" body)))))))
(when-let [line (.readLine br)]
(recur line)))
(catch IOException e nil))))
+48
View File
@@ -0,0 +1,48 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
class Echo {
public static String decodeHexString(String s) throws DecoderException {
return new String(Hex.decodeHex(s.toCharArray()));
}
public static String encodeHexString(String s) {
return new String(Hex.encodeHex(s.getBytes()));
}
public static String transformHTTPMessage(String req) {
// do actual transformations here
return req;
}
public static void main(String[] args) throws DecoderException {
if(args != null){
for(String arg : args){
System.out.println(arg);
}
}
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
try {
while ((line = stdin.readLine()) != null) {
String decodedLine = decodeHexString(line);
String transformedLine = transformHTTPMessage(decodedLine);
String encodedLine = encodeHexString(transformedLine);
System.out.println(encodedLine);
}
} catch (IOException e) {
}
}
}
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env node
const readline = require("readline");
const StringDecoder = require("string_decoder").StringDecoder
const rl = readline.createInterface({
input: process.stdin
});
var ignoreIds = new Set();
var ignoreAddresses = "/api";
const decoder = new StringDecoder("utf8");
function convertHexString(hex) {
var bytes = [];
for (var i = 0; i < hex.length - 1; i += 2) {
bytes.push(parseInt(hex.substr(i, 2), 16));
}
return decoder.write(Buffer.from(bytes));
}
function log(output) {
console.error("===================");
console.error(output);
}
function shouldOutputLine(request) {
const components = request.split("\n");
const header = components[0].split(" ");
const type = parseInt(header[0]);
const tag = header[1];
if (type === 3) {
return true;
}
if (type === 1) {
// Check if it's oauth
const endpoint = components[1].split(" ")[1];
if (!endpoint.startsWith(ignoreAddresses)) {
ignoreIds.add(tag);
return false;
}
} else if (type === 2) {
if (ignoreIds.has(tag)) {
ignoreIds.delete(tag);
return false;
}
}
return true;
}
rl.on("line", (input) => {
const str = convertHexString(input);
console.log(input);
if (shouldOutputLine(str)) {
log(str);
}
});
+76
View File
@@ -0,0 +1,76 @@
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import fileinput
import binascii
# Used to find end of the Headers section
EMPTY_LINE = b'\r\n\r\n'
def log(msg):
"""
Logging to STDERR as STDOUT and STDIN used for data transfer
@type msg: str or byte string
@param msg: Message to log to STDERR
"""
try:
msg = str(msg) + '\n'
except:
pass
sys.stderr.write(msg)
sys.stderr.flush()
def find_end_of_headers(byte_data):
"""
Finds where the header portion ends and the content portion begins.
@type byte_data: str or byte string
@param byte_data: Hex decoded req or resp string
"""
return byte_data.index(EMPTY_LINE) + 4
def process_stdin():
"""
Process STDIN and output to STDOUT
"""
for raw_line in fileinput.input():
line = raw_line.rstrip()
# Decode base64 encoded line
decoded = bytes.fromhex(line)
# Split into metadata and payload, the payload is headers + body
(raw_metadata, payload) = decoded.split(b'\n', 1)
# Split into headers and payload
headers_pos = find_end_of_headers(payload)
raw_headers = payload[:headers_pos]
raw_content = payload[headers_pos:]
log('===================================')
request_type_id = int(raw_metadata.split(b' ')[0])
log('Request type: {}'.format({
1: 'Request',
2: 'Original Response',
3: 'Replayed Response'
}[request_type_id]))
log('===================================')
log('Original data:')
log(line)
log('Decoded request:')
log(decoded)
encoded = binascii.hexlify(raw_metadata + b'\n' + raw_headers + raw_content).decode('ascii')
log('Encoded data:')
log(encoded)
sys.stdout.write(encoded + '\n')
if __name__ == '__main__':
process_stdin()
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env ruby
# encoding: utf-8
while data = STDIN.gets # continuously read line from STDIN
next unless data
data = data.chomp # remove end of line symbol
decoded = [data].pack("H*") # decode base64 encoded request
# decoded value is raw HTTP payload, example:
#
# POST /post HTTP/1.1
# Content-Length: 7
# Host: www.w3.org
#
# a=1&b=2"
encoded = decoded.unpack("H*").first # encoding back to base64
# Emit request back
# You can skip this if want to filter out request
STDOUT.puts encoded
end
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env bash
#
# `xxd` utility included into vim-common package
# It allow hex decoding/encoding
#
# This example may broke if you request contains `null` string, you may consider using pipes instead.
# See: https://github.com/buger/gor/issues/309
#
function log {
# Logging to stderr, because stdout/stdin used for data transfer
>&2 echo "[DEBUG][ECHO] $1"
}
while read line; do
decoded=$(echo -e "$line" | xxd -r -p)
header=$(echo -e "$decoded" | head -n +1)
payload=$(echo -e "$decoded" | tail -n +2)
encoded=$(echo -e "$header\n$payload" | xxd -p | tr -d "\\n")
log ""
log "==================================="
case ${header:0:1} in
"1")
log "Request type: Request"
;;
"2")
log "Request type: Original Response"
;;
"3")
log "Request type: Replayed Response"
;;
*)
log "Unknown request type $header"
esac
echo "$encoded"
log "==================================="
log "Original data: $line"
log "Decoded request: $decoded"
log "Encoded data: $encoded"
done;
+120
View File
@@ -0,0 +1,120 @@
/*
This middleware made for auth system that randomly generate access tokens, which used later for accessing secure content. Since there is no pre-defined token value, naive approach without middleware (or if middleware use only request payloads) will fail, because replayed server have own tokens, not synced with origin. To fix this, our middleware should take in account responses of replayed and origin server, store `originalToken -> replayedToken` aliases and rewrite all requests using this token to use replayed alias. See `middleware_test.go#TestTokenMiddleware` test for examples of using this middleware.
How middleware works:
Original request +--------------+
+-------------+----------STDIN---------->+ |
| Gor input | | Middleware |
+-------------+----------STDIN---------->+ |
Original response +------+---+---+
| ^
+-------------+ Modified request v |
| Gor output +<---------STDOUT-----------------+ |
+-----+-------+ |
| |
| Replayed response |
+------------------STDIN----------------->----+
*/
package main
import (
"bufio"
"bytes"
"encoding/hex"
"fmt"
"os"
"github.com/buger/goreplay/proto"
)
// requestID -> originalToken
var originalTokens map[string][]byte
// originalToken -> replayedToken
var tokenAliases map[string][]byte
func main() {
originalTokens = make(map[string][]byte)
tokenAliases = make(map[string][]byte)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
encoded := scanner.Bytes()
buf := make([]byte, len(encoded)/2)
hex.Decode(buf, encoded)
process(buf)
}
}
func process(buf []byte) {
// First byte indicate payload type, possible values:
// 1 - Request
// 2 - Response
// 3 - ReplayedResponse
payloadType := buf[0]
headerSize := bytes.IndexByte(buf, '\n') + 1
header := buf[:headerSize-1]
// Header contains space separated values of: request type, request id, and request start time (or round-trip time for responses)
meta := bytes.Split(header, []byte(" "))
// For each request you should receive 3 payloads (request, response, replayed response) with same request id
reqID := string(meta[1])
payload := buf[headerSize:]
Debug("Received payload:", string(buf))
switch payloadType {
case '1': // Request
if bytes.Equal(proto.Path(payload), []byte("/token")) {
originalTokens[reqID] = []byte{}
Debug("Found token request:", reqID)
} else {
token, vs, _ := proto.PathParam(payload, []byte("token"))
if vs != -1 { // If there is GET token param
if alias, ok := tokenAliases[string(token)]; ok {
// Rewrite original token to alias
payload = proto.SetPathParam(payload, []byte("token"), alias)
// Copy modified payload to our buffer
buf = append(buf[:headerSize], payload...)
}
}
}
// Emitting data back
os.Stdout.Write(encode(buf))
case '2': // Original response
if _, ok := originalTokens[reqID]; ok {
// Token is inside response body
secureToken := proto.Body(payload)
originalTokens[reqID] = secureToken
Debug("Remember origial token:", string(secureToken))
}
case '3': // Replayed response
if originalToken, ok := originalTokens[reqID]; ok {
delete(originalTokens, reqID)
secureToken := proto.Body(payload)
tokenAliases[string(originalToken)] = secureToken
Debug("Create alias for new token token, was:", string(originalToken), "now:", string(secureToken))
}
}
}
func encode(buf []byte) []byte {
dst := make([]byte, len(buf)*2+1)
hex.Encode(dst, buf)
dst[len(dst)-1] = '\n'
return dst
}
func Debug(args ...interface{}) {
fmt.Fprint(os.Stderr, "[DEBUG][TOKEN-MOD] ")
fmt.Fprintln(os.Stderr, args...)
}
+120 -24
View File
@@ -1,46 +1,142 @@
// Gor is simple http traffic replication tool written in Go. Its main goal to replay traffic from production servers to staging and dev environments.
// Now you can test your code on real user sessions in an automated and repeatable fashion.
//
// Gor consists of 2 parts: listener and replay servers.
// Listener catch http traffic from given port in real-time and send it to replay server via UDP. Replay server forwards traffic to given address.
package main
import (
"flag"
"fmt"
"github.com/buger/gor/listener"
"github.com/buger/gor/replay"
"io"
"log"
"net/http"
"net/http/httputil"
_ "net/http/pprof"
"os"
"os/signal"
"runtime"
_ "runtime/debug"
"runtime/pprof"
"syscall"
"time"
)
const (
VERSION = "0.1.1"
var (
mode string
cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
memprofile = flag.String("memprofile", "", "write memory profile to this file")
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rb, _ := httputil.DumpRequest(r, false)
log.Println(string(rb))
next.ServeHTTP(w, r)
})
}
var closeCh chan int
func main() {
closeCh = make(chan int)
// // Don't exit on panic
// defer func() {
// if r := recover(); r != nil {
// fmt.Printf("PANIC: pkg: %v %s \n", r, debug.Stack())
// }
// }()
// If not set via env cariable
if len(os.Getenv("GOMAXPROCS")) == 0 {
runtime.GOMAXPROCS(runtime.NumCPU() * 2)
}
args := os.Args[1:]
if len(args) > 0 && args[0] == "file-server" {
if len(args) != 2 {
log.Fatal("You should specify port and IP (optional) for the file server. Example: `gor file-server :80`")
}
dir, _ := os.Getwd()
log.Println("Started example file server for current directory on address ", args[1])
log.Fatal(http.ListenAndServe(args[1], loggingMiddleware(http.FileServer(http.Dir(dir)))))
} else {
flag.Parse()
InitPlugins()
}
fmt.Println("Version:", VERSION)
mode := "unknown"
if len(os.Args) > 1 {
mode = os.Args[1]
if len(Plugins.Inputs) == 0 || len(Plugins.Outputs) == 0 {
log.Fatal("Required at least 1 input and 1 output")
}
if mode != "listen" && mode != "replay" {
fmt.Println("Usage: \n\tgor listen -h\n\tgor replay -h")
return
if *memprofile != "" {
profileMEM(*memprofile)
}
// Remove mode attr
os.Args = append(os.Args[:1], os.Args[2:]...)
flag.Parse()
switch mode {
case "listen":
listener.Run()
case "replay":
replay.Run()
if *cpuprofile != "" {
profileCPU(*cpuprofile)
}
if Settings.pprof != "" {
go func() {
log.Println(http.ListenAndServe(Settings.pprof, nil))
}()
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
finalize()
os.Exit(1)
}()
if Settings.exitAfter > 0 {
log.Println("Running gor for a duration of", Settings.exitAfter)
time.AfterFunc(Settings.exitAfter, func() {
log.Println("Stopping gor after", Settings.exitAfter)
close(closeCh)
})
}
Start(closeCh)
}
func finalize() {
for _, p := range Plugins.All {
if cp, ok := p.(io.Closer); ok {
cp.Close()
}
}
}
func profileCPU(cpuprofile string) {
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
time.AfterFunc(30*time.Second, func() {
pprof.StopCPUProfile()
f.Close()
log.Println("Stop profiling after 30 seconds")
})
}
}
func profileMEM(memprofile string) {
if memprofile != "" {
f, err := os.Create(memprofile)
if err != nil {
log.Fatal(err)
}
time.AfterFunc(30*time.Second, func() {
pprof.WriteHeapProfile(f)
f.Close()
})
}
}
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"log"
"runtime"
"strconv"
"time"
)
type GorStat struct {
statName string
rateMs int
latest int
mean int
max int
count int
}
func NewGorStat(statName string, rateMs int) (s *GorStat) {
s = new(GorStat)
s.statName = statName
s.rateMs = rateMs
s.latest = 0
s.mean = 0
s.max = 0
s.count = 0
if Settings.stats {
log.Println(s.statName + ":latest,mean,max,count,count/second,gcount")
go s.reportStats()
}
return
}
func (s *GorStat) Write(latest int) {
if Settings.stats {
if latest > s.max {
s.max = latest
}
if latest != 0 {
s.mean = ((s.mean * s.count) + latest) / (s.count + 1)
}
s.latest = latest
s.count = s.count + 1
}
}
func (s *GorStat) Reset() {
s.latest = 0
s.max = 0
s.mean = 0
s.count = 0
}
func (s *GorStat) String() string {
return s.statName + ":" + strconv.Itoa(s.latest) + "," + strconv.Itoa(s.mean) + "," + strconv.Itoa(s.max) + "," + strconv.Itoa(s.count) + "," + strconv.Itoa(s.count/(s.rateMs/1000.0)) + "," + strconv.Itoa(runtime.NumGoroutine())
}
func (s *GorStat) reportStats() {
for {
log.Println(s)
s.Reset()
time.Sleep(time.Duration(s.rateMs) * time.Millisecond)
}
}
+46
View File
@@ -0,0 +1,46 @@
require "language/go"
class Gor < Formula
desc "Real-time HTTP traffic replay tool written in Go"
homepage "https://gortool.com"
url "https://github.com/buger/gor/archive/v0.14.0.tar.gz"
sha256 "62260a6f5cabde571b91d5762fba9c47691643df0a58565cbe808854cd064dc8"
head "https://github.com/buger/gor.git"
bottle do
cellar :any_skip_relocation
sha256 "c382403de70a41b7445920a02051f5e82030704aaaae70cfcd4e8f401cc87f6a" => :el_capitan
sha256 "4b76b3785584897800e87967f1af9510208faefe46f57d7bd6f8b40a7133c19b" => :yosemite
sha256 "d186cb1566d33ab8f78215e69934f49dd96becb1c236905b4502d94399ae1974" => :mavericks
end
depends_on "go" => :build
go_resource "github.com/bitly/go-hostpool" do
url "https://github.com/bitly/go-hostpool.git",
:revision => "d0e59c22a56e8dadfed24f74f452cea5a52722d2"
end
go_resource "github.com/buger/elastigo" do
url "https://github.com/buger/elastigo.git",
:revision => "23fcfd9db0d8be2189a98fdab77a4c90fcc3a1e9"
end
go_resource "github.com/google/gopacket" do
url "https://github.com/google/gopacket.git",
:revision => "aa09ced736460d76535444c825932a0742975f7d"
end
def install
ENV["GOPATH"] = buildpath
mkdir_p buildpath/"src/github.com/buger/"
ln_sf buildpath, buildpath/"src/github.com/buger/gor"
Language::Go.stage_deps resources, buildpath/"src"
system "go", "build", "-o", "#{bin}/gor", "-ldflags", "-X main.VERSION \"#{version}\""
end
test do
assert_match version.to_s, shell_output("#{bin}/gor", 1)
end
end
+527
View File
@@ -0,0 +1,527 @@
package main
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"runtime/debug"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/buger/goreplay/proto"
)
var httpMu sync.Mutex
const (
readChunkSize = 64 * 1024
maxResponseSize = 1073741824
)
var chunkedSuffix = []byte("0\r\n\r\n")
var defaultPorts = map[string]string{
"http": "80",
"https": "443",
}
type HTTPClientConfig struct {
FollowRedirects int
Debug bool
OriginalHost bool
ConnectionTimeout time.Duration
Timeout time.Duration
ResponseBufferSize int
CompatibilityMode bool
}
type HTTPClient struct {
baseURL string
scheme string
host string
auth string
conn net.Conn
proxy *url.URL
proxyAuth string
respBuf []byte
config *HTTPClientConfig
goClient *http.Client
redirectsCount int
}
func NewHTTPClient(baseURL string, config *HTTPClientConfig) *HTTPClient {
if !strings.HasPrefix(baseURL, "http") {
baseURL = "http://" + baseURL
}
u, _ := url.Parse(baseURL)
if config.Timeout == 0 {
config.Timeout = time.Second
}
config.ConnectionTimeout = config.Timeout
if config.ResponseBufferSize == 0 {
config.ResponseBufferSize = 100 * 1024 // 100kb
}
client := new(HTTPClient)
client.baseURL = u.String()
client.host = u.Host
client.scheme = u.Scheme
client.respBuf = make([]byte, config.ResponseBufferSize)
client.config = config
if config.CompatibilityMode {
client.goClient = &http.Client{
// #TODO
// CheckRedirect: redirectPolicyFunc,
}
}
if u.User != nil {
client.auth = "Basic " + base64.StdEncoding.EncodeToString([]byte(u.User.String()))
}
client.proxy, _ = http.ProxyFromEnvironment(&http.Request{URL: u})
if client.isProxy() && client.proxy.User != nil {
client.proxyAuth = "Basic " + base64.StdEncoding.EncodeToString([]byte(client.proxy.User.String()))
}
return client
}
func (c *HTTPClient) Connect() (err error) {
c.Disconnect()
var toDial string
if !strings.Contains(c.host, ":") {
toDial = c.host + ":" + defaultPorts[c.scheme]
} else {
toDial = c.host
}
if c.isProxy() {
if c.proxy.Scheme != "http" {
panic("Unsupported HTTP Proxy method")
}
Debug("[HTTPClient] Connecting to proxy", c.proxy.String(), "<>", toDial)
c.conn, err = net.DialTimeout("tcp", c.proxy.Host, c.config.ConnectionTimeout)
if err != nil {
return
}
if c.scheme == "https" {
c.conn.Write([]byte("CONNECT " + toDial + " HTTP/1.1\r\n"))
if c.proxyAuth != "" {
c.conn.Write([]byte("Proxy-Authorization: " + c.proxyAuth + "\r\n"))
}
c.conn.Write([]byte("\r\n"))
br := bufio.NewReader(c.conn)
l, _, err := br.ReadLine()
if err != nil {
return err
}
if len(l) < 12 {
panic("HTTP proxy did not respond correctly")
}
status := l[9:12]
if !bytes.Equal(status, []byte("200")) {
panic("HTTP proxy did not respond correctly")
}
for {
// Read until we find the empty line
l, _, err := br.ReadLine()
if err != nil {
return err
}
if len(l) == 0 {
break
}
}
}
Debug("[HTTPClient] Proxy successfully connected")
} else {
c.conn, err = net.DialTimeout("tcp", toDial, c.config.ConnectionTimeout)
if err != nil {
return
}
}
if c.scheme == "https" {
// Wrap our socket in TLS
Debug("[HTTPClient] Wrapping socket in TLS", c.host)
tlsConn := tls.Client(c.conn, &tls.Config{InsecureSkipVerify: true, ServerName: c.host})
if err = tlsConn.Handshake(); err != nil {
return
}
c.conn = tlsConn
Debug("[HTTPClient] Successfully wrapped in TLS")
}
return
}
func (c *HTTPClient) Disconnect() {
if c.conn != nil {
c.conn.Close()
c.conn = nil
Debug("[HTTP] Disconnected: ", c.baseURL)
}
}
func (c *HTTPClient) isAlive(readBytes *int) bool {
// Ready 1 byte from socket without timeout to check if it not closed
c.conn.SetReadDeadline(time.Now().Add(time.Millisecond))
n, err := c.conn.Read(c.respBuf[:1])
if err == io.EOF {
Debug("[HTTPClient] connection closed, reconnecting")
return false
}
if err == syscall.EPIPE {
Debug("Detected broken pipe.", err)
return false
}
if n != 0 {
*readBytes += n
Debug("[HTTPClient] isAlive readBytes ", *readBytes)
}
return true
}
func (c *HTTPClient) SendGoClient(data []byte) ([]byte, error) {
var req *http.Request
var resp *http.Response
var err error
req, err = http.ReadRequest(bufio.NewReader(bytes.NewBuffer(data)))
if err != nil {
return nil, err
}
if !c.config.OriginalHost {
req.Host = c.host
}
if c.auth != "" {
req.Header.Add("Authorization", c.auth)
}
req.URL, _ = url.ParseRequestURI(c.scheme + "://" + c.host + req.RequestURI)
req.RequestURI = ""
resp, err = c.goClient.Do(req)
if err != nil {
return nil, err
}
return httputil.DumpResponse(resp, true)
}
func (c *HTTPClient) Send(data []byte) (response []byte, err error) {
// Don't exit on panic
defer func() {
if r := recover(); r != nil {
Debug("[HTTPClient]", r, string(data))
if _, ok := r.(error); ok {
log.Println("[HTTPClient] Failed to send request: ", string(data))
log.Println("[HTTPClient] Response: ", string(response))
log.Println("PANIC: pkg:", r, string(debug.Stack()))
}
}
}()
if c.config.CompatibilityMode {
return c.SendGoClient(data)
}
var readBytes int
if c.conn == nil || !c.isAlive(&readBytes) {
Debug("[HTTPClient] Connecting:", c.baseURL)
if err = c.Connect(); err != nil {
log.Println("[HTTPClient] Connection error:", err)
response = errorPayload(HTTP_CONNECTION_ERROR)
return
}
}
timeout := time.Now().Add(c.config.Timeout)
c.conn.SetWriteDeadline(timeout)
if !c.config.OriginalHost {
data = proto.SetHost(data, []byte(c.baseURL), []byte(c.host))
}
if c.isProxy() && c.scheme == "http" {
path := proto.Path(data)
if len(path) > 0 && path[0] == '/' {
data = proto.SetPath(data, c.proxyPath(path))
if c.proxyAuth != "" {
data = proto.SetHeader(data, []byte("Proxy-Authorization"), []byte(c.proxyAuth))
}
}
}
if c.auth != "" {
data = proto.SetHeader(data, []byte("Authorization"), []byte(c.auth))
}
if c.config.Debug {
Debug("[HTTPClient] Sending:", string(data))
}
return c.send(data, readBytes, timeout)
}
func (c *HTTPClient) send(data []byte, readBytes int, timeout time.Time) (response []byte, err error) {
var payload []byte
var n int
if _, err = c.conn.Write(data); err != nil {
Debug("[HTTPClient] Write error:", err, c.baseURL)
response = errorPayload(HTTP_TIMEOUT)
c.Disconnect()
return
}
var currentChunk []byte
timeout = time.Now().Add(c.config.Timeout)
chunked := false
contentLength := -1
currentContentLength := 0
chunks := 0
for {
c.conn.SetReadDeadline(timeout)
if readBytes < len(c.respBuf) {
n, err = c.conn.Read(c.respBuf[readBytes:])
readBytes += n
chunks++
// First chunk
if chunked || contentLength != -1 {
currentContentLength += n
} else {
// If headers are finished
var firstEmptyLine = bytes.Index(c.respBuf[:readBytes], proto.EmptyLine)
if firstEmptyLine != -1 {
if bytes.Equal(proto.Header(c.respBuf[:readBytes], []byte("Transfer-Encoding")), []byte("chunked")) {
chunked = true
} else {
status, _ := strconv.Atoi(string(proto.Status(c.respBuf[:readBytes])))
// We want to soak up all 100 Continues received to get the real result code
if status >= 100 && status < 200 {
timeout = time.Now().Add(c.config.Timeout)
var deleteLen = firstEmptyLine + len(proto.EmptyLine)
copy(c.respBuf, c.respBuf[deleteLen:readBytes])
readBytes -= deleteLen
chunks--
continue
} else if status == 204 || status == 304 {
contentLength = 0
break
} else {
l := proto.Header(c.respBuf[:readBytes], []byte("Content-Length"))
if len(l) > 0 {
contentLength, _ = strconv.Atoi(string(l))
}
}
}
currentContentLength += len(proto.Body(c.respBuf[:readBytes]))
}
}
if chunked {
// Check if chunked message finished
if bytes.HasSuffix(c.respBuf[:readBytes], chunkedSuffix) {
break
}
} else if contentLength != -1 {
if currentContentLength > contentLength {
Debug("[HTTPClient] disconnected, wrong length", currentContentLength, contentLength)
c.Disconnect()
break
} else if currentContentLength == contentLength {
break
}
}
if err != nil {
if err == io.EOF {
err = nil
}
break
}
} else {
if currentChunk == nil {
currentChunk = make([]byte, readChunkSize)
}
n, err = c.conn.Read(currentChunk)
readBytes += int(n)
chunks++
currentContentLength += n
if chunked {
// Check if chunked message finished
if bytes.HasSuffix(currentChunk[:n], chunkedSuffix) {
break
}
} else if contentLength != -1 {
if currentContentLength > contentLength {
Debug("[HTTPClient] disconnected, wrong length", currentContentLength, contentLength)
c.Disconnect()
break
} else if currentContentLength == contentLength {
break
}
} else {
Debug("[HTTPClient] disconnected, can't find Content-Length or Chunked")
c.Disconnect()
break
}
if err == io.EOF {
break
} else if err != nil {
Debug("[HTTPClient] Read the whole body error:", err, c.baseURL)
break
}
}
if readBytes >= maxResponseSize {
Debug("[HTTPClient] Body is more than the max size", maxResponseSize,
c.baseURL)
break
}
// For following chunks expect less timeout
timeout = time.Now().Add(c.config.Timeout / 5)
}
if err != nil && readBytes == 0 {
maxRead := 100
if readBytes < maxRead {
maxRead = readBytes
}
Debug("[HTTPClient] Response read timeout error", err, c.conn, readBytes, string(c.respBuf[:maxRead]))
response = errorPayload(HTTP_TIMEOUT)
c.Disconnect()
return
}
if readBytes < 4 || string(c.respBuf[:4]) != "HTTP" {
maxRead := 100
if readBytes < maxRead {
maxRead = readBytes
}
Debug("[HTTPClient] Response read unknown error", err, c.conn, readBytes, string(c.respBuf[:maxRead]))
response = errorPayload(HTTP_UNKNOWN_ERROR)
c.Disconnect()
return
}
if readBytes > len(c.respBuf) {
readBytes = len(c.respBuf)
}
payload = make([]byte, readBytes)
copy(payload, c.respBuf[:readBytes])
if c.config.Debug {
Debug("[HTTPClient] Received:", string(payload))
}
if c.config.FollowRedirects > 0 && c.redirectsCount < c.config.FollowRedirects {
status := payload[9:12]
// 3xx requests
if status[0] == '3' {
c.redirectsCount++
location := proto.Header(payload, []byte("Location"))
redirectPayload := proto.SetPath(data, location)
if c.config.Debug {
Debug("[HTTPClient] Redirecting to: " + string(location))
}
return c.Send(redirectPayload)
}
}
if bytes.Equal(proto.Status(payload), []byte("400")) {
Debug("[HTTPClient] Closed connection on 400 response")
c.Disconnect()
}
c.redirectsCount = 0
return payload, err
}
func (c *HTTPClient) Get(path string) (response []byte, err error) {
payload := "GET " + path + " HTTP/1.1\r\n\r\n"
return c.Send([]byte(payload))
}
func (c *HTTPClient) Post(path string, body []byte) (response []byte, err error) {
payload := "POST " + path + " HTTP/1.1\r\n"
payload += "Content-Length: " + strconv.Itoa(len(body)) + "\r\n\r\n"
payload += string(body)
return c.Send([]byte(payload))
}
func (c *HTTPClient) proxyPath(path []byte) []byte {
return append([]byte(c.scheme+"://"+c.host), path...)
}
func (c *HTTPClient) isProxy() bool {
return c.proxy != nil
}
const (
// https://support.cloudflare.com/hc/en-us/articles/200171936-Error-520-Web-server-is-returning-an-unknown-error
HTTP_UNKNOWN_ERROR = "520"
// https://support.cloudflare.com/hc/en-us/articles/200171916-Error-521-Web-server-is-down
HTTP_CONNECTION_ERROR = "521"
// https://support.cloudflare.com/hc/en-us/articles/200171906-Error-522-Connection-timed-out
HTTP_CONNECTION_TIMEOUT = "522"
// https://support.cloudflare.com/hc/en-us/articles/200171946-Error-523-Origin-is-unreachable
HTTP_UNREACHABLE = "523"
// https://support.cloudflare.com/hc/en-us/articles/200171926-Error-524-A-timeout-occurred
HTTP_TIMEOUT = "524"
)
var errorPayloadTemplate = "HTTP/1.1 202 Accepted\r\nDate: Mon, 17 Aug 2015 14:10:11 GMT\r\nContent-Length: 0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n"
func errorPayload(errorCode string) []byte {
payload := make([]byte, len(errorPayloadTemplate))
copy(payload, errorPayloadTemplate)
copy(payload[29:58], []byte(time.Now().Format(time.RFC1123)))
copy(payload[9:12], errorCode)
return payload
}
+533
View File
@@ -0,0 +1,533 @@
package main
import (
"bytes"
"crypto/rand"
"io/ioutil"
_ "log"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
_ "reflect"
"strings"
"sync"
"testing"
"time"
"github.com/buger/goreplay/proto"
)
func TestHTTPClientURLPort(t *testing.T) {
c1 := NewHTTPClient("http://example.com", &HTTPClientConfig{})
if c1.baseURL != "http://example.com" {
t.Error("Sould not add 80 port for http:", c1.baseURL)
}
c2 := NewHTTPClient("https://example.com", &HTTPClientConfig{})
if c2.baseURL != "https://example.com" {
t.Error("Sould not add 443 port for https:", c2.baseURL)
}
c3 := NewHTTPClient("https://example.com:1", &HTTPClientConfig{})
if c3.baseURL != "https://example.com:1" {
t.Error("Sould use specified port:", c3.baseURL)
}
c4 := NewHTTPClient("example.com", &HTTPClientConfig{})
if c4.baseURL != "http://example.com" {
t.Error("Sould not add default protocol:", c4.baseURL)
}
}
func TestHTTPClientSend(t *testing.T) {
wg := new(sync.WaitGroup)
payload := func(reqType string) []byte {
switch reqType {
case "GET":
return []byte("GET / HTTP/1.1\r\n\r\n")
case "POST":
return []byte("POST /post HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
case "POST_CHUNKED":
return []byte("POST / HTTP/1.1\r\nHost: www.w3.org\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nWiki\r\n5\r\npedia\r\ne\r\n in\r\n\r\nchunks.\r\n0\r\n\r\n")
}
return []byte("")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if len(r.TransferEncoding) > 0 && r.TransferEncoding[0] == "chunked" {
if string(body) != "Wikipedia in\r\n\r\nchunks." {
t.Error("Wrong POST body:", body, string(body))
}
} else {
if string(body) != "a=1&b=2" {
buf, _ := httputil.DumpRequest(r, true)
t.Error("Wrong POST body:", string(body), string(buf))
}
}
}
wg.Done()
}))
defer server.Close()
client := NewHTTPClient(server.URL, &HTTPClientConfig{Debug: true})
wg.Add(4)
client.Send(payload("POST"))
client.Send(payload("GET"))
client.Send(payload("POST_CHUNKED"))
client.Send(payload("POST"))
wg.Wait()
client = NewHTTPClient(server.URL, &HTTPClientConfig{Debug: true, CompatibilityMode: true})
wg.Add(4)
if _, err := client.Send(payload("POST")); err != nil {
t.Fatal(err.Error())
}
if _, err := client.Send(payload("GET")); err != nil {
t.Fatal(err.Error())
}
if _, err := client.Send(payload("POST_CHUNKED")); err != nil {
t.Fatal(err.Error())
}
if _, err := client.Send(payload("POST")); err != nil {
t.Fatal(err.Error())
}
wg.Wait()
}
func TestHTTPClientResonseByClose(t *testing.T) {
wg := new(sync.WaitGroup)
payload := []byte("GET / HTTP/1.1\r\n\r\n")
ln, _ := net.Listen("tcp", ":0")
go func() {
for {
conn, _ := ln.Accept()
buf := make([]byte, 4096)
conn.Read(buf)
conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
conn.Write([]byte("ab"))
conn.Close()
wg.Done()
}
}()
client := NewHTTPClient(ln.Addr().String(), &HTTPClientConfig{Debug: true})
wg.Add(1)
resp, _ := client.Send(payload)
if !bytes.Equal(resp, []byte("HTTP/1.1 200 OK\r\n\r\nab")) {
t.Error("Should return valid response", string(resp))
}
wg.Wait()
}
// https://github.com/buger/gor/issues/184
func TestHTTPClientResponseBuffer(t *testing.T) {
testCases := []struct {
name string
responseSize int
buffserSize int
expectedSize int
timeout time.Duration
}{
{"Chunked, buffer overflow", 10 * 1024, 1024, 1024, 50 * time.Millisecond},
{"Chunked, fits buffer", 10 * 1024, 64 * 1024, 10*1024 + 145 /* headers length + chunked meta */, 50 * time.Millisecond},
{"Content-Length, buffer overflow", 1024, 1000, 1000, 50 * time.Millisecond},
{"Content-Length, fits buffer", 1024, 64 * 1024, 1024 + 118, 50 * time.Millisecond},
}
for _, tc := range testCases {
wg := new(sync.WaitGroup)
payload := []byte("GET / HTTP/1.1\r\n\r\n")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
size := tc.responseSize // 1kb
rb := make([]byte, size)
rand.Read(rb)
w.Write(rb[:size/2])
w.Write(rb[size/2:])
wg.Done()
}))
client := NewHTTPClient(server.URL, &HTTPClientConfig{Debug: true, ResponseBufferSize: tc.buffserSize, Timeout: 100 * time.Millisecond})
wg.Add(2)
start := time.Now()
client.Send(payload)
resp, err := client.Send(payload)
stop := time.Now()
if err != nil {
t.Error("Request error", err)
}
if stop.Sub(start) > tc.timeout {
t.Error("Request took too long", stop.Sub(start), tc.timeout)
}
if len(resp) != tc.expectedSize {
t.Error(tc.name, " - Wrong response size:", tc.expectedSize, len(resp))
} else {
if !bytes.Equal(resp[0:8], []byte("HTTP/1.1")) {
t.Error(tc.name, " - Response buffer contains data from previous request", string(resp), len(resp))
}
}
wg.Wait()
server.Close()
}
}
func TestHTTPClientHTTPSSend(t *testing.T) {
wg := new(sync.WaitGroup)
payload := func(reqType string) []byte {
switch reqType {
case "GET":
return []byte("GET / HTTP/1.1\r\n\r\n")
case "POST":
return []byte("POST /post HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
case "POST_CHUNKED":
return []byte("POST / HTTP/1.1\r\nHost: www.w3.org\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nWiki\r\n5\r\npedia\r\ne\r\n in\r\n\r\nchunks.\r\n0\r\n\r\n")
}
return []byte("")
}
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if len(r.TransferEncoding) > 0 && r.TransferEncoding[0] == "chunked" {
if string(body) != "Wikipedia in\r\n\r\nchunks." {
t.Error("Wrong POST body:", body, string(body))
}
} else {
if string(body) != "a=1&b=2" {
buf, _ := httputil.DumpRequest(r, true)
t.Error("Wrong POST body:", string(body), string(buf))
}
}
}
wg.Done()
}))
defer server.Close()
client := NewHTTPClient(server.URL, &HTTPClientConfig{})
wg.Add(4)
client.Send(payload("POST"))
client.Send(payload("GET"))
client.Send(payload("POST_CHUNKED"))
client.Send(payload("POST"))
wg.Wait()
}
func TestHTTPClientServerInstantDisconnect(t *testing.T) {
wg := new(sync.WaitGroup)
GETPayload := []byte("GET / HTTP/1.1\r\n\r\n")
ln, _ := net.Listen("tcp", "127.0.0.1:0")
defer ln.Close()
go func() {
for {
conn, err := ln.Accept()
if err != nil {
break
}
conn.Close()
wg.Done()
}
}()
client := NewHTTPClient(ln.Addr().String(), &HTTPClientConfig{})
wg.Add(2)
client.Send(GETPayload)
client.Send(GETPayload)
wg.Wait()
}
func TestHTTPClientServerNoKeepAlive(t *testing.T) {
wg := new(sync.WaitGroup)
GETPayload := []byte("GET / HTTP/1.1\r\n\r\n")
ln, _ := net.Listen("tcp", "127.0.0.1:0")
defer ln.Close()
go func() {
for {
conn, err := ln.Accept()
if err != nil {
break
}
buf := make([]byte, 4096)
reqLen, err := conn.Read(buf)
if err != nil {
t.Error("Error reading:", err.Error())
}
Debug("Received: ", string(buf[0:reqLen]))
conn.Write([]byte("OK"))
// No keep-alive connections
conn.Close()
wg.Done()
}
}()
client := NewHTTPClient(ln.Addr().String(), &HTTPClientConfig{})
wg.Add(2)
client.Send(GETPayload)
client.Send(GETPayload)
wg.Wait()
}
func TestHTTPClientRedirect(t *testing.T) {
wg := new(sync.WaitGroup)
GETPayload := []byte("GET / HTTP/1.1\r\n\r\n")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/new", 301)
}
wg.Done()
}))
defer server.Close()
client := NewHTTPClient(server.URL, &HTTPClientConfig{FollowRedirects: 1, Debug: false})
// Should do 2 queries
wg.Add(2)
client.Send(GETPayload)
wg.Wait()
}
func TestHTTPClientRedirectLimit(t *testing.T) {
wg := new(sync.WaitGroup)
GETPayload := []byte("GET / HTTP/1.1\r\n\r\n")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/r1", 301)
}
if r.URL.Path == "/r1" {
http.Redirect(w, r, "/r2", 301)
}
if r.URL.Path == "/r2" {
http.Redirect(w, r, "/new", 301)
}
wg.Done()
}))
defer server.Close()
client := NewHTTPClient(server.URL, &HTTPClientConfig{FollowRedirects: 2, Debug: false})
// Have 3 redirects + 1 GET, but should do only 2 redirects + GET
wg.Add(3)
client.Send(GETPayload)
wg.Wait()
}
func TestHTTPClientKeepHeadersRedirect(t *testing.T) {
wg := new(sync.WaitGroup)
GETPayload := []byte("GET / HTTP/1.1\r\n\r\n")
GETPayload = proto.AddHeader(GETPayload, []byte("keep-header"), []byte("true"))
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/new", 301)
}
if r.Header.Get("keep-header") != "true" {
t.Errorf("Header keep-header was incorrect, got: %s, want: %s.", r.Header.Get("keep-header"), "true")
}
wg.Done()
}))
defer server.Close()
client := NewHTTPClient(server.URL, &HTTPClientConfig{FollowRedirects: 1, Debug: false})
wg.Add(2)
client.Send(GETPayload)
wg.Wait()
}
func TestHTTPClientBasicAuth(t *testing.T) {
wg := new(sync.WaitGroup)
wg.Add(2)
GETPayload := []byte("GET / HTTP/1.1\r\n\r\n")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, _ := r.BasicAuth()
if user != "user" || pass != "pass" {
http.Error(w, "Unauthorized.", 401)
wg.Done()
return
}
wg.Done()
}))
defer server.Close()
client := NewHTTPClient(server.URL, &HTTPClientConfig{Debug: false})
resp, _ := client.Send(GETPayload)
client.Disconnect()
if !bytes.Equal(proto.Status(resp), []byte("401")) {
t.Error("Should return unauthorized error", string(resp))
}
authUrl := strings.Replace(server.URL, "http://", "http://user:pass@", -1)
client = NewHTTPClient(authUrl, &HTTPClientConfig{Debug: false})
resp, _ = client.Send(GETPayload)
client.Disconnect()
if !bytes.Equal(proto.Status(resp), []byte("200")) {
t.Error("Should return proper response", string(resp))
}
wg.Wait()
}
func TestHTTPClientHandleHTTP10(t *testing.T) {
wg := new(sync.WaitGroup)
GETPayload := []byte("GET http://foobar.com/path HTTP/1.0\r\n\r\n")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/path" {
t.Error("Path not match:", r.URL.Path)
}
wg.Done()
}))
defer server.Close()
client := NewHTTPClient(server.URL, &HTTPClientConfig{Debug: true})
wg.Add(1)
client.Send(GETPayload)
wg.Wait()
}
func TestHTTPClientErrors(t *testing.T) {
req := []byte("GET http://foobar.com/path HTTP/1.0\r\n\r\n")
// Port not exists
client := NewHTTPClient("http://127.0.0.1:1", &HTTPClientConfig{Debug: true})
if resp, err := client.Send(req); err != nil {
if s := proto.Status(resp); !bytes.Equal(s, []byte("521")) {
t.Error("Should return status 521 for connection refused, instead:", string(s))
}
} else {
t.Error("Should throw error")
}
client = NewHTTPClient("http://not.existing", &HTTPClientConfig{Debug: true})
if resp, err := client.Send(req); err != nil {
if s := proto.Status(resp); !bytes.Equal(s, []byte("521")) {
t.Error("Should return status 521 for no such host, instead:", string(s))
}
} else {
t.Error("Should throw error")
}
// Non routable IP address to simulate connection timeout
client = NewHTTPClient("http://10.255.255.1", &HTTPClientConfig{Debug: true, ConnectionTimeout: 100 * time.Millisecond})
if resp, err := client.Send(req); err != nil {
if s := proto.Status(resp); !bytes.Equal(s, []byte("521")) {
t.Error("Should return status 521 for io/timeout:", string(s))
}
} else {
t.Error("Should throw error")
}
// Connecting but io timeout on read
ln, _ := net.Listen("tcp", "127.0.0.1:0")
client = NewHTTPClient("http://"+ln.Addr().String(), &HTTPClientConfig{Debug: true, Timeout: 10 * time.Millisecond})
defer ln.Close()
if resp, err := client.Send(req); err != nil {
if s := proto.Status(resp); !bytes.Equal(s, []byte("524")) {
t.Error("Should return status 524 for io read, instead:", string(s))
}
} else {
t.Error("Should throw error")
}
// Response read error read tcp [::1]:51128: connection reset by peer &{{0xc20802a000}}
ln1, _ := net.Listen("tcp", "127.0.0.1:0")
go func() {
ln1.Accept()
}()
defer ln1.Close()
client = NewHTTPClient("http://"+ln1.Addr().String(), &HTTPClientConfig{Debug: true, Timeout: 10 * time.Millisecond})
if resp, err := client.Send(req); err != nil {
if s := proto.Status(resp); !bytes.Equal(s, []byte("524")) {
t.Error("Should return status 524 for connection reset by peer, instead:", string(s))
}
} else {
t.Error("Should throw error")
}
}
+196
View File
@@ -0,0 +1,196 @@
package main
import (
"bytes"
"encoding/base64"
"hash/fnv"
"strings"
"github.com/buger/goreplay/proto"
)
type HTTPModifier struct {
config *HTTPModifierConfig
}
func NewHTTPModifier(config *HTTPModifierConfig) *HTTPModifier {
// Optimization to skip modifier completely if we do not need it
if len(config.urlRegexp) == 0 &&
len(config.urlNegativeRegexp) == 0 &&
len(config.urlRewrite) == 0 &&
len(config.headerRewrite) == 0 &&
len(config.headerFilters) == 0 &&
len(config.headerNegativeFilters) == 0 &&
len(config.headerBasicAuthFilters) == 0 &&
len(config.headerHashFilters) == 0 &&
len(config.paramHashFilters) == 0 &&
len(config.params) == 0 &&
len(config.headers) == 0 &&
len(config.methods) == 0 {
return nil
}
return &HTTPModifier{config: config}
}
func (m *HTTPModifier) Rewrite(payload []byte) (response []byte) {
if !proto.IsHTTPPayload(payload) {
return payload
}
if len(m.config.methods) > 0 {
method := proto.Method(payload)
matched := false
for _, m := range m.config.methods {
if bytes.Equal(method, m) {
matched = true
break
}
}
if !matched {
return
}
}
if len(m.config.headers) > 0 {
for _, header := range m.config.headers {
payload = proto.SetHeader(payload, []byte(header.Name), []byte(header.Value))
}
}
if len(m.config.params) > 0 {
for _, param := range m.config.params {
payload = proto.SetPathParam(payload, param.Name, param.Value)
}
}
if len(m.config.urlRegexp) > 0 {
path := proto.Path(payload)
matched := false
for _, f := range m.config.urlRegexp {
if f.regexp.Match(path) {
matched = true
break
}
}
if !matched {
return
}
}
if len(m.config.urlNegativeRegexp) > 0 {
path := proto.Path(payload)
for _, f := range m.config.urlNegativeRegexp {
if f.regexp.Match(path) {
return
}
}
}
if len(m.config.headerFilters) > 0 {
for _, f := range m.config.headerFilters {
value := proto.Header(payload, f.name)
if len(value) == 0 {
return
}
if !f.regexp.Match(value) {
return
}
}
}
if len(m.config.headerNegativeFilters) > 0 {
for _, f := range m.config.headerNegativeFilters {
value := proto.Header(payload, f.name)
if len(value) > 0 && f.regexp.Match(value) {
return
}
}
}
if len(m.config.headerBasicAuthFilters) > 0 {
for _, f := range m.config.headerBasicAuthFilters {
value := proto.Header(payload, []byte("Authorization"))
if len(value) > 0 {
valueString := string(value)
trimmedBasicAuthEncoded := strings.TrimPrefix(valueString, "Basic ")
if strings.Compare(valueString, trimmedBasicAuthEncoded) != 0 {
decodedAuth, _ := base64.StdEncoding.DecodeString(trimmedBasicAuthEncoded)
if !f.regexp.Match(decodedAuth) {
return
}
}
}
}
}
if len(m.config.headerHashFilters) > 0 {
for _, f := range m.config.headerHashFilters {
value := proto.Header(payload, f.name)
if len(value) > 0 {
hasher := fnv.New32a()
hasher.Write(value)
if (hasher.Sum32() % 100) >= f.percent {
return
}
}
}
}
if len(m.config.paramHashFilters) > 0 {
for _, f := range m.config.paramHashFilters {
value, s, _ := proto.PathParam(payload, f.name)
if s != -1 {
hasher := fnv.New32a()
hasher.Write(value)
if (hasher.Sum32() % 100) >= f.percent {
return
}
}
}
}
if len(m.config.urlRewrite) > 0 {
path := proto.Path(payload)
for _, f := range m.config.urlRewrite {
if f.src.Match(path) {
path = f.src.ReplaceAll(path, f.target)
payload = proto.SetPath(payload, path)
break
}
}
}
if len(m.config.headerRewrite) > 0 {
for _, f := range m.config.headerRewrite {
value := proto.Header(payload, f.header)
if len(value) == 0 {
break
}
if f.src.Match(value) {
newValue := f.src.ReplaceAll(value, f.target)
payload = proto.SetHeader(payload, f.header, newValue)
}
}
}
return payload
}
+281
View File
@@ -0,0 +1,281 @@
package main
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
// HTTPModifierConfig holds configuration options for built-in traffic modifier
type HTTPModifierConfig struct {
urlNegativeRegexp HTTPUrlRegexp
urlRegexp HTTPUrlRegexp
urlRewrite UrlRewriteMap
headerRewrite HeaderRewriteMap
headerFilters HTTPHeaderFilters
headerNegativeFilters HTTPHeaderFilters
headerBasicAuthFilters HTTPHeaderBasicAuthFilters
headerHashFilters HTTPHashFilters
paramHashFilters HTTPHashFilters
params HTTPParams
headers HTTPHeaders
methods HTTPMethods
}
//
// Handling of --http-allow-header, --http-disallow-header options
//
type headerFilter struct {
name []byte
regexp *regexp.Regexp
}
// HTTPHeaderFilters holds list of headers and their regexps
type HTTPHeaderFilters []headerFilter
func (h *HTTPHeaderFilters) String() string {
return fmt.Sprint(*h)
}
func (h *HTTPHeaderFilters) Set(value string) error {
valArr := strings.SplitN(value, ":", 2)
if len(valArr) < 2 {
return errors.New("need both header and value, colon-delimited (ex. user_id:^169$).")
}
val := strings.TrimSpace(valArr[1])
r, err := regexp.Compile(val)
if err != nil {
return err
}
*h = append(*h, headerFilter{name: []byte(valArr[0]), regexp: r})
return nil
}
//
// Handling of --http-basic-auth-filter option
//
type basicAuthFilter struct {
regexp *regexp.Regexp
}
// HTTPHeaderFilters holds list of headers and their regexps
type HTTPHeaderBasicAuthFilters []basicAuthFilter
func (h *HTTPHeaderBasicAuthFilters) String() string {
return fmt.Sprint(*h)
}
func (h *HTTPHeaderBasicAuthFilters) Set(value string) error {
r, err := regexp.Compile(value)
if err != nil {
return err
}
*h = append(*h, basicAuthFilter{regexp: r})
return nil
}
//
// Handling of --http-allow-header-hash and --http-allow-param-hash options
//
type hashFilter struct {
name []byte
percent uint32
}
type HTTPHashFilters []hashFilter
func (h *HTTPHashFilters) String() string {
return fmt.Sprint(*h)
}
func (h *HTTPHashFilters) Set(value string) error {
valArr := strings.SplitN(value, ":", 2)
if len(valArr) < 2 {
return errors.New("need both header and value, colon-delimited (ex. user_id:50%)")
}
f := hashFilter{name: []byte(valArr[0])}
val := strings.TrimSpace(valArr[1])
if strings.Contains(val, "%") {
p, _ := strconv.ParseInt(val[:len(val)-1], 0, 0)
f.percent = uint32(p)
} else if strings.Contains(val, "/") {
// DEPRECATED format
var num, den uint64
fracArr := strings.Split(val, "/")
num, _ = strconv.ParseUint(fracArr[0], 10, 64)
den, _ = strconv.ParseUint(fracArr[1], 10, 64)
f.percent = uint32((float64(num) / float64(den)) * 100)
} else {
return errors.New("Value should be percent and contain '%'")
}
*h = append(*h, f)
return nil
}
//
// Handling of --http-set-header option
//
type HTTPHeaders []HTTPHeader
type HTTPHeader struct {
Name string
Value string
}
func (h *HTTPHeaders) String() string {
return fmt.Sprint(*h)
}
func (h *HTTPHeaders) Set(value string) error {
v := strings.SplitN(value, ":", 2)
if len(v) != 2 {
return errors.New("Expected `Key: Value`")
}
header := HTTPHeader{
strings.TrimSpace(v[0]),
strings.TrimSpace(v[1]),
}
*h = append(*h, header)
return nil
}
//
// Handling of --http-set-param option
//
type HTTPParams []HTTPParam
type HTTPParam struct {
Name []byte
Value []byte
}
func (h *HTTPParams) String() string {
return fmt.Sprint(*h)
}
func (h *HTTPParams) Set(value string) error {
v := strings.SplitN(value, "=", 2)
if len(v) != 2 {
return errors.New("Expected `Key=Value`")
}
param := HTTPParam{
[]byte(strings.TrimSpace(v[0])),
[]byte(strings.TrimSpace(v[1])),
}
*h = append(*h, param)
return nil
}
//
// Handling of --http-allow-method option
//
type HTTPMethods [][]byte
func (h *HTTPMethods) String() string {
return fmt.Sprint(*h)
}
func (h *HTTPMethods) Set(value string) error {
*h = append(*h, []byte(value))
return nil
}
//
// Handling of --http-rewrite-url option
//
type urlRewrite struct {
src *regexp.Regexp
target []byte
}
type UrlRewriteMap []urlRewrite
func (r *UrlRewriteMap) String() string {
return fmt.Sprint(*r)
}
func (r *UrlRewriteMap) Set(value string) error {
valArr := strings.SplitN(value, ":", 2)
if len(valArr) < 2 {
return errors.New("need both src and target, colon-delimited (ex. /a:/b)")
}
regexp, err := regexp.Compile(valArr[0])
if err != nil {
return err
}
*r = append(*r, urlRewrite{src: regexp, target: []byte(valArr[1])})
return nil
}
//
// Handling of --http-rewrite-header option
//
type headerRewrite struct {
header []byte
src *regexp.Regexp
target []byte
}
type HeaderRewriteMap []headerRewrite
func (r *HeaderRewriteMap) String() string {
return fmt.Sprint(*r)
}
func (r *HeaderRewriteMap) Set(value string) error {
headerArr := strings.SplitN(value, ":", 2)
if len(headerArr) < 2 {
return errors.New("need both header, regexp and rewrite target, colon-delimited (ex. Header: regexp,target)")
}
header := headerArr[0]
valArr := strings.SplitN(strings.TrimSpace(headerArr[1]), ",", 2)
if len(valArr) < 2 {
return errors.New("need both header, regexp and rewrite target, colon-delimited (ex. Header: regexp,target)")
}
regexp, err := regexp.Compile(valArr[0])
if err != nil {
return err
}
*r = append(*r, headerRewrite{header: []byte(header), src: regexp, target: []byte(valArr[1])})
return nil
}
//
// Handling of --http-allow-url option
//
type urlRegexp struct {
regexp *regexp.Regexp
}
type HTTPUrlRegexp []urlRegexp
func (r *HTTPUrlRegexp) String() string {
return fmt.Sprint(*r)
}
func (r *HTTPUrlRegexp) Set(value string) error {
regexp, err := regexp.Compile(value)
*r = append(*r, urlRegexp{regexp: regexp})
return err
}
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"testing"
)
func TestHTTPHeaderFilters(t *testing.T) {
filters := HTTPHeaderFilters{}
err := filters.Set("Header1:^$")
if err != nil {
t.Error("Should not error on Header1:^$")
}
err = filters.Set("Header2:^:$")
if err != nil {
t.Error("Should not error on Header2:^:$")
}
// Missing colon
err = filters.Set("Header3-^$")
if err == nil {
t.Error("Should error on Header2:^:$")
}
}
func TestHTTPHashFilters(t *testing.T) {
filters := HTTPHashFilters{}
err := filters.Set("Header1:1/2")
if err != nil {
t.Error("Should support old syntax")
}
if filters[0].percent != 50 {
t.Error("Wrong percentage", filters[0].percent)
}
err = filters.Set("Header2:1")
if err == nil {
t.Error("Should error on Header2 because no % symbol")
}
err = filters.Set("Header2:10%")
if err != nil {
t.Error("Should pass")
}
if filters[1].percent != 10 {
t.Error("Wrong percentage", filters[1].percent)
}
}
func TestUrlRewriteMap(t *testing.T) {
var err error
rewrites := UrlRewriteMap{}
if err = rewrites.Set("/v1/user/([^\\/]+)/ping:/v2/user/$1/ping"); err != nil {
t.Error("Should set mapping", err)
}
if err = rewrites.Set("/v1/user/([^\\/]+)/ping"); err == nil {
t.Error("Should not set mapping without :")
}
}
+320
View File
@@ -0,0 +1,320 @@
package main
import (
"bytes"
"testing"
"github.com/buger/goreplay/proto"
)
func TestHTTPModifierWithoutConfig(t *testing.T) {
if NewHTTPModifier(&HTTPModifierConfig{}) != nil {
t.Error("If no config specified should not be initialized")
}
}
func TestHTTPModifierHeaderFilters(t *testing.T) {
filters := HTTPHeaderFilters{}
filters.Set("Host:^www.w3.org$")
modifier := NewHTTPModifier(&HTTPModifierConfig{
headerFilters: filters,
})
payload := []byte("POST /post HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
if len(modifier.Rewrite(payload)) == 0 {
t.Error("Request should pass filters")
}
filters = HTTPHeaderFilters{}
// Setting filter that not match our header
filters.Set("Host:^www.w4.org$")
modifier = NewHTTPModifier(&HTTPModifierConfig{
headerFilters: filters,
})
if len(modifier.Rewrite(payload)) != 0 {
t.Error("Request should not pass filters")
}
}
func TestHTTPModifierHeaderNegativeFilters(t *testing.T) {
filters := HTTPHeaderFilters{}
filters.Set("Host:^www.w3.org$")
modifier := NewHTTPModifier(&HTTPModifierConfig{
headerNegativeFilters: filters,
})
payload := []byte("POST /post HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w4.org\r\n\r\na=1&b=2")
if len(modifier.Rewrite(payload)) == 0 {
t.Error("Request should pass filters")
}
filters = HTTPHeaderFilters{}
// Setting filter that not match our header
filters.Set("Host:^www.w4.org$")
modifier = NewHTTPModifier(&HTTPModifierConfig{
headerNegativeFilters: filters,
})
if len(modifier.Rewrite(payload)) != 0 {
t.Error("Request should not pass filters")
}
filters = HTTPHeaderFilters{}
// Setting filter that not match our header
filters.Set("Host: www*")
modifier = NewHTTPModifier(&HTTPModifierConfig{
headerNegativeFilters: filters,
})
if len(modifier.Rewrite(payload)) != 0 {
t.Error("Request should not pass filters")
}
}
func TestHTTPHeaderBasicAuthFilters(t *testing.T) {
filters := HTTPHeaderBasicAuthFilters{}
filters.Set("^customer[0-9].*")
modifier := NewHTTPModifier(&HTTPModifierConfig{
headerBasicAuthFilters: filters,
})
//Encoded UserId:Password = customer3:welcome
payload := []byte("POST /post HTTP/1.1\r\nContent-Length: 7\r\nAuthorization: Basic Y3VzdG9tZXIzOndlbGNvbWU=\r\n\r\na=1&b=2")
if len(modifier.Rewrite(payload)) == 0 {
t.Error("Request should pass filters")
}
//customer6:rest@123^TEST
payload = []byte("POST /post HTTP/1.1\r\nContent-Length: 88\r\nAuthorization: Basic Y3VzdG9tZXI2OnJlc3RAMTIzXlRFU1Q==\r\n\r\na=1&b=2")
if len(modifier.Rewrite(payload)) == 0 {
t.Error("Request should pass filters")
}
filters = HTTPHeaderBasicAuthFilters{}
// Setting filter that not match our header
filters.Set("^(homer simpson|mickey mouse).*")
modifier = NewHTTPModifier(&HTTPModifierConfig{
headerBasicAuthFilters: filters,
})
if len(modifier.Rewrite(payload)) != 0 {
t.Error("Request should not pass filters")
}
//mickey mouse:happy123
payload = []byte("POST /post HTTP/1.1\r\nContent-Length: 88\r\nAuthorization: Basic bWlja2V5IG1vdXNlOmhhcHB5MTIz\r\n\r\na=1&b=2")
if len(modifier.Rewrite(payload)) == 0 {
t.Error("Request should pass filters")
}
}
func TestHTTPModifierURLRewrite(t *testing.T) {
var url, newURL []byte
rewrites := UrlRewriteMap{}
payload := func(url []byte) []byte {
return []byte("POST " + string(url) + " HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
}
err := rewrites.Set("/v1/user/([^\\/]+)/ping:/v2/user/$1/ping")
if err != nil {
t.Error("Should not error on /v1/user/([^\\/]+)/ping:/v2/user/$1/ping")
}
modifier := NewHTTPModifier(&HTTPModifierConfig{
urlRewrite: rewrites,
})
url = []byte("/v1/user/joe/ping")
if newURL = proto.Path(modifier.Rewrite(payload(url))); bytes.Equal(newURL, url) {
t.Error("Request url should have been rewritten, wasn't", string(newURL))
}
url = []byte("/v1/user/ping")
if newURL = proto.Path(modifier.Rewrite(payload(url))); !bytes.Equal(newURL, url) {
t.Error("Request url should have been rewritten, wasn't", string(newURL))
}
}
func TestHTTPModifierHeaderRewrite(t *testing.T) {
var header, newHeader []byte
rewrites := HeaderRewriteMap{}
payload := []byte("GET / HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
err := rewrites.Set("Host: (.*).w3.org,$1.beta.w3.org")
if err != nil {
t.Error("Should not error", err)
}
modifier := NewHTTPModifier(&HTTPModifierConfig{
headerRewrite: rewrites,
})
header = []byte("www.beta.w3.org")
if newHeader = proto.Header(modifier.Rewrite(payload), []byte("Host")); !bytes.Equal(newHeader, header) {
t.Error("Request header should have been rewritten, wasn't", string(newHeader), string(header))
}
}
func TestHTTPModifierHeaderHashFilters(t *testing.T) {
filters := HTTPHashFilters{}
filters.Set("Header2:1/2")
modifier := NewHTTPModifier(&HTTPModifierConfig{
headerHashFilters: filters,
})
payload := func(header []byte) []byte {
return []byte("POST / HTTP/1.1\r\n" + string(header) + "Content-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
}
if p := modifier.Rewrite(payload([]byte(""))); len(p) == 0 {
t.Error("Request should pass filters if Header does not exist")
}
if p := modifier.Rewrite(payload([]byte("Header2: 3\r\n"))); len(p) > 0 {
t.Error("Request should not pass filters, Header2 hash too high")
}
if p := modifier.Rewrite(payload([]byte("Header2: 1\r\n"))); len(p) == 0 {
t.Error("Request should pass filters")
}
}
func TestHTTPModifierParamHashFilters(t *testing.T) {
filters := HTTPHashFilters{}
filters.Set("user_id:1/2")
modifier := NewHTTPModifier(&HTTPModifierConfig{
paramHashFilters: filters,
})
payload := func(value []byte) []byte {
return []byte("POST /" + string(value) + " HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
}
if p := modifier.Rewrite(payload([]byte(""))); len(p) == 0 {
t.Error("Request should pass filters if param does not exist")
}
if p := modifier.Rewrite(payload([]byte("?user_id=3"))); len(p) > 0 {
t.Error("Request should not pass filters", string(p))
}
if p := modifier.Rewrite(payload([]byte("?user_id=1"))); len(p) == 0 {
t.Error("Request should pass filters")
}
}
func TestHTTPModifierHeaders(t *testing.T) {
headers := HTTPHeaders{}
headers.Set("Header1:1")
headers.Set("Host:localhost")
modifier := NewHTTPModifier(&HTTPModifierConfig{
headers: headers,
})
payload := []byte("POST /post HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
newPayload := []byte("POST /post HTTP/1.1\r\nHeader1: 1\r\nContent-Length: 7\r\nHost: localhost\r\n\r\na=1&b=2")
if payload = modifier.Rewrite(payload); !bytes.Equal(payload, newPayload) {
t.Error("Should update request headers", string(payload))
}
}
func TestHTTPModifierURLRegexp(t *testing.T) {
filters := HTTPUrlRegexp{}
filters.Set("/v1/app")
filters.Set("/v1/api")
modifier := NewHTTPModifier(&HTTPModifierConfig{
urlRegexp: filters,
})
payload := func(url string) []byte {
return []byte("POST " + url + " HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
}
if len(modifier.Rewrite(payload("/v1/app/test"))) == 0 {
t.Error("Should pass url")
}
if len(modifier.Rewrite(payload("/v1/api/test"))) == 0 {
t.Error("Should pass url")
}
if len(modifier.Rewrite(payload("/other"))) > 0 {
t.Error("Should not pass url")
}
}
func TestHTTPModifierURLNegativeRegexp(t *testing.T) {
filters := HTTPUrlRegexp{}
filters.Set("/restricted1")
filters.Set("/some/restricted2")
modifier := NewHTTPModifier(&HTTPModifierConfig{
urlNegativeRegexp: filters,
})
payload := func(url string) []byte {
return []byte("POST " + url + " HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
}
if len(modifier.Rewrite(payload("/v1/app/test"))) == 0 {
t.Error("Should pass url")
}
if len(modifier.Rewrite(payload("/restricted1"))) > 0 {
t.Error("Should not pass url")
}
if len(modifier.Rewrite(payload("/some/restricted2"))) > 0 {
t.Error("Should not pass url")
}
}
func TestHTTPModifierSetHeader(t *testing.T) {
filters := HTTPHeaders{}
filters.Set("User-Agent:Gor")
modifier := NewHTTPModifier(&HTTPModifierConfig{
headers: filters,
})
payload := []byte("POST /post HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
payloadAfter := []byte("POST /post HTTP/1.1\r\nUser-Agent: Gor\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
if payload = modifier.Rewrite(payload); !bytes.Equal(payloadAfter, payload) {
t.Error("Should add new header", string(payload))
}
}
func TestHTTPModifierSetParam(t *testing.T) {
filters := HTTPParams{}
filters.Set("api_key=1")
modifier := NewHTTPModifier(&HTTPModifierConfig{
params: filters,
})
payload := []byte("POST /post?api_key=1234 HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
payloadAfter := []byte("POST /post?api_key=1 HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
if payload = modifier.Rewrite(payload); !bytes.Equal(payloadAfter, payload) {
t.Error("Should override param", string(payload))
}
}
+75
View File
@@ -0,0 +1,75 @@
package main
import (
"bytes"
"compress/gzip"
"io/ioutil"
"net/http/httputil"
"strconv"
"github.com/buger/goreplay/proto"
)
func prettifyHTTP(p []byte) []byte {
headSize := bytes.IndexByte(p, '\n') + 1
head := p[:headSize]
body := p[headSize:]
headersPos := proto.MIMEHeadersEndPos(body)
if headersPos < 5 || headersPos > len(body) {
return p
}
headers := body[:headersPos]
content := body[headersPos:]
var tEnc, cEnc []byte
proto.ParseHeaders([][]byte{headers}, func(header, value []byte) bool {
if proto.HeadersEqual(header, []byte("Transfer-Encoding")) {
tEnc = value
}
if proto.HeadersEqual(header, []byte("Content-Encoding")) {
cEnc = value
}
return true
})
if len(tEnc) == 0 && len(cEnc) == 0 {
return p
}
if bytes.Equal(tEnc, []byte("chunked")) {
buf := bytes.NewBuffer(content)
r := httputil.NewChunkedReader(buf)
content, _ = ioutil.ReadAll(r)
headers = proto.DeleteHeader(headers, []byte("Transfer-Encoding"))
newLen := strconv.Itoa(len(content))
headers = proto.SetHeader(headers, []byte("Content-Length"), []byte(newLen))
}
if bytes.Equal(cEnc, []byte("gzip")) {
buf := bytes.NewBuffer(content)
g, err := gzip.NewReader(buf)
if err != nil {
Debug("[Prettifier] GZIP encoding error:", err)
return []byte{}
}
content, _ = ioutil.ReadAll(g)
headers = proto.DeleteHeader(headers, []byte("Content-Encoding"))
newLen := strconv.Itoa(len(content))
headers = proto.SetHeader(headers, []byte("Content-Length"), []byte(newLen))
}
newPayload := append(append(head, headers...), content...)
return newPayload
}
+36
View File
@@ -0,0 +1,36 @@
package main
import (
"bytes"
"compress/gzip"
"strconv"
"testing"
)
func TestHTTPPrettifierGzip(t *testing.T) {
b := bytes.NewBufferString("")
w := gzip.NewWriter(b)
w.Write([]byte("test"))
w.Close()
size := strconv.Itoa(len(b.Bytes()))
payload := []byte("2 1 1\nHTTP/1.1 200 OK\r\nContent-Length: " + size + "\r\nContent-Encoding: gzip\r\n\r\n")
payload = append(payload, b.Bytes()...)
newPayload := prettifyHTTP(payload)
if string(newPayload) != "2 1 1\nHTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest" {
t.Error("Payload not match:", string(newPayload))
}
}
func TestHTTPPrettifierChunked(t *testing.T) {
payload := []byte("POST / HTTP/1.1\r\nHost: www.w3.org\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nWiki\r\n5\r\npedia\r\ne\r\n in\r\n\r\nchunks.\r\n0\r\n\r\n")
newPayload := prettifyHTTP(payload)
if string(newPayload) != "POST / HTTP/1.1\r\nHost: www.w3.org\r\nContent-Length: 23\r\n\r\nWikipedia in\r\n\r\nchunks." {
t.Error("Payload not match:", string(newPayload))
}
}
+48
View File
@@ -0,0 +1,48 @@
package main
import (
"time"
)
// DummyInput used for debugging. It generate 1 "GET /"" request per second.
type DummyInput struct {
data chan []byte
}
// NewDummyInput constructor for DummyInput
func NewDummyInput(options string) (di *DummyInput) {
di = new(DummyInput)
di.data = make(chan []byte)
go di.emit()
return
}
func (i *DummyInput) Read(data []byte) (int, error) {
buf := <-i.data
copy(data, buf)
return len(buf), nil
}
func (i *DummyInput) emit() {
ticker := time.NewTicker(time.Second)
for {
select {
case <-ticker.C:
uuid := uuid()
reqh := payloadHeader(RequestPayload, uuid, time.Now().UnixNano(), -1)
i.data <- append(reqh, []byte("GET / HTTP/1.1\r\nHost: www.w3.org\r\nUser-Agent: Go 1.1 package http\r\nAccept-Encoding: gzip\r\n\r\n")...)
resh := payloadHeader(ResponsePayload, uuid, time.Now().UnixNano()+1, 1)
i.data <- append(resh, []byte("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")...)
}
}
}
func (i *DummyInput) String() string {
return "Dummy Input"
}
+245
View File
@@ -0,0 +1,245 @@
package main
import (
"bufio"
"bytes"
"compress/gzip"
"errors"
"io"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
type fileInputReader struct {
reader *bufio.Reader
data []byte
file *os.File
timestamp int64
}
func (f *fileInputReader) parseNext() error {
payloadSeparatorAsBytes := []byte(payloadSeparator)
var buffer bytes.Buffer
for {
line, err := f.reader.ReadBytes('\n')
if err != nil {
if err != io.EOF {
log.Println(err)
return err
}
if err == io.EOF {
f.file.Close()
f.file = nil
return err
}
}
if bytes.Equal(payloadSeparatorAsBytes[1:], line) {
asBytes := buffer.Bytes()
meta := payloadMeta(asBytes)
f.timestamp, _ = strconv.ParseInt(string(meta[2]), 10, 64)
f.data = asBytes[:len(asBytes)-1]
return nil
}
buffer.Write(line)
}
return nil
}
func (f *fileInputReader) ReadPayload() []byte {
defer f.parseNext()
return f.data
}
func (f *fileInputReader) Close() error {
if f.file != nil {
f.file.Close()
}
return nil
}
func NewFileInputReader(path string) *fileInputReader {
file, err := os.Open(path)
if err != nil {
log.Println(err)
return nil
}
r := &fileInputReader{file: file}
if strings.HasSuffix(path, ".gz") {
gzReader, err := gzip.NewReader(file)
if err != nil {
log.Println(err)
return nil
}
r.reader = bufio.NewReader(gzReader)
} else {
r.reader = bufio.NewReader(file)
}
r.parseNext()
return r
}
// FileInput can read requests generated by FileOutput
type FileInput struct {
mu sync.Mutex
data chan []byte
exit chan bool
path string
readers []*fileInputReader
speedFactor float64
loop bool
}
// NewFileInput constructor for FileInput. Accepts file path as argument.
func NewFileInput(path string, loop bool) (i *FileInput) {
i = new(FileInput)
i.data = make(chan []byte, 1000)
i.exit = make(chan bool, 1)
i.path = path
i.speedFactor = 1
i.loop = loop
if err := i.init(); err != nil {
return
}
go i.emit()
return
}
type NextFileNotFound struct{}
func (_ *NextFileNotFound) Error() string {
return "There is no new files"
}
func (i *FileInput) init() (err error) {
defer i.mu.Unlock()
i.mu.Lock()
var matches []string
if matches, err = filepath.Glob(i.path); err != nil {
log.Println("Wrong file pattern", i.path, err)
return
}
if len(matches) == 0 {
log.Println("No files match pattern: ", i.path)
return errors.New("No matching files")
}
i.readers = make([]*fileInputReader, len(matches))
for idx, p := range matches {
i.readers[idx] = NewFileInputReader(p)
}
return nil
}
func (i *FileInput) Read(data []byte) (int, error) {
buf := <-i.data
copy(data, buf)
return len(buf), nil
}
func (i *FileInput) String() string {
return "File input: " + i.path
}
// Find reader with smallest timestamp e.g next payload in row
func (i *FileInput) nextReader() (next *fileInputReader) {
for _, r := range i.readers {
if r == nil || r.file == nil {
continue
}
if next == nil || r.timestamp < next.timestamp {
next = r
continue
}
}
return
}
func (i *FileInput) emit() {
var lastTime int64 = -1
for {
select {
case <-i.exit:
return
default:
}
reader := i.nextReader()
if reader == nil {
if i.loop {
i.init()
lastTime = -1
continue
} else {
break
}
}
if lastTime != -1 {
diff := reader.timestamp - lastTime
lastTime = reader.timestamp
if i.speedFactor != 1 {
diff = int64(float64(diff) / i.speedFactor)
}
time.Sleep(time.Duration(diff))
} else {
lastTime = reader.timestamp
}
i.data <- reader.ReadPayload()
}
log.Printf("FileInput: end of file '%s'\n", i.path)
// For now having fixed timeout is temporary solution
// Further should be modified, so outputs can report if their queue empty or not
time.Sleep(time.Second)
if closeCh != nil {
close(closeCh)
}
}
func (i *FileInput) Close() error {
defer i.mu.Unlock()
i.mu.Lock()
i.exit <- true
for _, r := range i.readers {
r.Close()
}
return nil
}
+382
View File
@@ -0,0 +1,382 @@
package main
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"os"
"sync"
"syscall"
"testing"
"time"
)
var _ = log.Println
func TestInputFileWithGET(t *testing.T) {
input := NewTestInput()
rg := NewRequestGenerator([]io.Reader{input}, func() { input.EmitGET() }, 1)
readPayloads := [][]byte{}
// Given a capture file with a GET request
expectedCaptureFile := CreateCaptureFile(rg)
defer expectedCaptureFile.TearDown()
// When the request is read from the capture file
err := ReadFromCaptureFile(expectedCaptureFile.file, 1, func(data []byte) {
readPayloads = append(readPayloads, Duplicate(data))
})
// The read request should match the original request
if err != nil {
t.Error(err)
} else {
if !expectedCaptureFile.PayloadsEqual(readPayloads) {
t.Error("Request read back from file should match")
}
}
}
func TestInputFileWithPayloadLargerThan64Kb(t *testing.T) {
input := NewTestInput()
rg := NewRequestGenerator([]io.Reader{input}, func() { input.EmitSizedPOST(64 * 1024) }, 1)
readPayloads := [][]byte{}
// Given a capture file with a request over 64Kb
expectedCaptureFile := CreateCaptureFile(rg)
defer expectedCaptureFile.TearDown()
// When the request is read from the capture file
err := ReadFromCaptureFile(expectedCaptureFile.file, 1, func(data []byte) {
readPayloads = append(readPayloads, Duplicate(data))
})
// The read request should match the original request
if err != nil {
t.Error(err)
} else {
if !expectedCaptureFile.PayloadsEqual(readPayloads) {
t.Error("Request read back from file should match")
}
}
}
func TestInputFileWithGETAndPOST(t *testing.T) {
input := NewTestInput()
rg := NewRequestGenerator([]io.Reader{input}, func() {
input.EmitGET()
input.EmitPOST()
}, 2)
readPayloads := [][]byte{}
// Given a capture file with a GET request
expectedCaptureFile := CreateCaptureFile(rg)
defer expectedCaptureFile.TearDown()
// When the requests are read from the capture file
err := ReadFromCaptureFile(expectedCaptureFile.file, 2, func(data []byte) {
readPayloads = append(readPayloads, Duplicate(data))
})
// The read requests should match the original request
if err != nil {
t.Error(err)
} else {
if !expectedCaptureFile.PayloadsEqual(readPayloads) {
t.Error("Request read back from file should match")
}
}
}
func TestInputFileMultipleFilesWithRequestsOnly(t *testing.T) {
rnd := rand.Int63()
file1, _ := os.OpenFile(fmt.Sprintf("/tmp/%d_0", rnd), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
file1.Write([]byte("1 1 1\ntest1"))
file1.Write([]byte(payloadSeparator))
file1.Write([]byte("1 1 3\ntest2"))
file1.Write([]byte(payloadSeparator))
file1.Close()
file2, _ := os.OpenFile(fmt.Sprintf("/tmp/%d_1", rnd), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
file2.Write([]byte("1 1 2\ntest3"))
file2.Write([]byte(payloadSeparator))
file2.Write([]byte("1 1 4\ntest4"))
file2.Write([]byte(payloadSeparator))
file2.Close()
input := NewFileInput(fmt.Sprintf("/tmp/%d*", rnd), false)
buf := make([]byte, 1000)
for i := '1'; i <= '4'; i++ {
n, _ := input.Read(buf)
if buf[4] != byte(i) {
t.Error("Should emit requests in right order", string(buf[:n]))
}
}
os.Remove(file1.Name())
os.Remove(file2.Name())
}
func TestInputFileRequestsWithLatency(t *testing.T) {
rnd := rand.Int63()
file, _ := os.OpenFile(fmt.Sprintf("/tmp/%d", rnd), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
defer file.Close()
file.Write([]byte("1 1 100000000\nrequest1"))
file.Write([]byte(payloadSeparator))
file.Write([]byte("1 2 150000000\nrequest2"))
file.Write([]byte(payloadSeparator))
file.Write([]byte("1 3 250000000\nrequest3"))
file.Write([]byte(payloadSeparator))
input := NewFileInput(fmt.Sprintf("/tmp/%d", rnd), false)
buf := make([]byte, 1000)
start := time.Now().UnixNano()
for i := 0; i < 3; i++ {
input.Read(buf)
}
end := time.Now().UnixNano()
var expectedLatency int64 = 250000000 - 100000000
realLatency := end - start
if realLatency < expectedLatency {
t.Errorf("Should emit requests respecting latency. Expected: %v, real: %v", expectedLatency, realLatency)
}
if realLatency > expectedLatency+10000000 {
t.Errorf("Should emit requests respecting latency. Expected: %v, real: %v", expectedLatency, realLatency)
}
}
func TestInputFileMultipleFilesWithRequestsAndResponses(t *testing.T) {
rnd := rand.Int63()
file1, _ := os.OpenFile(fmt.Sprintf("/tmp/%d_0", rnd), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
file1.Write([]byte("1 1 1\nrequest1"))
file1.Write([]byte(payloadSeparator))
file1.Write([]byte("2 1 1\nresponse1"))
file1.Write([]byte(payloadSeparator))
file1.Write([]byte("1 2 3\nrequest2"))
file1.Write([]byte(payloadSeparator))
file1.Write([]byte("2 2 3\nresponse2"))
file1.Write([]byte(payloadSeparator))
file1.Close()
file2, _ := os.OpenFile(fmt.Sprintf("/tmp/%d_1", rnd), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
file2.Write([]byte("1 3 2\nrequest3"))
file2.Write([]byte(payloadSeparator))
file2.Write([]byte("2 3 2\nresponse3"))
file2.Write([]byte(payloadSeparator))
file2.Write([]byte("1 4 4\nrequest4"))
file2.Write([]byte(payloadSeparator))
file2.Write([]byte("2 4 4\nresponse4"))
file2.Write([]byte(payloadSeparator))
file2.Close()
input := NewFileInput(fmt.Sprintf("/tmp/%d*", rnd), false)
buf := make([]byte, 1000)
for i := '1'; i <= '4'; i++ {
n, _ := input.Read(buf)
if buf[0] != '1' && buf[4] != byte(i) {
t.Error("Shound emit requests in right order", string(buf[:n]))
}
n, _ = input.Read(buf)
if buf[0] != '2' && buf[4] != byte(i) {
t.Error("Shound emit responses in right order", string(buf[:n]))
}
}
os.Remove(file1.Name())
os.Remove(file2.Name())
}
func TestInputFileLoop(t *testing.T) {
rnd := rand.Int63()
file, _ := os.OpenFile(fmt.Sprintf("/tmp/%d", rnd), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
file.Write([]byte("1 1 1\ntest1"))
file.Write([]byte(payloadSeparator))
file.Write([]byte("1 1 2\ntest2"))
file.Write([]byte(payloadSeparator))
file.Close()
input := NewFileInput(fmt.Sprintf("/tmp/%d", rnd), true)
buf := make([]byte, 1000)
// Even if we have just 2 requests in file, it should indifinitly loop
for i := 0; i < 1000; i++ {
input.Read(buf)
}
input.Close()
os.Remove(file.Name())
}
func TestInputFileCompressed(t *testing.T) {
rnd := rand.Int63()
output := NewFileOutput(fmt.Sprintf("/tmp/%d_0.gz", rnd), &FileOutputConfig{flushInterval: time.Minute, append: true})
for i := 0; i < 1000; i++ {
output.Write([]byte("1 1 1\r\ntest"))
}
name1 := output.file.Name()
output.Close()
output2 := NewFileOutput(fmt.Sprintf("/tmp/%d_1.gz", rnd), &FileOutputConfig{flushInterval: time.Minute, append: true})
for i := 0; i < 1000; i++ {
output2.Write([]byte("1 1 1\r\ntest"))
}
name2 := output2.file.Name()
output2.Close()
input := NewFileInput(fmt.Sprintf("/tmp/%d*", rnd), false)
buf := make([]byte, 1000)
for i := 0; i < 2000; i++ {
input.Read(buf)
}
os.Remove(name1)
os.Remove(name2)
}
type CaptureFile struct {
data [][]byte
file *os.File
}
func NewExpectedCaptureFile(data [][]byte, file *os.File) *CaptureFile {
ecf := new(CaptureFile)
ecf.file = file
ecf.data = data
return ecf
}
func (expectedCaptureFile *CaptureFile) TearDown() {
if expectedCaptureFile.file != nil {
syscall.Unlink(expectedCaptureFile.file.Name())
}
}
type RequestGenerator struct {
inputs []io.Reader
emit func()
wg *sync.WaitGroup
}
func NewRequestGenerator(inputs []io.Reader, emit func(), count int) (rg *RequestGenerator) {
rg = new(RequestGenerator)
rg.inputs = inputs
rg.emit = emit
rg.wg = new(sync.WaitGroup)
rg.wg.Add(count)
return
}
func (expectedCaptureFile *CaptureFile) PayloadsEqual(other [][]byte) bool {
if len(expectedCaptureFile.data) != len(other) {
return false
}
for i, payload := range other {
if !bytes.Equal(expectedCaptureFile.data[i], payload) {
return false
}
}
return true
}
func CreateCaptureFile(requestGenerator *RequestGenerator) *CaptureFile {
f, err := ioutil.TempFile("", "testmainconf")
if err != nil {
panic(err)
}
quit := make(chan int)
readPayloads := [][]byte{}
output := NewTestOutput(func(data []byte) {
readPayloads = append(readPayloads, Duplicate(data))
requestGenerator.wg.Done()
})
outputFile := NewFileOutput(f.Name(), &FileOutputConfig{flushInterval: time.Minute, append: true})
Plugins.Inputs = requestGenerator.inputs
Plugins.Outputs = []io.Writer{output, outputFile}
go Start(quit)
requestGenerator.emit()
requestGenerator.wg.Wait()
time.Sleep(100 * time.Millisecond)
outputFile.Close()
close(quit)
return NewExpectedCaptureFile(readPayloads, f)
}
func ReadFromCaptureFile(captureFile *os.File, count int, callback writeCallback) (err error) {
quit := make(chan int)
wg := new(sync.WaitGroup)
input := NewFileInput(captureFile.Name(), false)
output := NewTestOutput(func(data []byte) {
callback(data)
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
wg.Add(count)
go Start(quit)
done := make(chan int, 1)
go func() {
wg.Wait()
done <- 1
}()
select {
case <-done:
break
case <-time.After(2 * time.Second):
err = errors.New("Timed out")
}
close(quit)
return
}
func Duplicate(data []byte) (duplicate []byte) {
duplicate = make([]byte, len(data))
copy(duplicate, data)
return
}
+76
View File
@@ -0,0 +1,76 @@
package main
import (
"log"
"net"
"net/http"
"net/http/httputil"
"time"
)
// HTTPInput used for sending requests to Gor via http
type HTTPInput struct {
data chan []byte
address string
listener net.Listener
}
// NewHTTPInput constructor for HTTPInput. Accepts address with port which he will listen on.
func NewHTTPInput(address string) (i *HTTPInput) {
i = new(HTTPInput)
i.data = make(chan []byte, 10000)
i.address = address
i.listen(address)
return
}
func (i *HTTPInput) Read(data []byte) (int, error) {
buf := <-i.data
header := payloadHeader(RequestPayload, uuid(), time.Now().UnixNano(), -1)
copy(data[0:len(header)], header)
copy(data[len(header):], buf)
return len(buf) + len(header), nil
}
func (i *HTTPInput) handler(w http.ResponseWriter, r *http.Request) {
r.URL.Scheme = "http"
r.URL.Host = i.listener.Addr().String()
buf, _ := httputil.DumpRequestOut(r, true)
http.Error(w, http.StatusText(200), 200)
select {
case i.data <- buf:
default:
Debug("[INPUT-HTTP] Dropping requests because output can't process them fast enough")
}
}
func (i *HTTPInput) listen(address string) {
var err error
mux := http.NewServeMux()
mux.HandleFunc("/", i.handler)
i.listener, err = net.Listen("tcp", address)
if err != nil {
log.Fatal("HTTP input listener failure:", err)
}
go func() {
err = http.Serve(i.listener, mux)
if err != nil {
log.Fatal("HTTP input serve failure:", err)
}
}()
}
func (i *HTTPInput) String() string {
return "HTTP input: " + i.address
}
+73
View File
@@ -0,0 +1,73 @@
package main
import (
"io"
"log"
"net/http"
"os/exec"
"strings"
"sync"
"testing"
"github.com/buger/goreplay/proto"
)
func TestHTTPInput(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewHTTPInput("127.0.0.1:0")
output := NewTestOutput(func(data []byte) {
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
address := strings.Replace(input.listener.Addr().String(), "[::]", "127.0.0.1", -1)
for i := 0; i < 100; i++ {
wg.Add(1)
http.Get("http://" + address + "/")
}
wg.Wait()
close(quit)
}
func TestInputHTTPLargePayload(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
dd := exec.Command("dd", "if=/dev/urandom", "of=/tmp/large", "bs=1", "count=4000000")
err := dd.Run()
if err != nil {
log.Fatal("dd error:", err)
}
input := NewHTTPInput("127.0.0.1:0")
output := NewTestOutput(func(data []byte) {
if len(proto.Body(payloadBody(data))) != 4000000 {
t.Error("Should receive full file")
}
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
wg.Add(1)
address := strings.Replace(input.listener.Addr().String(), "[::]", "127.0.0.1", -1)
curl := exec.Command("curl", "http://"+address, "--data-binary", "@/tmp/large")
err = curl.Run()
if err != nil {
log.Fatal("curl error:", err)
}
wg.Wait()
close(quit)
}
+107
View File
@@ -0,0 +1,107 @@
package main
import (
"encoding/json"
"log"
"strings"
"github.com/Shopify/sarama"
"github.com/Shopify/sarama/mocks"
)
// KafkaInput is used for recieving Kafka messages and
// transforming them into HTTP payloads.
type KafkaInput struct {
config *KafkaConfig
consumers []sarama.PartitionConsumer
messages chan *sarama.ConsumerMessage
}
// NewKafkaInput creates instance of kafka consumer client.
func NewKafkaInput(address string, config *KafkaConfig) *KafkaInput {
c := sarama.NewConfig()
// Configuration options go here
var con sarama.Consumer
if mock, ok := config.consumer.(*mocks.Consumer); ok && mock != nil {
con = config.consumer
} else {
var err error
//con, err = sarama.NewConsumer([]string{config.host}, c)
con, err = sarama.NewConsumer(strings.Split(config.host, ","), c)
if err != nil {
log.Fatalln("Failed to start Sarama(Kafka) consumer:", err)
}
}
partitions, err := con.Partitions(config.topic)
if err != nil {
log.Fatalln("Failed to collect Sarama(Kafka) partitions:", err)
}
i := &KafkaInput{
config: config,
consumers: make([]sarama.PartitionConsumer, len(partitions)),
messages: make(chan *sarama.ConsumerMessage, 256),
}
for index, partition := range partitions {
consumer, err := con.ConsumePartition(config.topic, partition, sarama.OffsetNewest)
if err != nil {
log.Fatalln("Failed to start Sarama(Kafka) partition consumer:", err)
}
go func(consumer sarama.PartitionConsumer) {
defer consumer.Close()
for message := range consumer.Messages() {
i.messages <- message
}
}(consumer)
if Settings.verbose {
// Start infinite loop for tracking errors for kafka producer.
go i.ErrorHandler(consumer)
}
i.consumers[index] = consumer
}
return i
}
// ErrorHandler should receive errors
func (i *KafkaInput) ErrorHandler(consumer sarama.PartitionConsumer) {
for err := range consumer.Errors() {
log.Println("Failed to read access log entry:", err)
}
}
func (i *KafkaInput) Read(data []byte) (int, error) {
message := <-i.messages
if !i.config.useJSON {
copy(data, message.Value)
return len(message.Value), nil
}
var kafkaMessage KafkaMessage
json.Unmarshal(message.Value, &kafkaMessage)
buf, err := kafkaMessage.Dump()
if err != nil {
log.Println("Failed to decode access log entry:", err)
return 0, err
}
copy(data, buf)
return len(buf), nil
}
func (i *KafkaInput) String() string {
return "Kafka Input: " + i.config.host + "/" + i.config.topic
}
+62
View File
@@ -0,0 +1,62 @@
package main
import (
"testing"
"github.com/Shopify/sarama"
"github.com/Shopify/sarama/mocks"
)
func TestInputKafkaRAW(t *testing.T) {
consumer := mocks.NewConsumer(t, nil)
defer consumer.Close()
consumer.ExpectConsumePartition("test", 0, mocks.AnyOffset).YieldMessage(&sarama.ConsumerMessage{Value: []byte("1 2 3\nGET / HTTP1.1\r\nHeader: 1\r\n\r\n")})
consumer.SetTopicMetadata(
map[string][]int32{"test": {0}},
)
input := NewKafkaInput("", &KafkaConfig{
consumer: consumer,
topic: "test",
useJSON: false,
})
buf := make([]byte, 1024)
n, err := input.Read(buf)
if err != nil {
t.Fatal(err)
}
if string(buf[:n]) != "1 2 3\nGET / HTTP1.1\r\nHeader: 1\r\n\r\n" {
t.Error("Message not properly decoded: ", string(buf[:n]), n)
}
}
func TestInputKafkaJSON(t *testing.T) {
consumer := mocks.NewConsumer(t, nil)
defer consumer.Close()
consumer.ExpectConsumePartition("test", 0, mocks.AnyOffset).YieldMessage(&sarama.ConsumerMessage{Value: []byte(`{"Req_URL":"/","Req_Type":"1","Req_ID":"2","Req_Ts":"3","Req_Method":"GET","Req_Headers":{"Header":"1"}}`)})
consumer.SetTopicMetadata(
map[string][]int32{"test": {0}},
)
input := NewKafkaInput("", &KafkaConfig{
consumer: consumer,
topic: "test",
useJSON: true,
})
buf := make([]byte, 1024)
n, err := input.Read(buf)
if err != nil {
t.Fatal(err)
}
if string(buf[:n]) != "1 2 3\nGET / HTTP/1.1\r\nHeader: 1\r\n\r\n" {
t.Error("Message not properly decoded: ", string(buf[:n]), n)
}
}
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"log"
"net"
"time"
"github.com/buger/goreplay/proto"
raw "github.com/buger/goreplay/raw_socket_listener"
)
// RAWInput used for intercepting traffic for given address
type RAWInput struct {
data chan *raw.TCPMessage
address string
expire time.Duration
quit chan bool
engine int
realIPHeader []byte
trackResponse bool
listener *raw.Listener
bpfFilter string
timestampType string
bufferSize int
}
// Available engines for intercepting traffic
const (
EngineRawSocket = 1 << iota
EnginePcap
EnginePcapFile
)
// NewRAWInput constructor for RAWInput. Accepts address with port as argument.
func NewRAWInput(address string, engine int, trackResponse bool, expire time.Duration, realIPHeader string, bpfFilter string, timestampType string, bufferSize int) (i *RAWInput) {
i = new(RAWInput)
i.data = make(chan *raw.TCPMessage)
i.address = address
i.expire = expire
i.engine = engine
i.bpfFilter = bpfFilter
i.realIPHeader = []byte(realIPHeader)
i.quit = make(chan bool)
i.trackResponse = trackResponse
i.timestampType = timestampType
i.bufferSize = bufferSize
i.listen(address)
i.listener.IsReady()
return
}
func (i *RAWInput) Read(data []byte) (int, error) {
msg := <-i.data
buf := msg.Bytes()
var header []byte
if msg.IsIncoming {
header = payloadHeader(RequestPayload, msg.UUID(), msg.Start.UnixNano(), -1)
if len(i.realIPHeader) > 0 {
buf = proto.SetHeader(buf, i.realIPHeader, []byte(msg.IP().String()))
}
} else {
header = payloadHeader(ResponsePayload, msg.UUID(), msg.Start.UnixNano(), msg.End.UnixNano()-msg.AssocMessage.End.UnixNano())
}
copy(data[0:len(header)], header)
copy(data[len(header):], buf)
return len(buf) + len(header), nil
}
func (i *RAWInput) listen(address string) {
Debug("Listening for traffic on: " + address)
host, port, err := net.SplitHostPort(address)
if err != nil {
log.Fatal("input-raw: error while parsing address", err)
}
i.listener = raw.NewListener(host, port, i.engine, i.trackResponse, i.expire, i.bpfFilter, i.timestampType, i.bufferSize, Settings.inputRAWOverrideSnapLen, Settings.inputRAWImmediateMode)
ch := i.listener.Receiver()
go func() {
for {
select {
case <-i.quit:
return
default:
}
// Receiving TCPMessage object
m := <-ch
i.data <- m
}
}()
}
func (i *RAWInput) String() string {
return "Intercepting traffic from: " + i.address
}
func (i *RAWInput) Close() error {
i.listener.Close()
close(i.quit)
return nil
}
+424
View File
@@ -0,0 +1,424 @@
package main
import (
"bytes"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/buger/goreplay/proto"
)
const testRawExpire = time.Millisecond * 200
func TestRAWInputIPv4(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
listener, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
origin := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
go origin.Serve(listener)
defer listener.Close()
originAddr := listener.Addr().String()
var respCounter, reqCounter int64
input := NewRAWInput(originAddr, EnginePcap, true, testRawExpire, "X-Real-IP", "", "", 0)
defer input.Close()
output := NewTestOutput(func(data []byte) {
if data[0] == '1' {
body := payloadBody(data)
if len(proto.Header(body, []byte("X-Real-IP"))) == 0 {
t.Error("Should have X-Real-IP header", string(body))
}
atomic.AddInt64(&reqCounter, 1)
} else {
atomic.AddInt64(&respCounter, 1)
}
if Settings.debug {
log.Println(reqCounter, respCounter)
}
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
client := NewHTTPClient("http://"+listener.Addr().String(), &HTTPClientConfig{})
go Start(quit)
for i := 0; i < 100; i++ {
// request + response
wg.Add(2)
client.Get("/")
time.Sleep(2 * time.Millisecond)
}
wg.Wait()
close(quit)
}
func TestRAWInputNoKeepAlive(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
listener, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
origin := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("a"))
w.Write([]byte("b"))
}),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
origin.SetKeepAlivesEnabled(false)
go origin.Serve(listener)
defer listener.Close()
originAddr := listener.Addr().String()
input := NewRAWInput(originAddr, EnginePcap, true, testRawExpire, "", "", "", 0)
defer input.Close()
output := NewTestOutput(func(data []byte) {
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
client := NewHTTPClient("http://"+listener.Addr().String(), &HTTPClientConfig{})
go Start(quit)
for i := 0; i < 100; i++ {
// request + response
wg.Add(2)
client.Get("/")
time.Sleep(2 * time.Millisecond)
}
wg.Wait()
close(quit)
}
func TestRAWInputIPv6(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
listener, err := net.Listen("tcp", "[::1]:0")
if err != nil {
t.Fatal(err)
}
origin := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
go origin.Serve(listener)
defer listener.Close()
originAddr := listener.Addr().String()
var respCounter, reqCounter int64
input := NewRAWInput(originAddr, EnginePcap, true, testRawExpire, "", "", "", 0)
defer input.Close()
output := NewTestOutput(func(data []byte) {
if data[0] == '1' {
atomic.AddInt64(&reqCounter, 1)
} else {
atomic.AddInt64(&respCounter, 1)
}
if Settings.debug {
log.Println(reqCounter, respCounter)
}
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
client := NewHTTPClient("http://"+listener.Addr().String(), &HTTPClientConfig{})
go Start(quit)
for i := 0; i < 100; i++ {
// request + response
wg.Add(2)
client.Get("/")
time.Sleep(2 * time.Millisecond)
}
wg.Wait()
close(quit)
}
func TestInputRAW100Expect(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
fileContent, _ := ioutil.ReadFile("COMM-LICENSE")
// Origing and Replay server initialization
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
ioutil.ReadAll(r.Body)
wg.Done()
}))
defer origin.Close()
originAddr := strings.Replace(origin.Listener.Addr().String(), "[::]", "127.0.0.1", -1)
input := NewRAWInput(originAddr, EnginePcap, true, time.Second, "", "", "", 0)
defer input.Close()
// We will use it to get content of raw HTTP request
testOutput := NewTestOutput(func(data []byte) {
switch data[0] {
case RequestPayload:
if strings.Contains(string(data), "Expect: 100-continue") {
t.Error("Should not contain 100-continue header")
}
wg.Done()
case ResponsePayload:
wg.Done()
}
})
replay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if !bytes.Equal(body, fileContent) {
buf, _ := httputil.DumpRequest(r, true)
t.Error("Wrong POST body:", string(buf))
}
wg.Done()
}))
defer replay.Close()
httpOutput := NewHTTPOutput(replay.URL, &HTTPOutputConfig{})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{testOutput, httpOutput}
go Start(quit)
// Origin + Response/Request Test Output + Request Http Output
wg.Add(4)
curl := exec.Command("curl", "http://"+originAddr, "--data-binary", "@COMM-LICENSE")
err := curl.Run()
if err != nil {
log.Fatal(err)
}
wg.Wait()
close(quit)
}
func TestInputRAWChunkedEncoding(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
fileContent, _ := ioutil.ReadFile("README.md")
// Origing and Replay server initialization
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
ioutil.ReadAll(r.Body)
wg.Done()
}))
originAddr := strings.Replace(origin.Listener.Addr().String(), "[::]", "127.0.0.1", -1)
input := NewRAWInput(originAddr, EnginePcap, true, time.Second, "", "", "", 0)
defer input.Close()
replay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if !bytes.Equal(body, fileContent) {
buf, _ := httputil.DumpRequest(r, true)
t.Error("Wrong POST body:", string(buf))
}
wg.Done()
}))
defer replay.Close()
httpOutput := NewHTTPOutput(replay.URL, &HTTPOutputConfig{Debug: true})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{httpOutput}
go Start(quit)
wg.Add(2)
curl := exec.Command("curl", "http://"+originAddr, "--header", "Transfer-Encoding: chunked", "--header", "Expect:", "--data-binary", "@README.md")
err := curl.Run()
if err != nil {
log.Fatal(err)
}
wg.Wait()
close(quit)
}
func TestInputRAWLargePayload(t *testing.T) {
// FIXME: Large payloads does not work for travis for some reason...
if os.Getenv("TRAVIS_BUILD_DIR") != "" {
return
}
wg := new(sync.WaitGroup)
quit := make(chan int)
sizeB := 100 * 1000
// Generate 100kb file
dd := exec.Command("dd", "if=/dev/urandom", "of=/tmp/large", "bs=1", "count="+strconv.Itoa(sizeB))
err := dd.Run()
if err != nil {
log.Fatal("dd error:", err)
}
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
body, _ := ioutil.ReadAll(req.Body)
if len(body) != sizeB {
t.Error("File size should be 1mb:", len(body))
}
wg.Done()
}))
originAddr := strings.Replace(origin.Listener.Addr().String(), "[::]", "127.0.0.1", -1)
input := NewRAWInput(originAddr, EnginePcap, true, testRawExpire, "", "", "", 0)
defer input.Close()
replay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
body, _ := ioutil.ReadAll(req.Body)
// // req.Body = http.MaxBytesReader(w, req.Body, 1*1024*1024)
// // buf := make([]byte, 1*1024*1024)
// n, _ := req.Body.Read(buf)
// body := buf[0:n]
if len(body) != sizeB {
t.Errorf("File size should be %d bytes: %d", sizeB, len(body))
}
wg.Done()
}))
defer replay.Close()
httpOutput := NewHTTPOutput(replay.URL, &HTTPOutputConfig{Debug: false})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{httpOutput}
go Start(quit)
wg.Add(2)
curl := exec.Command("curl", "http://"+originAddr, "--header", "Transfer-Encoding: chunked", "--header", "Expect:", "--data-binary", "@/tmp/large")
err = curl.Run()
if err != nil {
log.Fatal("curl error:", err)
}
wg.Wait()
close(quit)
}
func BenchmarkRAWInput(b *testing.B) {
quit := make(chan int)
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
defer origin.Close()
originAddr := strings.Replace(origin.Listener.Addr().String(), "[::]", "127.0.0.1", -1)
var respCounter, reqCounter int64
input := NewRAWInput(originAddr, EnginePcap, true, testRawExpire, "", "", "", 0)
defer input.Close()
output := NewTestOutput(func(data []byte) {
if data[0] == '1' {
atomic.AddInt64(&reqCounter, 1)
} else {
atomic.AddInt64(&respCounter, 1)
}
// log.Println("Captured ", reqCounter, "requests and ", respCounter, " responses")
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
emitted := 0
fileContent, _ := ioutil.ReadFile("LICENSE.txt")
for i := 0; i < b.N; i++ {
wg := new(sync.WaitGroup)
wg.Add(10 * 100)
emitted += 10 * 100
for w := 0; w < 100; w++ {
go func() {
client := NewHTTPClient(origin.URL, &HTTPClientConfig{})
for i := 0; i < 10; i++ {
if rand.Int63n(2) == 0 {
client.Post("/", fileContent)
} else {
client.Get("/")
}
time.Sleep(time.Duration(rand.Int63n(50)) * time.Millisecond)
wg.Done()
}
}()
}
wg.Wait()
}
time.Sleep(400 * time.Millisecond)
log.Println("Emitted ", emitted, ", Captured ", reqCounter, "requests and ", respCounter, " responses")
close(quit)
}
+117
View File
@@ -0,0 +1,117 @@
package main
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"io"
"log"
"net"
"os"
)
// TCPInput used for internal communication
type TCPInput struct {
data chan []byte
listener net.Listener
address string
config *TCPInputConfig
}
type TCPInputConfig struct {
secure bool
certificatePath string
keyPath string
}
// NewTCPInput constructor for TCPInput, accepts address with port
func NewTCPInput(address string, config *TCPInputConfig) (i *TCPInput) {
i = new(TCPInput)
i.data = make(chan []byte, 1000)
i.address = address
i.config = config
i.listen(address)
return
}
func (i *TCPInput) Read(data []byte) (int, error) {
buf := <-i.data
copy(data, buf)
return len(buf), nil
}
func (i *TCPInput) listen(address string) {
if i.config.secure {
cer, err := tls.LoadX509KeyPair(i.config.certificatePath, i.config.keyPath)
if err != nil {
log.Fatal("Error while loading --input-file certificate:", err)
}
config := &tls.Config{Certificates: []tls.Certificate{cer}}
listener, err := tls.Listen("tcp", address, config)
if err != nil {
log.Fatal("Can't start --input-tcp with secure connection:", err)
}
i.listener = listener
} else {
listener, err := net.Listen("tcp", address)
if err != nil {
log.Fatal("Can't start:", err)
}
i.listener = listener
}
go func() {
for {
conn, err := i.listener.Accept()
if err != nil {
log.Println("Error while Accept()", err)
continue
}
go i.handleConnection(conn)
}
}()
}
func (i *TCPInput) handleConnection(conn net.Conn) {
defer conn.Close()
payloadSeparatorAsBytes := []byte(payloadSeparator)
reader := bufio.NewReader(conn)
var buffer bytes.Buffer
for {
line, err := reader.ReadBytes('\n')
if err != nil {
if err != io.EOF {
fmt.Fprintln(os.Stderr, "Unexpected error in input tcp connection:", err)
}
break
}
if bytes.Equal(payloadSeparatorAsBytes[1:], line) {
asBytes := buffer.Bytes()
buffer.Reset()
newBuf := make([]byte, len(asBytes)-1)
copy(newBuf, asBytes)
i.data <- newBuf
} else {
buffer.Write(line)
}
}
}
func (i *TCPInput) String() string {
return "TCP input: " + i.address
}
+136
View File
@@ -0,0 +1,136 @@
package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"io"
"io/ioutil"
"log"
"math/big"
"net"
"os"
"sync"
"testing"
"time"
)
func TestTCPInput(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTCPInput("127.0.0.1:0", &TCPInputConfig{})
output := NewTestOutput(func(data []byte) {
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
tcpAddr, err := net.ResolveTCPAddr("tcp", input.listener.Addr().String())
if err != nil {
log.Fatal(err)
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
log.Fatal(err)
}
msg := []byte("1 1 1\nGET / HTTP/1.1\r\n\r\n")
for i := 0; i < 100; i++ {
wg.Add(1)
conn.Write(msg)
conn.Write([]byte(payloadSeparator))
}
wg.Wait()
close(quit)
}
func genCertificate(template *x509.Certificate) ([]byte, []byte) {
priv, _ := rsa.GenerateKey(rand.Reader, 2048)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)
template.SerialNumber = serialNumber
template.BasicConstraintsValid = true
template.NotBefore = time.Now()
template.NotAfter = time.Now().Add(time.Hour)
derBytes, _ := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
var certPem, keyPem bytes.Buffer
pem.Encode(&certPem, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
pem.Encode(&keyPem, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
return certPem.Bytes(), keyPem.Bytes()
}
func TestTCPInputSecure(t *testing.T) {
serverCertPem, serverPrivPem := genCertificate(&x509.Certificate{
DNSNames: []string{"localhost"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::")},
})
serverCertPemFile, _ := ioutil.TempFile("", "server.crt")
serverCertPemFile.Write(serverCertPem)
serverCertPemFile.Close()
serverPrivPemFile, _ := ioutil.TempFile("", "server.key")
serverPrivPemFile.Write(serverPrivPem)
serverPrivPemFile.Close()
defer func() {
os.Remove(serverPrivPemFile.Name())
os.Remove(serverCertPemFile.Name())
}()
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTCPInput("127.0.0.1:0", &TCPInputConfig{
secure: true,
certificatePath: serverCertPemFile.Name(),
keyPath: serverPrivPemFile.Name(),
})
output := NewTestOutput(func(data []byte) {
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
conf := &tls.Config{
InsecureSkipVerify: true,
}
conn, err := tls.Dial("tcp", input.listener.Addr().String(), conf)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
msg := []byte("1 1 1\nGET / HTTP/1.1\r\n\r\n")
for i := 0; i < 100; i++ {
wg.Add(1)
conn.Write(msg)
conn.Write([]byte(payloadSeparator))
}
wg.Wait()
close(quit)
}
+51
View File
@@ -0,0 +1,51 @@
package main
import (
"bytes"
"fmt"
"github.com/buger/goreplay/proto"
"github.com/Shopify/sarama"
)
// KafkaConfig should contains required information to
// build producers.
type KafkaConfig struct {
host string
topic string
producer sarama.AsyncProducer
consumer sarama.Consumer
useJSON bool
}
// KafkaMessage should contains catched request information that should be
// passed as Json to Apache Kafka.
type KafkaMessage struct {
ReqURL string `json:"Req_URL"`
ReqType string `json:"Req_Type"`
ReqID string `json:"Req_ID"`
ReqTs string `json:"Req_Ts"`
ReqMethod string `json:"Req_Method"`
ReqBody string `json:"Req_Body,omitempty"`
ReqHeaders map[string]string `json:"Req_Headers,omitempty"`
}
// Dump returns the given request in its HTTP/1.x wire
// representation.
func (m KafkaMessage) Dump() ([]byte, error) {
var b bytes.Buffer
b.WriteString(fmt.Sprintf("%s %s %s\n", m.ReqType, m.ReqID, m.ReqTs))
b.WriteString(fmt.Sprintf("%s %s HTTP/1.1", m.ReqMethod, m.ReqURL))
b.Write(proto.CLRF)
for key, value := range m.ReqHeaders {
b.WriteString(fmt.Sprintf("%s: %s", key, value))
b.Write(proto.CLRF)
}
b.Write(proto.CLRF)
b.WriteString(m.ReqBody)
return b.Bytes(), nil
}
+100
View File
@@ -0,0 +1,100 @@
package main
import (
"fmt"
"io"
"math/rand"
"strconv"
"strings"
"time"
)
// Limiter is a wrapper for input or output plugin which adds rate limiting
type Limiter struct {
plugin interface{}
limit int
isPercent bool
currentRPS int
currentTime int64
}
func parseLimitOptions(options string) (limit int, isPercent bool) {
if strings.Contains(options, "%") {
limit, _ = strconv.Atoi(strings.Split(options, "%")[0])
isPercent = true
} else {
limit, _ = strconv.Atoi(options)
isPercent = false
}
return
}
// NewLimiter constructor for Limiter, accepts plugin and options
// `options` allow to sprcify relatve or absolute limiting
func NewLimiter(plugin interface{}, options string) io.ReadWriter {
l := new(Limiter)
l.limit, l.isPercent = parseLimitOptions(options)
l.plugin = plugin
l.currentTime = time.Now().UnixNano()
// FileInput have its own rate limiting. Unlike other inputs we not just dropping requests, we can slow down or speed up request emittion.
if fi, ok := l.plugin.(*FileInput); ok && l.isPercent {
fi.speedFactor = float64(l.limit) / float64(100)
}
return l
}
func (l *Limiter) isLimited() bool {
// File input have its own limiting algorithm
if _, ok := l.plugin.(*FileInput); ok && l.isPercent {
return false
}
if l.isPercent {
return l.limit <= rand.Intn(100)
}
if (time.Now().UnixNano() - l.currentTime) > time.Second.Nanoseconds() {
l.currentTime = time.Now().UnixNano()
l.currentRPS = 0
}
if l.currentRPS >= l.limit {
return true
}
l.currentRPS++
return false
}
func (l *Limiter) Write(data []byte) (n int, err error) {
if l.isLimited() {
return 0, nil
}
n, err = l.plugin.(io.Writer).Write(data)
return
}
func (l *Limiter) Read(data []byte) (n int, err error) {
if r, ok := l.plugin.(io.Reader); ok {
n, err = r.Read(data)
} else {
return 0, nil
}
if l.isLimited() {
return 0, nil
}
return
}
func (l *Limiter) String() string {
return fmt.Sprintf("Limiting %s to: %d (isPercent: %v)", l.plugin, l.limit, l.isPercent)
}
+106
View File
@@ -0,0 +1,106 @@
// +build !race
package main
import (
"io"
"sync"
"testing"
)
func TestOutputLimiter(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
output := NewLimiter(NewTestOutput(func(data []byte) {
wg.Done()
}), "10")
wg.Add(10)
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
for i := 0; i < 100; i++ {
input.EmitGET()
}
wg.Wait()
close(quit)
}
func TestInputLimiter(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewLimiter(NewTestInput(), "10")
output := NewTestOutput(func(data []byte) {
wg.Done()
})
wg.Add(10)
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
for i := 0; i < 100; i++ {
input.(*Limiter).plugin.(*TestInput).EmitGET()
}
wg.Wait()
close(quit)
}
// Should limit all requests
func TestPercentLimiter1(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
output := NewLimiter(NewTestOutput(func(data []byte) {
wg.Done()
}), "0%")
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
for i := 0; i < 100; i++ {
input.EmitGET()
}
wg.Wait()
close(quit)
}
// Should not limit at all
func TestPercentLimiter2(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
output := NewLimiter(NewTestOutput(func(data []byte) {
wg.Done()
}), "100%")
wg.Add(100)
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
for i := 0; i < 100; i++ {
input.EmitGET()
}
wg.Wait()
close(quit)
}
-159
View File
@@ -1,159 +0,0 @@
// Listener capture TCP traffic right from given port using `tcpdump` utility.
// Note: it requires sudo or root access.
//
// Rigt now it suport only HTTP, and only GET requests.
package listener
import (
"bufio"
"bytes"
"encoding/gob"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"regexp"
"strings"
)
type HttpRequest struct {
Tag string // Not used yet
Method string // Right now only 'GET'
Url string // Request URL
Headers map[string]string // Request Headers
}
// Enable debug logging only if "--verbose" flag passed
func Debug(v ...interface{}) {
if Settings.verbose { log.Println(v...) }
}
// Parse `tcpdump` output to find HTTP GET requests
// When HttpRequest found it get send to `requests` channel
func parseRequest(pipe io.ReadCloser, requests chan *HttpRequest) {
request_re := regexp.MustCompile("(GET) (/.*) HTTP/1.1")
headers_re := regexp.MustCompile("([^ ]*): (.*)")
reader := bufio.NewScanner(pipe)
var request *HttpRequest
var requestStarted = false
for reader.Scan() {
line := reader.Text()
// HTTP/1.1 match finds both requests and response
// Index is used instead of Regexp just for speed
if strings.Index(line, "HTTP/1.1") != -1 {
// Allow only requests
match := request_re.FindAllString(line, -1)
if len(match) > 0 {
info := strings.Split(match[0], " ")
request = &HttpRequest{
Method: info[0],
Url: info[1],
Headers: make(map[string]string),
}
requestStarted = true
}
}
if requestStarted {
// We assume that empty line is end of request info
// This is true only for GET requests
if line == "" {
requests <- request
requestStarted = false
} else {
// All headers comes in this format:
//
// User-Agent: Mozilla
// Content-Type: text/html
//
match := headers_re.FindAllString(line, -1)
if len(match) > 0 {
header := strings.Split(match[0], ": ")
request.Headers[header[0]] = header[1]
}
}
}
}
}
// Sends request to replay server via UDP
// Before sending it encode request object using standard gob encoder
func forwardRequest(requests chan *HttpRequest) {
serverAddr, err := net.ResolveUDPAddr("udp4", Settings.ReplayServer())
conn, err := net.DialUDP("udp", nil, serverAddr)
defer conn.Close()
if err != nil {
log.Fatal("Connection error", err)
}
for {
select {
case request := <-requests:
Debug("Forwarding:", request.Url, "to", Settings.ReplayServer())
msg := bytes.Buffer{}
enc := gob.NewEncoder(&msg)
err := enc.Encode(request)
conn.Write(msg.Bytes())
if err != nil {
log.Println("encode error:", err)
}
}
}
}
func greeting() {
fmt.Println("Listening for HTTP traffic on", Settings.port, "port")
fmt.Println("Running: tcpdump "+strings.Join(Settings.TCPDumpConfig()," "))
fmt.Println("Forwarding requests to replay server:", Settings.ReplayServer())
}
// Because its sub-program, Run acts as `main`
func Run() {
if os.Getuid() != 0 {
fmt.Println("Please start the listener as root or sudo!")
fmt.Println("This is required since listener sniff traffic on given port.")
os.Exit(1)
}
// TODO: use RAW_SOCKETS instead of tcpdump
cmd := exec.Command("tcpdump", Settings.TCPDumpConfig()...)
greeting()
stdout, _ := cmd.StdoutPipe()
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
requests := make(chan *HttpRequest)
go parseRequest(stdout, requests)
go forwardRequest(requests)
if err := cmd.Wait(); err != nil {
flag.Usage()
}
}
-54
View File
@@ -1,54 +0,0 @@
package listener
import (
"strconv"
"strings"
"flag"
"os"
)
const (
defaultPort = 80
defaultNetworkInterface = "any"
defaultReplayAddress = "localhost:28020"
)
type ListenerSettings struct {
networkInterface string
port int
replayAddress string
verbose bool
}
var Settings ListenerSettings = ListenerSettings{}
func (s *ListenerSettings) ReplayServer() string {
if !strings.Contains(s.replayAddress, ":") {
return s.replayAddress + ":28020"
}
return s.replayAddress
}
// tcpdump -vv -A -i all port 8080
func (s *ListenerSettings) TCPDumpConfig() []string {
return []string{"-vv", "-A", "-i", Settings.networkInterface, "port "+strconv.Itoa(Settings.port)}
}
func init() {
if len(os.Args) < 2 || os.Args[1] != "listen" {
return
}
flag.IntVar(&Settings.port, "p", defaultPort, "Specify the http server port whose traffic you want to capture")
flag.StringVar(&Settings.networkInterface, "i", defaultNetworkInterface, "By default it try to listen on all network interfaces.To get list of interfaces run `ifconfig`")
flag.StringVar(&Settings.replayAddress, "r", defaultReplayAddress, "Address of replay server.")
flag.BoolVar(&Settings.verbose, "verbose", false, "Log requests")
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"bufio"
"encoding/hex"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"sync"
)
type Middleware struct {
command string
data chan []byte
mu sync.Mutex
Stdin io.Writer
Stdout io.Reader
}
func NewMiddleware(command string) *Middleware {
m := new(Middleware)
m.command = command
m.data = make(chan []byte, 1000)
commands := strings.Split(command, " ")
cmd := exec.Command(commands[0], commands[1:]...)
m.Stdout, _ = cmd.StdoutPipe()
m.Stdin, _ = cmd.StdinPipe()
cmd.Stderr = os.Stderr
go m.read(m.Stdout)
go func() {
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
err = cmd.Wait()
if err != nil {
log.Fatal(err)
}
}()
return m
}
func (m *Middleware) ReadFrom(plugin io.Reader) {
Debug("[MIDDLEWARE-MASTER] Starting reading from", plugin)
go m.copy(m.Stdin, plugin)
}
func (m *Middleware) copy(to io.Writer, from io.Reader) {
buf := make([]byte, 5*1024*1024)
dst := make([]byte, len(buf)*4)
for {
nr, _ := from.Read(buf)
if nr == 0 || nr > len(buf) {
continue
}
payload := buf[0:nr]
if Settings.prettifyHTTP {
payload = prettifyHTTP(payload)
nr = len(payload)
if nr*2 > len(dst) {
continue
}
}
if Settings.prettifyHTTP {
payload = prettifyHTTP(payload)
nr = len(payload)
}
hex.Encode(dst, payload)
dst[nr*2] = '\n'
m.mu.Lock()
to.Write(dst[0 : nr*2+1])
m.mu.Unlock()
if Settings.debug {
Debug("[MIDDLEWARE-MASTER] Sending:", string(buf[0:nr]), "From:", from)
}
}
}
func (m *Middleware) read(from io.Reader) {
reader := bufio.NewReader(from)
var line []byte
var e error
for {
if line, e = reader.ReadBytes('\n'); e != nil {
if e == io.EOF {
continue
} else {
break
}
}
buf := make([]byte, len(line)/2)
if _, err := hex.Decode(buf, line[:len(line)-1]); err != nil {
fmt.Fprintln(os.Stderr, "Failed to decode input payload", err, len(line))
}
if Settings.debug {
Debug("[MIDDLEWARE-MASTER] Received:", string(buf))
}
m.data <- buf
}
return
}
func (m *Middleware) Read(data []byte) (int, error) {
buf := <-m.data
copy(data, buf)
return len(buf), nil
}
func (m *Middleware) String() string {
return fmt.Sprintf("Modifying traffic using '%s' command", m.command)
}
+122
View File
@@ -0,0 +1,122 @@
# GoReplay middleware
GoReplay support protocol for writing middleware in any language, which allows you to implement custom logic like authentification or complex rewriting and filterting. See protocol description here: https://github.com/buger/goreplay/wiki/Middleware, but the basic idea that middleware process receive hex encoded data via STDIN and emits it back via STDOUT. STDERR for loggin inside middleware. Yes, that's simple.
To simplify middleware creation we provide packages for NodeJS and Go (upcoming).
If you want to get access to original and replayed responses, do not forget adding `--output-http-track-respose` and `--input-raw-track-response` options.
## NodeJS
Before starting, you should install the package via npm: `npm install goreplay_middleware`.
And initialize middleware the following way:
```javascript
var gor = require("goreplay_middleware");
// `init` will initialize STDIN listener
gor.init();
```
Basic idea is that you write callbacks which respond to `request`, `response`, `replay`, or `message` events, which contain request meta information and actuall http paylod. Depending on your needs you may compare, override or filter incoming requests and responses.
You can respond to the incoming events using `on` function, by providing callbacks:
```javascript
// valid events are `request`, `response` (original response), `replay` (replayed response), and `message` (all events)
gor.on('request', function(data) {
// `data` contains incoming message its meta information.
data
// Raw HTTP payload of `Buffer` type
// Example (hidden character for line endings shown on purpose):
// GET / HTTP/1.1\r\n
// User-Agent: Golang\r\n
// \r\n
data.http
// Meta is an array size of 4, containing:
// 1. request type - 1, 2 or 3 (which maps to `request`, `respose` and `replay`)
// 2. uuid - request unique identifier. Request responses have the same ID as their request.
// 3. timestamp of when request was made (for responses it is time of request start too)
// 4. latency - time difference between request start and finish. For `request` is zero.
data.meta
// Unique request ID. It should be same for `request`, `response` and `replay` events of the same request.
data.ID
// You should return data at the end of function, even if you not changed request, if you do not want to filter it out.
// If you just `return` nothing, request will be filtered
return data
})
```
### Mapping requests and responses
You can provide request ID as additional argument to `on` function, which allow you to map related requests and responses. Below is example of middleware which checks that original and replayed response have same HTTP status code.
```javascript
// Example of very basic way to compare if replayed traffic have no errors
gor.on("request", function(req) {
gor.on("response", req.ID, function(resp) {
gor.on("replay", req.ID, function(repl) {
if (gor.httpStatus(resp.http) != gor.httpStatus(repl.http)) {
// Note that STDERR is used for logging, and it actually will be send to `Gor` STDOUT.
// This trick is used because SDTIN and STDOUT already used for process communication.
// You can write logger that writes to files insead.
console.error(`${gor.httpPath(req.http)} STATUS NOT MATCH: 'Expected ${gor.httpStatus(resp.http)}' got '${gor.httpStatus(repl.http)}'`)
}
return repl;
})
return resp;
})
return req
})
```
This middleware includes `searchResponses` helper which is used to compare value of original response with the replayed response. If authentication system or xsrf protection returns unique tokens in headers or the response, it will be helpful to rewrite your requests based on them. Because tokens are unique, and the value contained in original and replayed responses will be different. So, you need to extract value from both responses, and rewrite requests based on those mappings.
`searchResponses` accepts request id, regexp pattern for searching the compared value (should include capture group), and callback which returns both original and replayed matched value.
Example:
```javascript
// Compare HTTP headers for response and replayed response, and map values
let tokMap = {};
gor.on("request", function(req) {
let tok = gor.httpHeader(req.http, "Auth-Token");
if (tok && tokMap[tok]) {
req.http = gor.setHttpHeader(req.http, "Auth-Token", tokMap[tok])
}
gor.searchResponses(req.ID, "X-Set-Token: (\w+)$", function(respTok, replTok) {
if (respTok && replTok) tokMap[respTok] = replTok;
})
return req;
})
```
### API documentation
Package expose following functions to process raw HTTP payloads:
* `init` - initialize middleware object, start reading from STDIN.
* `httpPath` - URL path of the request: `gor.httpPath(req.http)`
* `httpMethod` - Http method: 'GET', 'POST', etc. `gor.httpMethod(req.http)`.
* `setHttpPath` - update URL path: `req.http = gor.setHttpPath(req.http, newPath)`
* `httpPathParam` - get param from URL path: `gor.httpPathParam(req.http, queryParam)`
* `setHttpPathParam` - set URL param: `req.http = gor.setHttpPathParam(req.http, queryParam, value)`
* `httpStatus` - response status code
* `httpHeaders` - get all headers: `gor.httpHeaders(req.http)`
* `httpHeader` - get HTTP header: `gor.httpHeader(req.http, "Content-Length")`
* `setHttpHeader` - Set HTTP header, returns modified payload: `req.http = gor.setHttpHeader(req.http, "X-Replayed", "1")`
* `httpBody` - get HTTP Body: `gor.httpBody(req.http)`
* `setHttpBody` - Set HTTP Body and ensures that `Content-Length` header have proper value. Returns modified payload: `req.http = gor.setHttpBody(req.http, Buffer.from('hello!'))`.
* `httpBodyParam` - get POST body param: `gor.httpBodyParam(req.http, param)`
* `setHttpBodyParam` - set POST body param: `req.http = gor.setHttpBodyParam(req.http, param, value)`
* `httpCookie` - get HTTP cookie: `gor.httpCookie(req.http, "SESSSION_ID")`
* `setHttpCookie` - set HTTP cookie, returns modified payload: `req.http = gor.setHttpCookie(req.http, "iam", "cuckoo")`
* `deleteHttpCookie` - delete HTTP cookie, returns modified payload: `req.http = gor.deleteHttpCookie(req.http, "iam")`
Also it is totally legit to use standard `Buffer` functions like `indexOf` for processing the HTTP payload. Just do not forget that if you modify the body, update the `Content-Length` header with a new value. And if you modify any of the headers, line endings should be `\r\n`. Rest is up to your imagination.
## Support
Feel free to ask questions here and by sending email to [support@goreplay.org](mailto:support@goreplay.org). Commercial support is available and welcomed 🙈.
+779
View File
@@ -0,0 +1,779 @@
// ======= GoReplay Middleware helper =============
// Created by Leonid Bugaev in 2017
//
// For questions use GitHub or support@goreplay.org
//
// GoReplay: https://github.com/buger/goreplay
// Middleware package: https://github.com/buger/goreplay/middleware
var middleware;
function init() {
var proxy = {
ch: {},
on: function(chan, id, cb) {
if (!cb && id) {
cb = id;
} else if (cb && id) {
chan = chan + "#" + id;
}
if (!proxy.ch[chan]) {
proxy.ch[chan] = [];
}
proxy.ch[chan].push({
created: new Date(),
cb: cb
});
return proxy;
},
emit: function(msg, raw) {
var chanPrefix;
switch(msg.type) {
case "1": chanPrefix = "request"; break;
case "2": chanPrefix = "response"; break;
case "3": chanPrefix = "replay"; break;
}
let resp = msg;
["message", chanPrefix, chanPrefix + "#" + msg.ID].forEach(function(chanID, idx){
if (proxy.ch[chanID]) {
proxy.ch[chanID].forEach(function(ch){
let r = ch.cb(msg);
if (resp) resp = r; // If one of callback decided not to send response back, do not override it in global callbacks
})
// Cleanup Individual message channels to avoid memory leaks
if (idx == 2) {
delete proxy.ch[chanID]
}
}
})
if (resp) {
process.stdout.write(`${resp.rawMeta.toString('hex')}${Buffer.from("\n").toString("hex")}${resp.http.toString('hex')}\n`)
}
return resp
}
}
// Clean up old messaged ID specific channels if they are older then 60s
let gc = function(gcTime){
let now = new Date();
for (k in proxy.ch) {
if (k.indexOf("#") == -1) continue;
proxy.ch[k] = proxy.ch[k].filter(function(ch){
return (now - ch.created) < gcTime
})
if (proxy.ch[k].length == 0) {
delete proxy.ch[k]
}
}
}
proxy.gc = gc
setInterval(function(){
gc(10 * 1000)
}, 1000);
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin
});
rl.on('line', function(line) {
let msg = parseMessage(line)
if (msg) {
proxy.emit(msg, line)
}
});
middleware = proxy;
return proxy;
}
function parseMessage(msg) {
try {
let payload = Buffer.from(msg, "hex");
let metaPos = payload.indexOf("\n");
let meta = payload.slice(0, metaPos);
let metaArr = meta.toString("ascii").split(" ");
let pType = metaArr[0];
let pID = metaArr[1];
let raw = payload.slice(metaPos + 1, payload.length);
return {
type: pType,
ID: pID,
rawMeta: meta,
meta: metaArr,
http: raw
}
} catch(e) {
fail(`Error while parsing incoming request: ${msg}`)
}
}
// Used to compare values from original and replayed responses
// Accepts request id, regexp pattern for searching the compared value (should include capture group), and callback which returns both original and replayed matched value.
// Example:
//
// // Compare HTTP headers for response and replayed response, and map values
// let tokMap = {};
//
// gor.on("request", function(req) {
// let tok = gor.httpHeader(req.http, "Auth-Token");
// if (tok && tokMap[tok]) {
// req.http = gor.setHttpHeader(req.http, "Auth-Token", tokMap[tok])
// }
//
// gor.searchResponses(req.ID, "X-Set-Token: (\w+)$", function(respTok, replTok) {
// tokMap[respTok] = replTok;
// })
//
// return req;
// })
//
function searchResponses(id, searchPattern, callback) {
let re = new RegExp(searchPattern);
// Using regexp require converting buffer to string
// Before converting to string we can use initial `Buffer.indexOf` check
let indexPattern = searchPattern.split("(")[0];
if (!indexPattern) {
console.error("Search regexp should include capture group, pointing to the value: `prefix-(.*)`")
return
}
middleware.on("response", id, function(resp){
if (resp.http.indexOf(indexPattern) == -1) {
callback()
return resp
}
let respMatch = resp.http.toString('utf-8').match(re);
if (!respMatch) {
callback()
return resp
}
middleware.on("replay", id, function(repl) {
if (repl.http.indexOf(indexPattern) == -1) {
callback(respMatch[1]);
return repl;
}
let replMatch = repl.http.toString('utf-8').match(re);
if (!replMatch) {
callback(respMatch[1]);
return repl;
}
callback(respMatch[1], replMatch[1]);
return repl;
})
return resp;
})
}
// =========== HTTP parsing =================
// Example HTTP payload record (including hidden characters):
//
// POST / HTTP/1.1\r\n
// User-Agent: Node\r\n
// Content-Length: 5\r\n
// \r\n
// hello
function httpMethod(payload) {
var pEnd = payload.indexOf(' ');
return payload.slice(0, pEnd).toString("ascii");
}
function httpPath(payload) {
var pStart = payload.indexOf(' ') + 1;
var pEnd = payload.indexOf(' ', pStart);
return payload.slice(pStart, pEnd).toString("ascii");
}
function setHttpPath(payload, newPath) {
var pStart = payload.indexOf(' ') + 1;
var pEnd = payload.indexOf(' ', pStart);
return Buffer.concat([payload.slice(0, pStart), Buffer.from(newPath), payload.slice(pEnd, payload.length)])
}
function httpPathParam(payload, name) {
let path = httpPath(payload);
let re = new RegExp(name + "=([^&$]+)");
let match = path.match(re);
if (match) return decodeURI(match[1]);
}
function setHttpPathParam(payload, name, value) {
let path = httpPath(payload);
let re = new RegExp(name + "=([^&$]+)");
let newPath = path.replace(re, name + "=" + encodeURI(value));
// If we should add new param instead
if (newPath == path) {
if (newPath.indexOf("?") == -1) {
newPath += "?"
} else {
newPath += "&"
}
newPath += name + "=" + encodeURI(value);
}
return setHttpPath(payload, newPath)
}
// HTTP response have status code in same position as `path` for requests
function httpStatus(payload) {
return httpPath(payload);
}
function setHttpStatus(payload, newStatus) {
return setHttpPath(payload, newStatus);
}
function httpHeaders(payload) {
var httpHeaderString = payload.slice(0,payload.indexOf("\r\n\r\n") + 4).toString().split("\n").slice(1);
var headers = {};
for (var item in httpHeaderString) {
var parts = httpHeaderString[item].split(":");
if (parts.length > 1) {
headers[parts[0]] = parts.slice(1).join(":").trim();
}
}
return headers;
}
function httpHeader(payload, name) {
var currentLine = 0;
var i = 0;
var header = { start: -1, end: -1, valueStart: -1 }
var nameBuf = Buffer.from(name);
var nameBufLower = Buffer.from(name.toLowerCase());
while(c = payload[i]) {
if (c == 13) { // new line "\n"
currentLine++;
i++
header.end = i
if (currentLine > 0 && header.start > 0 && header.valueStart > 0) {
if (nameBuf.compare(payload, header.start, header.valueStart - 1) == 0 ||
nameBufLower.compare(payload, header.start, header.valueStart - 1) == 0) { // ensure that headers are not case sensitive
header.value = payload.slice(header.valueStart, header.end - 1).toString("utf-8").trim();
header.name = payload.slice(header.start, header.valueStart - 1).toString("utf-8");
return header
}
}
header.start = -1
header.valueStart = -1
continue;
} else if (c == 10) { // "\r"
i++
continue;
} else if (c == 58) { // ":" Header/value separator symbol
if (header.valueStart == -1) {
header.valueStart = i + 1;
i++
continue;
}
}
if (header.start == -1) header.start = i;
i++
}
return
}
function setHttpHeader(payload, name, value) {
let header = httpHeader(payload, name);
if (!header) {
let headerStart = payload.indexOf(13) + 1;
return Buffer.concat([payload.slice(0, headerStart + 1), Buffer.from(name + ": " + value + "\r\n"), payload.slice(headerStart + 1, payload.length)])
} else {
return Buffer.concat([payload.slice(0, header.valueStart), Buffer.from(" " + value + "\r\n"), payload.slice(header.end + 1, payload.length)])
}
}
function deleteHttpHeader(payload, name) {
let header = httpHeader(payload, name);
if (header) {
return Buffer.concat([payload.slice(0, header.start), payload.slice(header.end+1, payload.length)])
}
return payload
}
function httpBody(payload) {
return payload.slice(payload.indexOf("\r\n\r\n") + 4, payload.length);
}
function setHttpBody(payload, newBody) {
let p = setHttpHeader(payload, "Content-Length", newBody.length)
let headerEnd = p.indexOf("\r\n\r\n") + 4;
return Buffer.concat([p.slice(0, headerEnd), newBody])
}
function httpBodyParam(payload, name) {
let body = httpBody(payload);
let re = new RegExp(name + "=([^&$]+)");
if (body.indexOf(name + "=") != -1) {
let param = body.toString('utf-8').match(re);
if (param) {
return decodeURI(param[1]);
}
}
}
function setHttpBodyParam(payload, name, value) {
let body = httpBody(payload);
let re = new RegExp(name + "=([^&$]+)");
let newBody = body.toString('utf-8');
if (newBody.indexOf(name + "=") != -1 ) {
newBody = newBody.replace(re, name + "=" + encodeURI(value));
} else {
if (newBody.indexOf("=") != -1) {
newBody += "&";
}
newBody += name + "=" + value;
}
return setHttpBody(payload, Buffer.from(newBody));
}
function setHttpCookie(payload, name, value) {
let h = httpHeader(payload, "Cookie");
let cookie = h ? h.value : "";
let cookies = cookie.split("; ").filter(function(v){ return v.indexOf(name + "=") != 0 })
cookies.push(name + "=" + value)
return setHttpHeader(payload, "Cookie", cookies.join("; "))
}
function deleteHttpCookie(payload, name) {
let h = httpHeader(payload, "Cookie");
let cookie = h ? h.value : "";
let cookies = cookie.split("; ").filter(function(v){ return v.indexOf(name + "=") != 0 })
return setHttpHeader(payload, "Cookie", cookies.join("; "))
}
function httpCookie(payload, name) {
let h = httpHeader(payload, "Cookie");
let cookie = h ? h.value : "";
let value;
let cookies = cookie.split("; ").forEach(function(v){
if (v.indexOf(name + "=") == 0) {
value = v.substr(name.length + 1);
}
})
return value;
}
module.exports = {
init: init,
on: function(){ return middleware.on.apply(this, arguments) },
parseMessage: parseMessage,
searchResponses: searchResponses,
httpPath: httpPath,
httpMethod: httpMethod,
setHttpPath: setHttpPath,
httpPathParam: httpPathParam,
setHttpPathParam: setHttpPathParam,
httpStatus: httpStatus,
setHttpStatus: setHttpStatus,
httpHeader: httpHeader,
setHttpHeader: setHttpHeader,
deleteHttpHeader: deleteHttpHeader,
httpBody: httpBody,
setHttpBody: setHttpBody,
httpBodyParam: httpBodyParam,
setHttpBodyParam: setHttpBodyParam,
httpCookie: httpCookie,
setHttpCookie: setHttpCookie,
deleteHttpCookie: deleteHttpCookie,
test: testRunner,
benchmark: testBenchmark,
httpHeaders: httpHeaders
}
// =========== Tests ==============
function testRunner(){
["init", "filter", "parseMessage", "httpMethod", "httpPath", "setHttpHeader", "deleteHttpHeader", "httpPathParam", "httpHeader", "httpBody", "setHttpBody", "httpBodyParam", "httpCookie", "setHttpCookie", "deleteHttpCookie", "httpHeaders"].forEach(function(t){
console.log(`====== Start ${t} =======`)
eval(`TEST_${t}()`)
console.log(`====== End ${t} =======`)
})
}
function testBenchmark(){
const child_process = require('child_process');
let gor = init();
gor.on("message", function(){
});
gor.on("request", function(){
});
for (var i = 0; i<256; i++) {
let req = parseMessage(Buffer.from("1 2 3\nGET / HTTP/1.1\r\n\r\n").toString('hex'));
req.ID = +Date.now()
gor.emit(req);
gor.on("request", req.ID+"", function(){
gor.on("response", req.ID+"", function(){
})
})
if ( i % 3 == 0 ) {
let resp = parseMessage(Buffer.from("2 2 3\nHTTP/1.1 200 OK\r\n\r\n").toString('hex'));
resp.ID = req.ID
gor.emit(resp);
}
}
child_process.execSync("sleep 0.01");
gor.gc(1)
fail(JSON.stringify(gor.ch))
}
// Just print in red color
function fail(message) {
console.error("\x1b[31m[MIDDLEWARE] %s\x1b[0m", message)
}
function log(message) {
console.error(message)
}
function TEST_init() {
const child_process = require('child_process');
let received = 0;
let gor = init();
gor.on("message", function(){
received++; // should be called 3 times for for every request
});
gor.on("request", function(){
received++; // should be called 1 time only for request
});
gor.on("response", "2", function(){
received++; // should be called 1 time only for specific response
})
if (Object.keys(gor.ch).length != 3) {
return fail("Should create 3 channels");
}
let req = parseMessage(Buffer.from("1 2 3\nGET / HTTP/1.1\r\n\r\n").toString('hex'));
let resp = parseMessage(Buffer.from("2 2 3\nHTTP/1.1 200 OK\r\n\r\n").toString('hex'));
let resp2 = parseMessage(Buffer.from("2 3 3\nHTTP/1.1 200 OK\r\n\r\n").toString('hex'));
gor.emit(req);
gor.emit(resp);
gor.emit(resp2);
child_process.execSync("sleep 0.01");
if (received != 5) {
fail(`Should receive 5 messages: ${received}`);
}
}
function TEST_filter() {
const child_process = require('child_process');
let gor = init();
gor.on("request", function(req){
if (httpPath(req.http) != "/filter") {
return req
}
});
gor.on("request", function(req){
return req
});
let reqPass = parseMessage(Buffer.from("1 2 3\nGET / HTTP/1.1\r\n\r\n").toString('hex'));
let reqFilter = parseMessage(Buffer.from("1 2 3\nGET /filter HTTP/1.1\r\n\r\n").toString('hex'));
if (!gor.emit(reqPass)) {
return fail("Should not filter request")
}
if (gor.emit(reqFilter)) {
return fail("Should filter request even if one middleware rejected it")
}
}
function TEST_parseMessage() {
const exampleMessage = Buffer.from("1 2 3\nGET / HTTP/1.1\r\n\r\n").toString('hex')
let msg = parseMessage(exampleMessage)
let expected = { type: '1', ID: '2', meta: ["1", "2", "3"], http: Buffer.from("GET / HTTP/1.1\r\n\r\n") }
Object.keys(expected).forEach(function(k){
if (msg[k].toString() != expected[k].toString()) {
fail(`${k}: '${expected[k]}' != '${msg[k]}'`)
}
})
}
function TEST_httpPath() {
const examplePayload = "GET /test HTTP/1.1\r\n\r\n";
let payload = Buffer.from(examplePayload);
let path = httpPath(payload);
if (path != "/test") {
return fail(`Path '${patj}' != '/test'`)
}
let newPayload = setHttpPath(payload, '/')
if (newPayload.toString() != "GET / HTTP/1.1\r\n\r\n") {
return fail(`Malformed payload '${newPayload}'`)
}
newPayload = setHttpPath(payload, '/bigger')
if (newPayload.toString() != "GET /bigger HTTP/1.1\r\n\r\n") {
return fail(`Malformed payload '${newPayload}'`)
}
}
function TEST_httpMethod() {
const examplePayload = "GET /test HTTP/1.1\r\n\r\n";
let payload = Buffer.from(examplePayload);
let method = httpMethod(payload);
if (method != "GET") {
return fail(`Path '${method}' != 'GET'`)
}
}
function TEST_httpPathParam() {
let p = Buffer.from("GET / HTTP/1.1\r\n\r\n");
if (httpPathParam(p, "test")) {
return fail("Should not found param")
}
p = setHttpPathParam(p, "test", "123");
if (httpPath(p) != "/?test=123") {
return fail("Should set first param: " + httpPath(p));
}
if (httpPathParam(p, "test") != "123") {
return fail("Should get first param: " + httpPathParam(p, "test"));
}
p = setHttpPathParam(p, "qwer", "ty");
if (httpPath(p) != "/?test=123&qwer=ty") {
return fail("Should set second param: " + httpPath(p));
}
p = setHttpPathParam(p, "test", "4321");
if (httpPath(p) != "/?test=4321&qwer=ty") {
return fail("Should update first param: " + httpPath(p));
}
if (httpPathParam(p, "test") != "4321") {
return fail("Should update first param: " + httpPath(p));
}
}
function TEST_httpBodyParam() {
let p = Buffer.from("POST / HTTP/1.1\r\n\r\n");
if (httpBodyParam(p, "test")) {
return fail("Should not found param")
}
p = setHttpBodyParam(p, "test", "123");
if (httpBody(p).toString() != "test=123") {
return fail("Should set first param: " + httpBody(p).toString());
}
if (httpBodyParam(p, "test") != "123") {
return fail("Should get first param: " + httpBodyParam(p, "test"));
}
p = setHttpBodyParam(p, "qwer", "ty");
if (httpBody(p).toString() != "test=123&qwer=ty") {
return fail("Should set second param: " + httpBody(p).toString());
}
p = setHttpBodyParam(p, "test", "4321");
if (httpBody(p).toString() != "test=4321&qwer=ty") {
return fail("Should update first param: " + httpBody(p).toString());
}
if (httpBodyParam(p, "test") != "4321") {
return fail("Should update first param: " + httpBody(p).toString());
}
}
function TEST_httpHeader() {
const examplePayload = "GET / HTTP/1.1\r\nHost: localhost:3000\r\nUser-Agent: Node\r\nContent-Length:5\r\n\r\nhello";
let expected = {"Host": "localhost:3000", "User-Agent": "Node", "Content-Length": "5"}
Object.keys(expected).forEach(function(name){
let payload = Buffer.from(examplePayload);
let header = httpHeader(payload, name);
if (!header) {
fail(`Header not found. Was looking for: ${name}`)
}
if (header && header.value != expected[name]) {
fail(`${name}: '${expected[name]}' != '${header.value}'`)
}
})
}
function TEST_setHttpHeader() {
const examplePayload = "GET / HTTP/1.1\r\nUser-Agent: Node\r\nContent-Length: 5\r\n\r\nhello";
// Modify existing header
["", "1", "Long test header"].forEach(function(ua){
let expected = `GET / HTTP/1.1\r\nUser-Agent: ${ua}\r\nContent-Length: 5\r\n\r\nhello`;
let p = Buffer.from(examplePayload);
p = setHttpHeader(p, "User-Agent", ua);
if (p != expected) {
console.error(`setHeader failed, expected User-Agent value: ${ua}.\n${p}`)
}
})
// Adding new header
let expected = `GET / HTTP/1.1\r\nX-Test: test\r\nUser-Agent: Node\r\nContent-Length: 5\r\n\r\nhello`;
let p = Buffer.from(examplePayload);
p = setHttpHeader(p, "X-Test", "test");
if (p != expected) {
console.error(`setHeader failed, expected new header 'X-Test' header: ${p}`)
}
}
function TEST_deleteHttpHeader() {
const examplePayload = "GET / HTTP/1.1\r\nUser-Agent: Node\r\nContent-Length: 5\r\n\r\nhello";
// Adding new header
let expected = `GET / HTTP/1.1\r\nContent-Length: 5\r\n\r\nhello`;
let p = Buffer.from(examplePayload);
p = deleteHttpHeader(p, "User-Agent", "test");
if (p != expected) {
console.error(`setHeader failed, expected delete header 'User-Agent' header: ${p}`)
}
}
function TEST_httpBody() {
const examplePayload = "GET / HTTP/1.1\r\nUser-Agent: Node\r\nContent-Length: 5\r\n\r\nhello";
let body = httpBody(Buffer.from(examplePayload));
if (body != "hello") {
fail(`'${body}' != 'hello'`)
}
}
function TEST_setHttpBody() {
const examplePayload = "GET / HTTP/1.1\r\nUser-Agent: Node\r\nContent-Length: 5\r\n\r\nhello";
let p = setHttpBody(Buffer.from(examplePayload), Buffer.from("hello, world!"));
if (p != "GET / HTTP/1.1\r\nUser-Agent: Node\r\nContent-Length: 13\r\n\r\nhello, world!") {
fail(`Wrong body: '${p}'`)
}
}
function TEST_httpCookie() {
const examplePayload = "GET / HTTP/1.1\r\nCookie: a=b; test=zxc\r\n\r\n";
let c = httpCookie(Buffer.from(examplePayload), "test");
if (c != "zxc") {
return fail(`Should get cookie: ${c}`);
}
c = httpCookie(Buffer.from(examplePayload), "nope");
if (c != null) {
return fail(`Should not find cookie: ${c}`);
}
}
function TEST_setHttpCookie() {
const examplePayload = "GET / HTTP/1.1\r\nCookie: a=b; test=zxc\r\n\r\n";
let p = setHttpCookie(Buffer.from(examplePayload), "test", "1");
if (p != "GET / HTTP/1.1\r\nCookie: a=b; test=1\r\n\r\n") {
return fail(`Should update cookie: ${p}`)
}
p = setHttpCookie(Buffer.from(examplePayload), "new", "one");
if (p != "GET / HTTP/1.1\r\nCookie: a=b; test=zxc; new=one\r\n\r\n") {
return fail(`Should add new cookie: ${p}`)
}
}
function TEST_deleteHttpCookie() {
const examplePayload = "GET / HTTP/1.1\r\nCookie: a=b; test=zxc\r\n\r\n";
let p = deleteHttpCookie(Buffer.from(examplePayload), "a");
if (p != "GET / HTTP/1.1\r\nCookie: test=zxc\r\n\r\n") {
return fail(`Should delete cookie: ${p}`)
}
}
function TEST_httpHeaders() {
const examplePayload = "GET / HTTP/1.1\r\nHost: localhost:3000\r\nUser-Agent: Node\r\nContent-Length:5\r\n\r\nhello";
let expectedHeaders = {"Host": "localhost:3000", "User-Agent": "Node", "Content-Length": "5"}
let payload = Buffer.from(examplePayload);
let headers = httpHeaders(payload);
["Host", "User-Agent", "Content-Length"].forEach(function(header){
let actual = headers[header];
let expected = expectedHeaders[header];
if (!actual) {
fail(`${header} Header was not found`);
}
if (actual != expected) {
fail(`${header} Header not Equal to Expected: ${expected} was ${actual}`);
}
})
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "goreplay_middleware",
"version": "1.0.0",
"description": "Package for writing middleware for GoReplay https://goreplay.org",
"main": "middleware.js",
"scripts": {
"test": "node -e \"var gor = require('./middleware.js'); gor.test(); process.exit()\"",
"benchmark": "node -e \"var gor = require('./middleware.js'); gor.benchmark(); process.exit()\""
},
"keywords": [
"middleware",
"goreplay"
],
"author": "Leonid Bugaev",
"license": "LGPL-3.0"
}
+221
View File
@@ -0,0 +1,221 @@
package main
import (
"bytes"
"crypto/rand"
"encoding/hex"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/buger/goreplay/proto"
)
type fakeServiceCb func(string, int, []byte)
// Simple service that generate token on request, and require this token for accesing to secure area
func NewFakeSecureService(wg *sync.WaitGroup, cb fakeServiceCb) *httptest.Server {
active_tokens := make([]string, 0)
var mu sync.Mutex
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
mu.Lock()
defer mu.Unlock()
Debug("Received request: " + req.URL.String())
switch req.URL.Path {
case "/token":
// Generate random token
token_length := 10
buf := make([]byte, token_length)
rand.Read(buf)
token := hex.EncodeToString(buf)
active_tokens = append(active_tokens, token)
w.Write([]byte(token))
cb(req.URL.Path, 200, []byte(token))
case "/secure":
token := req.URL.Query().Get("token")
token_found := false
for _, t := range active_tokens {
if t == token {
token_found = true
break
}
}
if token_found {
w.WriteHeader(http.StatusAccepted)
cb(req.URL.Path, 202, []byte(nil))
} else {
w.WriteHeader(http.StatusForbidden)
cb(req.URL.Path, 403, []byte(nil))
}
}
wg.Done()
}))
return server
}
func TestFakeSecureService(t *testing.T) {
var resp, token []byte
wg := new(sync.WaitGroup)
server := NewFakeSecureService(wg, func(path string, status int, resp []byte) {
})
defer server.Close()
wg.Add(3)
client := NewHTTPClient(server.URL, &HTTPClientConfig{Debug: true})
resp, _ = client.Get("/token")
token = proto.Body(resp)
// Right token
resp, _ = client.Get("/secure?token=" + string(token))
if !bytes.Equal(proto.Status(resp), []byte("202")) {
t.Error("Valid token should return status 202:", string(proto.Status(resp)))
}
// Wrong tokens forbidden
resp, _ = client.Get("/secure?token=wrong")
if !bytes.Equal(proto.Status(resp), []byte("403")) {
t.Error("Wrong token should returns status 403:", string(proto.Status(resp)))
}
wg.Wait()
}
func TestEchoMiddleware(t *testing.T) {
wg := new(sync.WaitGroup)
from := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Env", "prod")
w.Header().Set("RequestPath", r.URL.Path)
wg.Done()
}))
defer from.Close()
to := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Env", "test")
w.Header().Set("RequestPath", r.URL.Path)
wg.Done()
}))
defer to.Close()
quit := make(chan int)
Settings.middleware = "./examples/middleware/echo.sh"
// Catch traffic from one service
fromAddr := strings.Replace(from.Listener.Addr().String(), "[::]", "127.0.0.1", -1)
input := NewRAWInput(fromAddr, EnginePcap, true, testRawExpire, "", "", "", 0)
defer input.Close()
// And redirect to another
output := NewHTTPOutput(to.URL, &HTTPOutputConfig{Debug: false})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
// Start Gor
go Start(quit)
// Wait till middleware initialization
time.Sleep(100 * time.Millisecond)
// Should receive 2 requests from original + 2 from replayed
client := NewHTTPClient(from.URL, &HTTPClientConfig{Debug: false})
for i := 0; i < 10; i++ {
wg.Add(4)
// Request should be echoed
client.Get("/a")
time.Sleep(5 * time.Millisecond)
client.Get("/b")
time.Sleep(5 * time.Millisecond)
}
wg.Wait()
close(quit)
time.Sleep(200 * time.Millisecond)
Settings.middleware = ""
}
func TestTokenMiddleware(t *testing.T) {
var resp, token []byte
wg := new(sync.WaitGroup)
from := NewFakeSecureService(wg, func(path string, status int, tok []byte) {
time.Sleep(10 * time.Millisecond)
})
defer from.Close()
to := NewFakeSecureService(wg, func(path string, status int, tok []byte) {
switch path {
case "/secure":
if status != 202 {
t.Error("Server should receive valid rewritten token")
}
}
time.Sleep(10 * time.Millisecond)
})
defer to.Close()
quit := make(chan int)
Settings.middleware = "go run ./examples/middleware/token_modifier.go"
fromAddr := strings.Replace(from.Listener.Addr().String(), "[::]", "127.0.0.1", -1)
// Catch traffic from one service
input := NewRAWInput(fromAddr, EnginePcap, true, testRawExpire, "", "", "", 0)
defer input.Close()
// And redirect to another
output := NewHTTPOutput(to.URL, &HTTPOutputConfig{Debug: true})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
// Start Gor
go Start(quit)
// Wait for middleware to initialize
// Give go compiller time to build programm
time.Sleep(500 * time.Millisecond)
// Should receive 2 requests from original + 2 from replayed
wg.Add(4)
client := NewHTTPClient(from.URL, &HTTPClientConfig{Debug: true})
// Sending traffic to original service
resp, _ = client.Get("/token")
token = proto.Body(resp)
// When delay is too smal, middleware does not always rewrite requests in time
// Hopefuly client will have delay more then 100ms :)
time.Sleep(100 * time.Millisecond)
resp, _ = client.Get("/secure?token=" + string(token))
if !bytes.Equal(proto.Status(resp), []byte("202")) {
t.Error("Valid token should return 202:", proto.Status(resp))
}
wg.Wait()
close(quit)
time.Sleep(100 * time.Millisecond)
Settings.middleware = ""
}
+2
View File
@@ -0,0 +1,2 @@
site_name: My Docs
theme: readthedocs
+26
View File
@@ -0,0 +1,26 @@
package main
import (
"fmt"
)
// DummyOutput used for debugging, prints all incoming requests
type DummyOutput struct {
}
// NewDummyOutput constructor for DummyOutput
func NewDummyOutput() (di *DummyOutput) {
di = new(DummyOutput)
return
}
func (i *DummyOutput) Write(data []byte) (int, error) {
fmt.Println(string(data))
return len(data), nil
}
func (i *DummyOutput) String() string {
return "Dummy Output"
}
+271
View File
@@ -0,0 +1,271 @@
package main
import (
"bufio"
"compress/gzip"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"time"
)
var dateFileNameFuncs = map[string]func(*FileOutput) string{
"%Y": func(o *FileOutput) string { return time.Now().Format("2006") },
"%m": func(o *FileOutput) string { return time.Now().Format("01") },
"%d": func(o *FileOutput) string { return time.Now().Format("02") },
"%H": func(o *FileOutput) string { return time.Now().Format("15") },
"%M": func(o *FileOutput) string { return time.Now().Format("04") },
"%S": func(o *FileOutput) string { return time.Now().Format("05") },
"%NS": func(o *FileOutput) string { return fmt.Sprint(time.Now().Nanosecond()) },
"%r": func(o *FileOutput) string { return string(o.currentID) },
"%t": func(o *FileOutput) string { return string(o.payloadType) },
}
type FileOutputConfig struct {
flushInterval time.Duration
sizeLimit unitSizeVar
outputFileMaxSize unitSizeVar
queueLimit int
append bool
}
// FileOutput output plugin
type FileOutput struct {
mu sync.Mutex
pathTemplate string
currentName string
file *os.File
queueLength int
chunkSize int
writer io.Writer
requestPerFile bool
currentID []byte
payloadType []byte
closed bool
totalFileSize int64
config *FileOutputConfig
}
// NewFileOutput constructor for FileOutput, accepts path
func NewFileOutput(pathTemplate string, config *FileOutputConfig) *FileOutput {
o := new(FileOutput)
o.pathTemplate = pathTemplate
o.config = config
o.updateName()
if strings.Contains(pathTemplate, "%r") {
o.requestPerFile = true
}
go func() {
for {
time.Sleep(config.flushInterval)
if o.closed {
break
}
o.updateName()
o.flush()
}
}()
return o
}
func getFileIndex(name string) int {
ext := filepath.Ext(name)
withoutExt := strings.TrimSuffix(name, ext)
if idx := strings.LastIndex(withoutExt, "_"); idx != -1 {
if i, err := strconv.Atoi(withoutExt[idx+1:]); err == nil {
return i
}
}
return -1
}
func setFileIndex(name string, idx int) string {
idxS := strconv.Itoa(idx)
ext := filepath.Ext(name)
withoutExt := strings.TrimSuffix(name, ext)
if i := strings.LastIndex(withoutExt, "_"); i != -1 {
if _, err := strconv.Atoi(withoutExt[i+1:]); err == nil {
withoutExt = withoutExt[:i]
}
}
return withoutExt + "_" + idxS + ext
}
func withoutIndex(s string) string {
if i := strings.LastIndex(s, "_"); i != -1 {
return s[:i]
}
return s
}
type sortByFileIndex []string
func (s sortByFileIndex) Len() int {
return len(s)
}
func (s sortByFileIndex) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortByFileIndex) Less(i, j int) bool {
if withoutIndex(s[i]) == withoutIndex(s[j]) {
return getFileIndex(s[i]) < getFileIndex(s[j])
}
return s[i] < s[j]
}
func (o *FileOutput) filename() string {
defer o.mu.Unlock()
o.mu.Lock()
path := o.pathTemplate
for name, fn := range dateFileNameFuncs {
path = strings.Replace(path, name, fn(o), -1)
}
if !o.config.append {
nextChunk := false
if o.currentName == "" ||
((o.config.queueLimit > 0 && o.queueLength >= o.config.queueLimit) ||
(o.config.sizeLimit > 0 && o.chunkSize >= int(o.config.sizeLimit))) {
nextChunk = true
}
ext := filepath.Ext(path)
withoutExt := strings.TrimSuffix(path, ext)
if matches, err := filepath.Glob(withoutExt + "*" + ext); err == nil {
if len(matches) == 0 {
return setFileIndex(path, 0)
}
sort.Sort(sortByFileIndex(matches))
last := matches[len(matches)-1]
fileIndex := 0
if idx := getFileIndex(last); idx != -1 {
fileIndex = idx
if nextChunk {
fileIndex++
}
}
return setFileIndex(last, fileIndex)
}
}
return path
}
func (o *FileOutput) updateName() {
o.currentName = filepath.Clean(o.filename())
}
func (o *FileOutput) Write(data []byte) (n int, err error) {
if o.requestPerFile {
meta := payloadMeta(data)
o.currentID = meta[1]
o.payloadType = meta[0]
}
o.updateName()
if o.file == nil || o.currentName != o.file.Name() {
o.mu.Lock()
o.Close()
o.file, err = os.OpenFile(o.currentName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
o.file.Sync()
if strings.HasSuffix(o.currentName, ".gz") {
o.writer = gzip.NewWriter(o.file)
} else {
o.writer = bufio.NewWriter(o.file)
}
if err != nil {
log.Fatal(o, "Cannot open file %q. Error: %s", o.currentName, err)
}
o.queueLength = 0
o.mu.Unlock()
}
o.writer.Write(data)
o.writer.Write([]byte(payloadSeparator))
o.totalFileSize += int64(len(data) + len(payloadSeparator))
o.queueLength++
if Settings.outputFileConfig.outputFileMaxSize > 0 && o.totalFileSize >= int64(Settings.outputFileConfig.outputFileMaxSize) {
return len(data), errors.New("File output reached size limit")
}
return len(data), nil
}
func (o *FileOutput) flush() {
// Don't exit on panic
defer func() {
if r := recover(); r != nil {
log.Println("PANIC while file flush: ", r, o, string(debug.Stack()))
}
}()
defer o.mu.Unlock()
o.mu.Lock()
if o.file != nil {
if strings.HasSuffix(o.currentName, ".gz") {
o.writer.(*gzip.Writer).Flush()
} else {
o.writer.(*bufio.Writer).Flush()
}
if stat, err := o.file.Stat(); err == nil {
o.chunkSize = int(stat.Size())
} else {
log.Println("Error accessing file sats", err)
}
}
}
func (o *FileOutput) String() string {
return "File output: " + o.file.Name()
}
func (o *FileOutput) Close() error {
if o.file != nil {
if strings.HasSuffix(o.currentName, ".gz") {
o.writer.(*gzip.Writer).Close()
} else {
o.writer.(*bufio.Writer).Flush()
}
o.file.Close()
}
o.closed = true
return nil
}
+40
View File
@@ -0,0 +1,40 @@
package main
import (
"strconv"
"strings"
)
var dataUnitMap = map[byte]int64{
'k': 1024,
'm': 1024 * 1024,
'g': 1024 * 1024 * 1024,
}
func parseDataUnit(s string) int64 {
// Allow kb, mb, gb
if strings.HasSuffix(s, "b") {
s = s[:len(s)-1]
}
if unit, ok := dataUnitMap[s[len(s)-1]]; ok {
size, _ := strconv.ParseInt(s[:len(s)-1], 10, 64)
return unit * size
}
// If no unit specified use bytes
size, _ := strconv.ParseInt(s, 10, 64)
return size
}
type unitSizeVar int64
func (u unitSizeVar) String() string {
return strconv.Itoa(int(u))
}
func (u *unitSizeVar) Set(s string) error {
*u = unitSizeVar(parseDataUnit(s))
return nil
}
+348
View File
@@ -0,0 +1,348 @@
package main
import (
"fmt"
"io"
"math/rand"
"os"
"reflect"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestFileOutput(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
output := NewFileOutput("/tmp/test_requests.gor", &FileOutputConfig{flushInterval: time.Minute, append: true})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
for i := 0; i < 100; i++ {
wg.Add(2)
input.EmitGET()
input.EmitPOST()
}
time.Sleep(100 * time.Millisecond)
output.flush()
close(quit)
quit = make(chan int)
var counter int64
input2 := NewFileInput("/tmp/test_requests.gor", false)
output2 := NewTestOutput(func(data []byte) {
atomic.AddInt64(&counter, 1)
wg.Done()
})
Plugins.Inputs = []io.Reader{input2}
Plugins.Outputs = []io.Writer{output2}
go Start(quit)
wg.Wait()
close(quit)
}
func TestFileOutputWithNameCleaning(t *testing.T) {
output := &FileOutput{pathTemplate: "./test_requests.gor", config: &FileOutputConfig{flushInterval: time.Minute, append: false}}
expectedFileName := "test_requests_0.gor"
output.updateName()
if expectedFileName != output.currentName {
t.Errorf("Expected path %s but got %s", expectedFileName, output.currentName)
}
}
func TestFileOutputPathTemplate(t *testing.T) {
output := &FileOutput{pathTemplate: "/tmp/log-%Y-%m-%d-%S-%t", config: &FileOutputConfig{flushInterval: time.Minute, append: true}}
now := time.Now()
output.payloadType = []byte("3")
expectedPath := fmt.Sprintf("/tmp/log-%s-%s-%s-%s-3", now.Format("2006"), now.Format("01"), now.Format("02"), now.Format("05"))
path := output.filename()
if expectedPath != path {
t.Errorf("Expected path %s but got %s", expectedPath, path)
}
}
func TestFileOutputMultipleFiles(t *testing.T) {
output := NewFileOutput("/tmp/log-%Y-%m-%d-%S", &FileOutputConfig{append: true, flushInterval: time.Minute})
if output.file != nil {
t.Error("Should not initialize file if no writes")
}
output.Write([]byte("1 1 1\r\ntest"))
name1 := output.file.Name()
output.Write([]byte("1 1 1\r\ntest"))
name2 := output.file.Name()
time.Sleep(time.Second)
output.updateName()
output.Write([]byte("1 1 1\r\ntest"))
name3 := output.file.Name()
if name2 != name1 {
t.Error("Fast changes should happen in same file:", name1, name2, name3)
}
if name3 == name1 {
t.Error("File name should change:", name1, name2, name3)
}
os.Remove(name1)
os.Remove(name3)
}
func TestFileOutputFilePerRequest(t *testing.T) {
output := NewFileOutput("/tmp/log-%Y-%m-%d-%S-%r", &FileOutputConfig{append: true})
if output.file != nil {
t.Error("Should not initialize file if no writes")
}
output.Write([]byte("1 1 1\ntest"))
name1 := output.file.Name()
output.Write([]byte("1 2 1\ntest"))
name2 := output.file.Name()
time.Sleep(time.Second)
output.updateName()
output.Write([]byte("1 3 1\ntest"))
name3 := output.file.Name()
if name3 == name2 || name2 == name1 || name3 == name1 {
t.Error("File name should change:", name1, name2, name3)
}
os.Remove(name1)
os.Remove(name2)
os.Remove(name3)
}
func TestFileOutputCompression(t *testing.T) {
output := NewFileOutput("/tmp/log-%Y-%m-%d-%S.gz", &FileOutputConfig{append: true, flushInterval: time.Minute})
if output.file != nil {
t.Error("Should not initialize file if no writes")
}
for i := 0; i < 1000; i++ {
output.Write([]byte("1 1 1\r\ntest"))
}
name := output.file.Name()
output.Close()
s, _ := os.Stat(name)
if s.Size() == 12*1000 {
t.Error("Should be compressed file:", s.Size())
}
os.Remove(name)
}
func TestParseDataUnit(t *testing.T) {
var tests = []struct {
value string
size int64
}{
{"100kb", dataUnitMap['k'] * 100},
{"100k", dataUnitMap['k'] * 100},
{"1kb", dataUnitMap['k']},
{"1g", dataUnitMap['g']},
{"10m", dataUnitMap['m'] * 10},
{"zsaa312", 0},
}
for _, c := range tests {
if parseDataUnit(c.value) != c.size {
t.Error(c.value, "should be", c.size, "instead", parseDataUnit(c.value))
}
}
}
func TestGetFileIndex(t *testing.T) {
var tests = []struct {
path string
index int
}{
{"/tmp/logs", -1},
{"/tmp/logs_1", 1},
{"/tmp/logs_2.gz", 2},
{"/tmp/logs_0.gz", 0},
}
for _, c := range tests {
if getFileIndex(c.path) != c.index {
t.Error(c.path, "should be", c.index, "instead", getFileIndex(c.path))
}
}
}
func TestSetFileIndex(t *testing.T) {
var tests = []struct {
path string
index int
newPath string
}{
{"/tmp/logs", 0, "/tmp/logs_0"},
{"/tmp/logs.gz", 1, "/tmp/logs_1.gz"},
{"/tmp/logs_1", 0, "/tmp/logs_0"},
{"/tmp/logs_0", 10, "/tmp/logs_10"},
{"/tmp/logs_0.gz", 10, "/tmp/logs_10.gz"},
{"/tmp/logs_underscores.gz", 10, "/tmp/logs_underscores_10.gz"},
}
for _, c := range tests {
if setFileIndex(c.path, c.index) != c.newPath {
t.Error(c.path, "should be", c.newPath, "instead", setFileIndex(c.path, c.index))
}
}
}
func TestFileOutputAppendQueueLimitOverflow(t *testing.T) {
rnd := rand.Int63()
name := fmt.Sprintf("/tmp/%d", rnd)
output := NewFileOutput(name, &FileOutputConfig{append: false, flushInterval: time.Minute, queueLimit: 2})
output.Write([]byte("1 1 1\r\ntest"))
name1 := output.file.Name()
output.Write([]byte("1 1 1\r\ntest"))
name2 := output.file.Name()
output.updateName()
output.Write([]byte("1 1 1\r\ntest"))
name3 := output.file.Name()
if name2 != name1 || name1 != fmt.Sprintf("/tmp/%d_0", rnd) {
t.Error("Fast changes should happen in same file:", name1, name2, name3)
}
if name3 == name1 || name3 != fmt.Sprintf("/tmp/%d_1", rnd) {
t.Error("File name should change:", name1, name2, name3)
}
os.Remove(name1)
os.Remove(name3)
}
func TestFileOutputAppendQueueLimitNoOverflow(t *testing.T) {
rnd := rand.Int63()
name := fmt.Sprintf("/tmp/%d", rnd)
output := NewFileOutput(name, &FileOutputConfig{append: false, flushInterval: time.Minute, queueLimit: 3})
output.Write([]byte("1 1 1\r\ntest"))
name1 := output.file.Name()
output.Write([]byte("1 1 1\r\ntest"))
name2 := output.file.Name()
output.updateName()
output.Write([]byte("1 1 1\r\ntest"))
name3 := output.file.Name()
if name2 != name1 || name1 != fmt.Sprintf("/tmp/%d_0", rnd) {
t.Error("Fast changes should happen in same file:", name1, name2, name3)
}
if name3 != name1 || name3 != fmt.Sprintf("/tmp/%d_0", rnd) {
t.Error("File name should not change:", name1, name2, name3)
}
os.Remove(name1)
os.Remove(name3)
}
func TestFileOutputAppendQueueLimitGzips(t *testing.T) {
rnd := rand.Int63()
name := fmt.Sprintf("/tmp/%d.gz", rnd)
output := NewFileOutput(name, &FileOutputConfig{append: false, flushInterval: time.Minute, queueLimit: 2})
output.Write([]byte("1 1 1\r\ntest"))
name1 := output.file.Name()
output.Write([]byte("1 1 1\r\ntest"))
name2 := output.file.Name()
output.updateName()
output.Write([]byte("1 1 1\r\ntest"))
name3 := output.file.Name()
if name2 != name1 || name1 != fmt.Sprintf("/tmp/%d_0.gz", rnd) {
t.Error("Fast changes should happen in same file:", name1, name2, name3)
}
if name3 == name1 || name3 != fmt.Sprintf("/tmp/%d_1.gz", rnd) {
t.Error("File name should change:", name1, name2, name3)
}
os.Remove(name1)
os.Remove(name3)
}
func TestFileOutputSort(t *testing.T) {
var files = []string{"2016_0", "2014_10", "2015_0", "2015_10", "2015_2"}
var expected = []string{"2014_10", "2015_0", "2015_2", "2015_10", "2016_0"}
sort.Sort(sortByFileIndex(files))
if !reflect.DeepEqual(files, expected) {
t.Error("Should properly sort file names using indexes", files, expected)
}
}
func TestFileOutputAppendSizeLimitOverflow(t *testing.T) {
rnd := rand.Int63()
name := fmt.Sprintf("/tmp/%d", rnd)
message := []byte("1 1 1\r\ntest")
messageSize := len(message) + len(payloadSeparator)
output := NewFileOutput(name, &FileOutputConfig{append: false, flushInterval: time.Minute, sizeLimit: unitSizeVar(2 * messageSize)})
output.Write([]byte("1 1 1\r\ntest"))
name1 := output.file.Name()
output.Write([]byte("1 1 1\r\ntest"))
name2 := output.file.Name()
output.flush()
output.updateName()
output.Write([]byte("1 1 1\r\ntest"))
name3 := output.file.Name()
if name2 != name1 || name1 != fmt.Sprintf("/tmp/%d_0", rnd) {
t.Error("Fast changes should happen in same file:", name1, name2, name3)
}
if name3 == name1 || name3 != fmt.Sprintf("/tmp/%d_1", rnd) {
t.Error("File name should change:", name1, name2, name3)
}
os.Remove(name1)
os.Remove(name3)
}
+233
View File
@@ -0,0 +1,233 @@
package main
import (
"io"
"log"
"sync/atomic"
"time"
"github.com/buger/goreplay/proto"
)
const initialDynamicWorkers = 10
type response struct {
payload []byte
uuid []byte
roundTripTime int64
startedAt int64
}
// HTTPOutputConfig struct for holding http output configuration
type HTTPOutputConfig struct {
redirectLimit int
stats bool
workersMin int
workersMax int
statsMs int
workers int
queueLen int
elasticSearch string
Timeout time.Duration
OriginalHost bool
BufferSize int
CompatibilityMode bool
Debug bool
TrackResponses bool
}
// HTTPOutput plugin manage pool of workers which send request to replayed server
// By default workers pool is dynamic and starts with 10 workers
// You can specify fixed number of workers using `--output-http-workers`
type HTTPOutput struct {
// Keep this as first element of struct because it guarantees 64bit
// alignment. atomic.* functions crash on 32bit machines if operand is not
// aligned at 64bit. See https://github.com/golang/go/issues/599
activeWorkers int64
address string
limit int
queue chan []byte
responses chan response
needWorker chan int
config *HTTPOutputConfig
queueStats *GorStat
elasticSearch *ESPlugin
}
// NewHTTPOutput constructor for HTTPOutput
// Initialize workers
func NewHTTPOutput(address string, config *HTTPOutputConfig) io.Writer {
o := new(HTTPOutput)
o.address = address
o.config = config
if o.config.stats {
o.queueStats = NewGorStat("output_http", o.config.statsMs)
}
o.queue = make(chan []byte, o.config.queueLen)
o.responses = make(chan response, o.config.queueLen)
o.needWorker = make(chan int, 1)
// Initial workers count
if o.config.workersMax == 0 {
o.needWorker <- initialDynamicWorkers
} else {
o.needWorker <- o.config.workersMax
}
if o.config.elasticSearch != "" {
o.elasticSearch = new(ESPlugin)
o.elasticSearch.Init(o.config.elasticSearch)
}
go o.workerMaster()
return o
}
func (o *HTTPOutput) workerMaster() {
for {
newWorkers := <-o.needWorker
for i := 0; i < newWorkers; i++ {
go o.startWorker()
}
}
}
func (o *HTTPOutput) startWorker() {
client := NewHTTPClient(o.address, &HTTPClientConfig{
FollowRedirects: o.config.redirectLimit,
Debug: o.config.Debug,
OriginalHost: o.config.OriginalHost,
Timeout: o.config.Timeout,
ResponseBufferSize: o.config.BufferSize,
CompatibilityMode: o.config.CompatibilityMode,
})
deathCount := 0
atomic.AddInt64(&o.activeWorkers, 1)
for {
select {
case data := <-o.queue:
o.sendRequest(client, data)
deathCount = 0
case <-time.After(time.Millisecond * 100):
// When dynamic scaling enabled workers die after 2s of inactivity
if o.config.workersMin == o.config.workersMax {
continue
}
deathCount++
if deathCount > 20 {
workersCount := int(atomic.LoadInt64(&o.activeWorkers))
// At least 1 startWorker should be alive
if workersCount != 1 && workersCount > o.config.workersMin {
atomic.AddInt64(&o.activeWorkers, -1)
return
}
}
}
}
}
func (o *HTTPOutput) Write(data []byte) (n int, err error) {
if !isRequestPayload(data) {
return len(data), nil
}
buf := make([]byte, len(data))
copy(buf, data)
o.queue <- buf
if o.config.stats {
o.queueStats.Write(len(o.queue))
}
if o.config.workersMax != o.config.workersMin {
workersCount := int(atomic.LoadInt64(&o.activeWorkers))
if len(o.queue) > workersCount {
extraWorkersReq := len(o.queue) - workersCount + 1
maxWorkersAvailable := o.config.workersMax - workersCount
if extraWorkersReq > maxWorkersAvailable {
extraWorkersReq = maxWorkersAvailable
}
if extraWorkersReq > 0 {
o.needWorker <- extraWorkersReq
}
}
}
return len(data), nil
}
func (o *HTTPOutput) Read(data []byte) (int, error) {
resp := <-o.responses
if Settings.debug {
Debug("[OUTPUT-HTTP] Received response:", string(resp.payload))
}
header := payloadHeader(ReplayedResponsePayload, resp.uuid, resp.roundTripTime, resp.startedAt)
copy(data[0:len(header)], header)
copy(data[len(header):], resp.payload)
return len(resp.payload) + len(header), nil
}
func (o *HTTPOutput) sendRequest(client *HTTPClient, request []byte) {
meta := payloadMeta(request)
if Settings.debug {
Debug(meta)
}
if len(meta) < 2 {
return
}
uuid := meta[1]
body := payloadBody(request)
if !proto.IsHTTPPayload(body) {
return
}
start := time.Now()
resp, err := client.Send(body)
stop := time.Now()
if err != nil {
log.Println("Error when sending ", err, time.Now())
Debug("Request error:", err)
}
if o.config.TrackResponses {
o.responses <- response{resp, uuid, start.UnixNano(), stop.UnixNano() - start.UnixNano()}
}
if o.elasticSearch != nil {
o.elasticSearch.ResponseAnalyze(request, resp, start, stop)
}
}
func (o *HTTPOutput) String() string {
return "HTTP output: " + o.address
}
+158
View File
@@ -0,0 +1,158 @@
package main
import (
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
_ "net/http/httputil"
"sync"
"testing"
"time"
)
func TestHTTPOutput(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Header.Get("User-Agent") != "Gor" {
t.Error("Wrong header")
}
if req.Method == "OPTIONS" {
t.Error("Wrong method")
}
if req.Method == "POST" {
defer req.Body.Close()
body, _ := ioutil.ReadAll(req.Body)
if string(body) != "a=1&b=2" {
t.Error("Wrong POST body:", string(body))
}
}
wg.Done()
}))
defer server.Close()
headers := HTTPHeaders{HTTPHeader{"User-Agent", "Gor"}}
methods := HTTPMethods{[]byte("GET"), []byte("PUT"), []byte("POST")}
Settings.modifierConfig = HTTPModifierConfig{headers: headers, methods: methods}
http_output := NewHTTPOutput(server.URL, &HTTPOutputConfig{Debug: true, TrackResponses: true})
output := NewTestOutput(func(data []byte) {
wg.Done()
})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{http_output, output}
go Start(quit)
for i := 0; i < 1; i++ {
// 2 http-output, 2 - test output request, 2 - test output http response
wg.Add(6) // OPTIONS should be ignored
input.EmitPOST()
input.EmitOPTIONS()
input.EmitGET()
}
wg.Wait()
close(quit)
Settings.modifierConfig = HTTPModifierConfig{}
}
func TestHTTPOutputKeepOriginalHost(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Host != "custom-host.com" {
t.Error("Wrong header", req.Host)
}
wg.Done()
}))
defer server.Close()
headers := HTTPHeaders{HTTPHeader{"Host", "custom-host.com"}}
Settings.modifierConfig = HTTPModifierConfig{headers: headers}
output := NewHTTPOutput(server.URL, &HTTPOutputConfig{Debug: false, OriginalHost: true})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
wg.Add(1)
input.EmitGET()
wg.Wait()
close(quit)
Settings.modifierConfig = HTTPModifierConfig{}
}
func TestOutputHTTPSSL(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
// Origing and Replay server initialization
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wg.Done()
}))
input := NewTestInput()
output := NewHTTPOutput(server.URL, &HTTPOutputConfig{})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
wg.Add(2)
input.EmitPOST()
input.EmitGET()
wg.Wait()
close(quit)
}
func BenchmarkHTTPOutput(b *testing.B) {
wg := new(sync.WaitGroup)
quit := make(chan int)
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(50 * time.Millisecond)
wg.Done()
}))
defer server.Close()
input := NewTestInput()
output := NewHTTPOutput(server.URL, &HTTPOutputConfig{})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
for i := 0; i < b.N; i++ {
wg.Add(1)
input.EmitPOST()
}
wg.Wait()
close(quit)
}
+101
View File
@@ -0,0 +1,101 @@
package main
import (
"encoding/json"
"io"
"log"
"strings"
"time"
"github.com/buger/goreplay/proto"
"github.com/Shopify/sarama"
"github.com/Shopify/sarama/mocks"
)
// KafkaOutput is used for sending payloads to kafka in JSON format.
type KafkaOutput struct {
config *KafkaConfig
producer sarama.AsyncProducer
}
// KafkaOutputFrequency in milliseconds
const KafkaOutputFrequency = 500
// NewKafkaOutput creates instance of kafka producer client.
func NewKafkaOutput(address string, config *KafkaConfig) io.Writer {
c := sarama.NewConfig()
var producer sarama.AsyncProducer
if mock, ok := config.producer.(*mocks.AsyncProducer); ok && mock != nil {
producer = config.producer
} else {
c.Producer.RequiredAcks = sarama.WaitForLocal
c.Producer.Compression = sarama.CompressionSnappy
c.Producer.Flush.Frequency = KafkaOutputFrequency * time.Millisecond
brokerList := strings.Split(config.host, ",")
var err error
producer, err = sarama.NewAsyncProducer(brokerList, c)
if err != nil {
log.Fatalln("Failed to start Sarama(Kafka) producer:", err)
}
}
o := &KafkaOutput{
config: config,
producer: producer,
}
if Settings.verbose {
// Start infinite loop for tracking errors for kafka producer.
go o.ErrorHandler()
}
return o
}
// ErrorHandler should receive errors
func (o *KafkaOutput) ErrorHandler() {
for err := range o.producer.Errors() {
log.Println("Failed to write access log entry:", err)
}
}
func (o *KafkaOutput) Write(data []byte) (n int, err error) {
var message sarama.StringEncoder
if !o.config.useJSON {
message = sarama.StringEncoder(data)
} else {
headers := make(map[string]string)
proto.ParseHeaders([][]byte{data}, func(header []byte, value []byte) bool {
headers[string(header)] = string(value)
return true
})
meta := payloadMeta(data)
req := payloadBody(data)
kafkaMessage := KafkaMessage{
ReqURL: string(proto.Path(req)),
ReqType: string(meta[0]),
ReqID: string(meta[1]),
ReqTs: string(meta[2]),
ReqMethod: string(proto.Method(req)),
ReqBody: string(proto.Body(req)),
ReqHeaders: headers,
}
jsonMessage, _ := json.Marshal(&kafkaMessage)
message = sarama.StringEncoder(jsonMessage)
}
o.producer.Input() <- &sarama.ProducerMessage{
Topic: o.config.topic,
Value: message,
}
return len(message), nil
}
+54
View File
@@ -0,0 +1,54 @@
package main
import (
"testing"
"github.com/Shopify/sarama"
"github.com/Shopify/sarama/mocks"
)
func TestOutputKafkaRAW(t *testing.T) {
config := sarama.NewConfig()
config.Producer.Return.Successes = true
producer := mocks.NewAsyncProducer(t, config)
producer.ExpectInputAndSucceed()
output := NewKafkaOutput("", &KafkaConfig{
producer: producer,
topic: "test",
useJSON: false,
})
output.Write([]byte("1 2 3\nGET / HTTP1.1\r\nHeader: 1\r\n\r\n"))
resp := <-producer.Successes()
data, _ := resp.Value.Encode()
if string(data) != "1 2 3\nGET / HTTP1.1\r\nHeader: 1\r\n\r\n" {
t.Error("Message not properly encoded: ", string(data))
}
}
func TestOutputKafkaJSON(t *testing.T) {
config := sarama.NewConfig()
config.Producer.Return.Successes = true
producer := mocks.NewAsyncProducer(t, config)
producer.ExpectInputAndSucceed()
output := NewKafkaOutput("", &KafkaConfig{
producer: producer,
topic: "test",
useJSON: true,
})
output.Write([]byte("1 2 3\nGET / HTTP1.1\r\nHeader: 1\r\n\r\n"))
resp := <-producer.Successes()
data, _ := resp.Value.Encode()
if string(data) != `{"Req_URL":"/","Req_Type":"1","Req_ID":"2","Req_Ts":"3","Req_Method":"GET","Req_Headers":{"Header":"1"}}` {
t.Error("Message not properly encoded: ", string(data))
}
}

Some files were not shown because too many files have changed in this diff Show More