mirror of
https://github.com/caddyserver/caddy.git
synced 2026-05-25 16:22:36 -04:00
Compare commits
1648 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7dc1dc1c78 | |||
| a3aa414ff3 | |||
| 54c63002cc | |||
| c555e95366 | |||
| 466269fd10 | |||
| 8653b70c32 | |||
| e363491a28 | |||
| b0685a64be | |||
| ff98aa3dd0 | |||
| c212365a3a | |||
| fea0d5ac3a | |||
| 9f16ac84a0 | |||
| 5874fbeb7e | |||
| 17e7e6076a | |||
| 9e98d6cd52 | |||
| 76f12f475b | |||
| 32fa0ce6a0 | |||
| 80eb45fcfb | |||
| 36f8759a7b | |||
| e2917784d0 | |||
| fec840a861 | |||
| d0bf3e1647 | |||
| b8722d9af3 | |||
| 7dc23b18ae | |||
| 9d398adf5d | |||
| 22a266a259 | |||
| 5a6b765673 | |||
| 8acf043297 | |||
| 98c17bcdf2 | |||
| 8c392a02c8 | |||
| 30337ac33f | |||
| b783caaaed | |||
| c972ea39c8 | |||
| 12fd349916 | |||
| dd4c4d7eb6 | |||
| 0cdaaba4b8 | |||
| 63f749112b | |||
| e19a007b38 | |||
| e85ba0d4db | |||
| b89cbe18e2 | |||
| 14500d8204 | |||
| a2900e46f4 | |||
| 08c17c7c31 | |||
| 49cb225cbd | |||
| 53e117802f | |||
| 23f89f30e9 | |||
| ff32ade1d8 | |||
| 3ce9075d3d | |||
| f2e999aab2 | |||
| 8cc3416bbc | |||
| c4d64a418b | |||
| f3108bb7bf | |||
| c2853ea64b | |||
| 561069fdb6 | |||
| 66a07773ab | |||
| a1dd6f0b34 | |||
| 2b9bbc5236 | |||
| 2f5e840ea9 | |||
| ab3cc8f961 | |||
| efb1c54e13 | |||
| 3c1957a612 | |||
| 2bd6fd0aea | |||
| f1342e37ed | |||
| 94af37087b | |||
| 5fcfdab6c7 | |||
| 016384abef | |||
| 036633b64a | |||
| 550b1170bd | |||
| d44016b937 | |||
| 4baca884c5 | |||
| d0455c7b9c | |||
| e5d33e73f3 | |||
| 9ced4b17e5 | |||
| b48bda4a6d | |||
| 5d9989405a | |||
| 733f622f7a | |||
| 20a54d0e07 | |||
| b5a07d43fa | |||
| 8561f42786 | |||
| e1ea58b7c4 | |||
| e9ce45ce61 | |||
| cc638c7faa | |||
| b766dab9fa | |||
| c885edda24 | |||
| bb7787d2ee | |||
| 8620581f95 | |||
| 99a6b2db67 | |||
| 8944332e13 | |||
| be1c57acfe | |||
| b06b3981cf | |||
| 8cb4e90852 | |||
| 871d11af00 | |||
| 6397a85e50 | |||
| d0ddfc849d | |||
| 617012c3fb | |||
| 4adbcd2565 | |||
| d01bcd591c | |||
| c9b022b5e0 | |||
| a661007a55 | |||
| 0c0142c8cc | |||
| 37f05e450f | |||
| 9b9a77a160 | |||
| 4670d13c8c | |||
| 9077cce126 | |||
| 76d9d695be | |||
| a4d70262aa | |||
| 79f2deee42 | |||
| bac54de9eb | |||
| 3f83eccfbd | |||
| d60a26ae30 | |||
| bbf954cbf2 | |||
| 73916ccc30 | |||
| fcad474064 | |||
| 4449d3dcd9 | |||
| c4a177bd3b | |||
| 8ecd543519 | |||
| 7af499c28b | |||
| 64fd281f5b | |||
| bedad34b25 | |||
| 0e7635c54b | |||
| 40a3a6b24f | |||
| 09a1f02971 | |||
| 8e54d5cecb | |||
| 7ef405f9b2 | |||
| 11bf28f783 | |||
| 98bba33861 | |||
| abdf13ea30 | |||
| a251831feb | |||
| 1ea96def31 | |||
| 635714fe38 | |||
| 5f135a27d5 | |||
| 45a3d0b526 | |||
| a122304196 | |||
| 14a6e4b4ed | |||
| 72e4ba8b5b | |||
| 1991083322 | |||
| 7ba804353c | |||
| ac933f1685 | |||
| 20ee457cae | |||
| 34a99598f7 | |||
| 191ec27c26 | |||
| b1ae8a71f1 | |||
| d4f4fcdb4c | |||
| ef58536711 | |||
| 17709a7d3f | |||
| 5a691fbaf5 | |||
| fd3008459e | |||
| e7af23e1e6 | |||
| 536daf36be | |||
| 5e0f4083c4 | |||
| c3e0733406 | |||
| 70cbfdc585 | |||
| 3dc98c8ce3 | |||
| 151d0baa94 | |||
| 9d947713ff | |||
| 1dfe1e5ada | |||
| 628920e20e | |||
| 15d25f1ca4 | |||
| 2ef8905966 | |||
| fdad616df7 | |||
| 590862a962 | |||
| 40c09d6789 | |||
| bba1059ef9 | |||
| 1d3212a598 | |||
| c75ee0000e | |||
| 8cdc65edd2 | |||
| a609fa5f56 | |||
| 78341a3a9a | |||
| fdc62d015f | |||
| e8e55955f4 | |||
| 8b8afd72d7 | |||
| c5524b0bab | |||
| c5aa5843d9 | |||
| 745ae6ff2f | |||
| 432a2d23a7 | |||
| 83345062d7 | |||
| f372f5fce7 | |||
| 454b1e3939 | |||
| 45ac11088e | |||
| eb3bbc409f | |||
| b830667a25 | |||
| ba5aeab19d | |||
| 441a8f5eff | |||
| 4f6500c95b | |||
| 7dd385f6b4 | |||
| ac0dd303be | |||
| 676202a31e | |||
| c8a99d2f81 | |||
| 8e8e2f596d | |||
| f7003bee3f | |||
| 532ab661c7 | |||
| 68be4a9161 | |||
| 46bc0d5c4e | |||
| 8e75ae2495 | |||
| d56ac28bec | |||
| 3fd8218f67 | |||
| d06c15cae6 | |||
| 59b1e8b0bc | |||
| dbd76f7a57 | |||
| e081d8b5c2 | |||
| 8eefeb6788 | |||
| 5fb3c504c9 | |||
| 0f04f2fd44 | |||
| ce8b1dfe94 | |||
| 4b3c532573 | |||
| 4d76ccb1c4 | |||
| de7bf4f241 | |||
| 681c95a749 | |||
| e5a8927635 | |||
| 2019eec5a5 | |||
| 33d1033928 | |||
| 0d8b95334f | |||
| ee615371a8 | |||
| 4c6082df64 | |||
| 8898066455 | |||
| fffc1bed73 | |||
| 824ec6cb95 | |||
| 5b5e365295 | |||
| c6c221b8db | |||
| 985049e0c2 | |||
| 3a4f8e8d0c | |||
| f3a3bf6204 | |||
| 81a3101efe | |||
| 22a4b6cde2 | |||
| 94c63e42d6 | |||
| c110b27ef5 | |||
| 6e9439d22e | |||
| f4cdf53761 | |||
| 89f5b646c3 | |||
| a24e361761 | |||
| 5ac04b91bb | |||
| 1b1aecb1e6 | |||
| 3d43c5b697 | |||
| d534a2139f | |||
| c4e65df262 | |||
| 88d3dcae42 | |||
| db4cd8ee2d | |||
| da5b3cfc50 | |||
| 372c77da3a | |||
| 251c38bfb2 | |||
| ba1bee2b8f | |||
| b64894c31e | |||
| d88dd74dec | |||
| 7157bdc79d | |||
| 72af3f8256 | |||
| c8daaba4be | |||
| af48bbd234 | |||
| 1e1e69b90f | |||
| cf1b355d30 | |||
| 1dd413bd69 | |||
| 1bbad72ff1 | |||
| b2aed643f4 | |||
| 62e8c4b76b | |||
| 6490ff6224 | |||
| 57710e8b0d | |||
| 4678471fe0 | |||
| d746b95906 | |||
| 3c8b2b5954 | |||
| cf3ce49104 | |||
| ca3d23bc70 | |||
| e7c842215e | |||
| beae16f07c | |||
| 1240690973 | |||
| b35d19d78e | |||
| cf4e0c9c9c | |||
| ac97cf426f | |||
| f28af63732 | |||
| 38c2463416 | |||
| df018ea64a | |||
| 4ff46ad447 | |||
| 59c6513b31 | |||
| aede4ccbce | |||
| 9315738dab | |||
| 502a8979a8 | |||
| d6110f8e9e | |||
| d7698ecf13 | |||
| 9ea0591951 | |||
| ffafb2eca8 | |||
| 6bb1e0c674 | |||
| 6f37e9d31b | |||
| b58872925a | |||
| 8d7136fc06 | |||
| 2125ae5f99 | |||
| 3fd3feeffe | |||
| 62622eb853 | |||
| 87c389f73d | |||
| cf03c9a6c8 | |||
| 48abb41135 | |||
| 7eb4bb8e1c | |||
| 39e55072d7 | |||
| 88a2811e2a | |||
| 065eeb42c3 | |||
| d4b10b69a7 | |||
| f77264b776 | |||
| ad2ed5b0ae | |||
| fdb6d64f9d | |||
| 227664336e | |||
| 32329a473d | |||
| e5bf8cab24 | |||
| 6db4771aa8 | |||
| b1cd0bfeff | |||
| 2e84fe4504 | |||
| d2be213e10 | |||
| a1bc94e409 | |||
| 80dd95a495 | |||
| 5a45719227 | |||
| 345ece3850 | |||
| 2b44a7d052 | |||
| 58085edc16 | |||
| 6f05faa670 | |||
| eddb6f0a79 | |||
| 70b75d1433 | |||
| 15fa5cf2da | |||
| e74678ed43 | |||
| d84c823855 | |||
| b49f65d5de | |||
| fd8fe24bcb | |||
| 281603895b | |||
| fbad4e15c2 | |||
| ab301fec00 | |||
| deec149891 | |||
| 9ca87cd139 | |||
| cad9b3f62f | |||
| e585a74115 | |||
| d9b6563d88 | |||
| 0a3f68f0d7 | |||
| e625c7c051 | |||
| 937654d1e0 | |||
| 33aba7eb91 | |||
| d252d40681 | |||
| 81c4ea6be7 | |||
| 1fdc46e571 | |||
| a798e0c951 | |||
| 07b7c99965 | |||
| 807617965a | |||
| a50462974c | |||
| 6fe5c1a69f | |||
| 54355d8fb3 | |||
| e486c9c6e7 | |||
| 0f1e5bcebf | |||
| fee4890e94 | |||
| b14baf7e20 | |||
| 2b06edccd3 | |||
| 492d5aa37f | |||
| 1e4a4109a7 | |||
| daa4de572e | |||
| 83451ea2a0 | |||
| 06fed0db17 | |||
| 98cf26377c | |||
| ff82057131 | |||
| 6492592b4a | |||
| 6c847d0723 | |||
| 01e05afa0c | |||
| e7fc26e3fb | |||
| 37ae21001d | |||
| b23eec4fac | |||
| 727ef24306 | |||
| d3860f95f5 | |||
| 9b4134b287 | |||
| ddff08392a | |||
| 71c14fa16e | |||
| ff22fbd79a | |||
| a762dde145 | |||
| 416af05a00 | |||
| 2f92443de7 | |||
| 49fdc6a20a | |||
| ac4fa2c3a9 | |||
| e1a6b60736 | |||
| 9b5ad487d7 | |||
| d291b76721 | |||
| 881da313dd | |||
| 1bdbf9d6ba | |||
| 2536ea74d9 | |||
| 9acfec5418 | |||
| a0e6eb3ba9 | |||
| 6e6d9e7e9e | |||
| 238250e7e6 | |||
| 324ec15890 | |||
| c64361a753 | |||
| 6d9dcb1729 | |||
| da97ac7c63 | |||
| 374d0a3f09 | |||
| bee9c50a71 | |||
| bac29cc20a | |||
| e6b1028da9 | |||
| 4c62397ff8 | |||
| e516aebc08 | |||
| da8ae9e511 | |||
| d377c79a5d | |||
| 389a6eb344 | |||
| 85d793ce88 | |||
| 1f29c52151 | |||
| 9705f34970 | |||
| db21b0319d | |||
| 25b934824f | |||
| c23c6d9cb4 | |||
| 9697c47e21 | |||
| 39030d9e1b | |||
| 61c7a51bfa | |||
| 45e783c3f9 | |||
| 2bccc1466e | |||
| a3af232dc5 | |||
| 04089c533b | |||
| e0bc426050 | |||
| bd2a33dd14 | |||
| 20dfaab703 | |||
| 249c9a17f5 | |||
| c431a07af5 | |||
| e2234497b7 | |||
| 96425f0f40 | |||
| d05dac8d2e | |||
| 81e26970a3 | |||
| f561dc0bc1 | |||
| 21382702d2 | |||
| e97649493b | |||
| 19d6f666aa | |||
| 6f5cff5393 | |||
| 5c96ee1d9c | |||
| 3c578dfbc1 | |||
| a093aea797 | |||
| 9f1762873a | |||
| c3417a0757 | |||
| 72bc6932b0 | |||
| a41e3d2515 | |||
| 7f35600b28 | |||
| cc6aa6b54b | |||
| 239f6825f7 | |||
| 1d38d113f8 | |||
| 6908136092 | |||
| da016f8d5a | |||
| 2f2d357fb6 | |||
| 924b53eb3c | |||
| 2b51be7fd7 | |||
| 376e1090a3 | |||
| dd4de698cf | |||
| a682100c5e | |||
| aba3d37c88 | |||
| 0890e330e2 | |||
| 19a85d08c6 | |||
| 5a0d373fcd | |||
| ecf91f525f | |||
| b541c717ca | |||
| c05c5163e2 | |||
| 3513b6f2f7 | |||
| 4a6121f989 | |||
| e652d12cfc | |||
| b97a7909d8 | |||
| 7c9867917a | |||
| a762bec06d | |||
| b75016e646 | |||
| ddf4b1fd3b | |||
| 69c2d78f69 | |||
| f31875dfde | |||
| 4e98cc3005 | |||
| d3a77ce3c3 | |||
| 48d294a695 | |||
| b149a86bc2 | |||
| ac80f6edc3 | |||
| ef95173827 | |||
| 36a3e204b6 | |||
| e0b63d92f4 | |||
| 004a7f84ef | |||
| ed8a48e7f1 | |||
| c86c26a056 | |||
| 0a7ca64f53 | |||
| c4e2cf96e7 | |||
| 42b7d57421 | |||
| c64cf218b0 | |||
| 027f697fdf | |||
| 6a7b777f14 | |||
| 67b137175e | |||
| dfa3b8645d | |||
| 2dca50dee8 | |||
| 3faad41b43 | |||
| c21ff8343c | |||
| 2072eec11f | |||
| 497ebb9ccb | |||
| e4e773c9ea | |||
| 32e63e6b94 | |||
| 86ccafbe58 | |||
| 3ef78d3db3 | |||
| 9ec1c17846 | |||
| 7ababfc909 | |||
| 31062dd6c2 | |||
| b952fd8f8f | |||
| 28e0bfbbbe | |||
| 30ce73e8fb | |||
| 987a5f98c4 | |||
| 859a93d296 | |||
| a14fce0b1e | |||
| 25b567b301 | |||
| 3d066789d3 | |||
| 93d982a5a4 | |||
| 572b9e4d67 | |||
| 2a82f7b520 | |||
| 1a9f700287 | |||
| 462128cd80 | |||
| cf69d190a2 | |||
| 3441cdef64 | |||
| 8a2f2f8d37 | |||
| 86854dca89 | |||
| b3a5b725db | |||
| f28d8b8601 | |||
| 5989eb0635 | |||
| cbd9b814b9 | |||
| 32dbbfd64c | |||
| 3395f6c775 | |||
| 61cf8b79bc | |||
| bb6764fd22 | |||
| c981b08b23 | |||
| 7271b57136 | |||
| 874bcff564 | |||
| eb279e7e8a | |||
| f4c729bd22 | |||
| ea35893be4 | |||
| 1efd1029dd | |||
| 426d165254 | |||
| a3127bed5f | |||
| b94e513116 | |||
| b6e5a599fb | |||
| 8fc35edc3b | |||
| 260c023e1e | |||
| 27f9b58c5d | |||
| f23d8cb37f | |||
| 3f49b32086 | |||
| 0aacaea918 | |||
| 9e0b1b4216 | |||
| e7001e6538 | |||
| 4d9741dda6 | |||
| 74a5cb2fe3 | |||
| ba2e9d80fd | |||
| a05a664d56 | |||
| 9f9fbf2e1b | |||
| 63e4352db7 | |||
| 640a0ef956 | |||
| 591b209024 | |||
| f1c1ea9905 | |||
| 6b801b111b | |||
| 717c88ec0f | |||
| 03a22aeb7e | |||
| 18332df358 | |||
| b9f8c183fa | |||
| 37d050922b | |||
| 04514fb791 | |||
| 6c2bf36dab | |||
| 4f5fe2de24 | |||
| 90c24d2f32 | |||
| d95c21ded5 | |||
| 4f4b34d481 | |||
| ed0342f171 | |||
| f14cdcc436 | |||
| b471b7e835 | |||
| b79ff7403f | |||
| 7560778602 | |||
| fc10951dde | |||
| 3e48e6a535 | |||
| 44fc9b18a6 | |||
| 3b6c387b84 | |||
| 35e4c1a7bf | |||
| 25bfdfe92c | |||
| 008ad398ce | |||
| 52d7379063 | |||
| e92a911e7d | |||
| 84845a66ab | |||
| e2f6ab3472 | |||
| f3a183ecc1 | |||
| e958686ae4 | |||
| 1f7d8d8ab0 | |||
| a7766c9033 | |||
| ce8ee831b3 | |||
| 741d7685f1 | |||
| 88e3a26c99 | |||
| f52b1e80f5 | |||
| 202679efde | |||
| 75915e0a25 | |||
| 9e386fc921 | |||
| 9099375b11 | |||
| 36b440c04b | |||
| 2a46f2a14e | |||
| 741880a38b | |||
| 43c339c7e3 | |||
| 49c2807ba1 | |||
| da08c94a8c | |||
| c827a71d5d | |||
| 2ecc837020 | |||
| c37ad7f677 | |||
| 737c7c4372 | |||
| 367397dbd6 | |||
| a2dbfdc10e | |||
| ef5f9c771d | |||
| 05957b4965 | |||
| 72fcdec8d8 | |||
| f4bb43781c | |||
| 197297b0d7 | |||
| a541eb7899 | |||
| 2ea6c95ac4 | |||
| c7674e2060 | |||
| c12847e5ba | |||
| bec130a563 | |||
| 09b7ce6c93 | |||
| b860be01bb | |||
| f7b5187bf3 | |||
| 09a7af8cae | |||
| 5f2670fdde | |||
| ecf913e58d | |||
| d05f89294e | |||
| 1ef7f3c4b1 | |||
| f25ae8230f | |||
| 1cfd960f3c | |||
| 2dba44327a | |||
| cae9f7de9c | |||
| a11e14aca8 | |||
| dc63e50172 | |||
| 04c7c442c5 | |||
| 7bd2adf0dc | |||
| 1fe39e4633 | |||
| 216a617249 | |||
| d25a3e95e4 | |||
| 11103bd8d6 | |||
| f1ba7fa343 | |||
| 7091a2090b | |||
| 57ffe5a619 | |||
| b1208d3fdf | |||
| b089d14b67 | |||
| e72fc20c78 | |||
| 5b7e0361dd | |||
| 86f36bdb61 | |||
| 3278106421 | |||
| f9b8e31ad7 | |||
| fbdfc979ec | |||
| 2acaf2fa6f | |||
| f4fcfa8793 | |||
| 79db939259 | |||
| f9b6ede92b | |||
| 184abe3bc8 | |||
| fde9bbeb32 | |||
| c59fd1c76e | |||
| 600ee9a89f | |||
| c5983e305f | |||
| 8d057c8614 | |||
| ac197f1694 | |||
| d8be787f39 | |||
| a8c8b48390 | |||
| 4d4ea94465 | |||
| aeaf58b16a | |||
| 73ed286309 | |||
| 9e900b0a08 | |||
| f1b2637d44 | |||
| 178c4d11d9 | |||
| 7613ae3bf0 | |||
| ad664e5bba | |||
| cf06abd691 | |||
| a6abec8210 | |||
| 82b049229b | |||
| fae612d53b | |||
| bae4ac9764 | |||
| 6e340cb1d6 | |||
| 0d8d0ba5a0 | |||
| 8655ea671b | |||
| 0d8526b7d9 | |||
| c9e0517e5e | |||
| e74558eaea | |||
| b0ccab7b4a | |||
| 47079c3d24 | |||
| b4cab78bec | |||
| 3c96718027 | |||
| 4b6e0e9369 | |||
| 2bcbdd6a17 | |||
| 8f2196c047 | |||
| c7d4d051cb | |||
| e283af4d9b | |||
| 12cd2d528c | |||
| 8a6c778c8d | |||
| 77eae62d9f | |||
| 97c8c9582a | |||
| ed0c0db6a3 | |||
| 202849055c | |||
| 060ab92d29 | |||
| 0830c728fe | |||
| dab679df86 | |||
| 9453224639 | |||
| fd1765973a | |||
| 0efe39a705 | |||
| a3f3bc67e1 | |||
| 8b93bfe751 | |||
| 897b6c5b0e | |||
| fc928e0b3b | |||
| 93b301372b | |||
| ce4981d046 | |||
| 62b210b544 | |||
| 5f6a0a4c0b | |||
| cae9880800 | |||
| 6d49392602 | |||
| 4593982065 | |||
| 94100a7ba6 | |||
| e9c2e50684 | |||
| 82b0c0b9eb | |||
| 55601d3ec2 | |||
| 829a0f34d0 | |||
| bb80f99190 | |||
| 946ff5e87b | |||
| 0a04fa40f4 | |||
| 48d7f1ead2 | |||
| be2f5c4b38 | |||
| 281007c482 | |||
| b6326d402d | |||
| e2a3ec4c3d | |||
| 3468986260 | |||
| 55f69fd742 | |||
| 1af7865e6c | |||
| 4636ca1051 | |||
| 94e3e7e5eb | |||
| 3c086fb2e6 | |||
| 55aa492dc1 | |||
| 7dadcd5834 | |||
| 73327e784d | |||
| bb23f68a43 | |||
| 6a27968f73 | |||
| 1e7ec3397b | |||
| 168723a026 | |||
| 92bd914418 | |||
| 9110dc4745 | |||
| 1ed786f836 | |||
| 4d5bc9fa6c | |||
| 98d8c0f81b | |||
| 32b8857eea | |||
| 9e163a655d | |||
| 4d867e848b | |||
| c748ef944b | |||
| 55d22f4ead | |||
| 3f787a20e3 | |||
| 6276be4e90 | |||
| f639d3cd68 | |||
| 43020533f7 | |||
| a5836aebfa | |||
| 3dd4c0eb6a | |||
| 1e27b5be89 | |||
| a946d65fe6 | |||
| f04ff063ed | |||
| 35ec61cc88 | |||
| 8f23c430ae | |||
| 5eadea6615 | |||
| 34d3cd7c92 | |||
| f11cd4d9dd | |||
| a8c9d47805 | |||
| 3966936bd6 | |||
| b7fd1f4e9e | |||
| b0397df719 | |||
| eb48885d4d | |||
| afbda595f6 | |||
| b65ddbc750 | |||
| aba0ae358e | |||
| 2e295b51b3 | |||
| 59dbea768c | |||
| a44d59f1e5 | |||
| e4ff77ed07 | |||
| b6c4178f0a | |||
| 23631cfaca | |||
| 8631f33940 | |||
| ab5087e215 | |||
| d56a9a1c5d | |||
| 41bdd77545 | |||
| b7827a342a | |||
| e17a18365d | |||
| d1216f409d | |||
| 12f594779c | |||
| b3f5e4d4ad | |||
| 5b93799a62 | |||
| fd14f257df | |||
| d044e497f6 | |||
| 6f4835f91a | |||
| 9002db2ae0 | |||
| 19c6bbf6a2 | |||
| ef2ca1da3d | |||
| fbc18c5b85 | |||
| d93fe53e84 | |||
| 0a40970dea | |||
| 6478eee338 | |||
| a60c739797 | |||
| 19ca7d812e | |||
| bc37cf0d1c | |||
| 78b95deb55 | |||
| b787569820 | |||
| 016344bae7 | |||
| 0b51369932 | |||
| 1fb66d534a | |||
| f0b1edaf8c | |||
| 4dbb4274d9 | |||
| 9886e89e42 | |||
| 3e402e0692 | |||
| 0a1721d5b2 | |||
| 4d907d57fa | |||
| 24352e799a | |||
| e17d43b58a | |||
| 580b50ea20 | |||
| 659df6967e | |||
| b9244cdf2e | |||
| a2ba00bdc8 | |||
| 1d47e590e5 | |||
| 280ba9db85 | |||
| 7f98a6cccf | |||
| a5b117fcdf | |||
| f56d2090b6 | |||
| 37e3cf684d | |||
| 7949388da8 | |||
| dd119e04b1 | |||
| f7cfe79905 | |||
| 3dc5e0e181 | |||
| 1ca34c4ecf | |||
| 837ee9f042 | |||
| d448c919e8 | |||
| 7d5b6b96ea | |||
| 7b064535bf | |||
| b42334eb91 | |||
| 94c746c44f | |||
| 7d46a7d5f4 | |||
| 9e2cef38f6 | |||
| e166ebf68b | |||
| 33b1d4c55d | |||
| ae2e0900c1 | |||
| 91ac2c58fa | |||
| 69662d4d7d | |||
| fc6afe2a8b | |||
| 51d2ff4e47 | |||
| d46967d1e2 | |||
| 4d78013646 | |||
| 5cced604e4 | |||
| a39ed2823e | |||
| 4bed399ca4 | |||
| 93c330c4ce | |||
| 76ec785e87 | |||
| e9b9432da5 | |||
| c31e86db02 | |||
| 13557eb5ef | |||
| 02213402e8 | |||
| e1f23a1eb7 | |||
| 485af2c6ba | |||
| 171fd34b3c | |||
| 1017142d9b | |||
| be9f644425 | |||
| 8628a50b7d | |||
| 161db70c15 | |||
| e7b8be31cf | |||
| e56f7affc9 | |||
| 2b1cc77f4b | |||
| 18e9aa4d57 | |||
| cf5aa1bed1 | |||
| c35b201685 | |||
| a1481bc29e | |||
| d34e92ee70 | |||
| bcea5182c6 | |||
| 2fb4810cdb | |||
| 411dd7dff5 | |||
| 96f04cdc38 | |||
| b963c7c9ac | |||
| fc7f7dffa8 | |||
| 47c5b6c9c4 | |||
| 8774c90709 | |||
| 01465932e7 | |||
| 72c0527b7d | |||
| e23af5e99a | |||
| 57f1d3c205 | |||
| 7a159ad934 | |||
| 6fdc83faeb | |||
| d36685acdd | |||
| 051d2a68c0 | |||
| 34c369155c | |||
| 7f7a6abafd | |||
| 5e1573dd84 | |||
| e8006acf80 | |||
| 295d21f37d | |||
| 866427491c | |||
| 9905f48c8e | |||
| 0970c058f7 | |||
| ad057ab873 | |||
| 09341fca12 | |||
| c3e6463676 | |||
| d18cf12f14 | |||
| abc7c6a148 | |||
| b143bbdbaa | |||
| be0fb0053d | |||
| 2712dcd1f5 | |||
| cac58eaab9 | |||
| 9a4e26a518 | |||
| a729be295a | |||
| b6078eded1 | |||
| ea642f6e1d | |||
| 4d71620cb0 | |||
| e4028b23c7 | |||
| 96c7c2768c | |||
| 78d857a374 | |||
| 19148eba44 | |||
| 6a32076271 | |||
| ef617f9ce4 | |||
| 3843cea959 | |||
| dd1c49bde9 | |||
| e99b3af0a5 | |||
| 88c646c86c | |||
| 64cded8246 | |||
| e3be524447 | |||
| a62a7f7cf1 | |||
| 9d456bba9b | |||
| 89ad7593bd | |||
| d227bec0ff | |||
| a3f0fff734 | |||
| efeeece735 | |||
| 234783548f | |||
| 5a29107f3b | |||
| 976f5182e1 | |||
| 30c949085c | |||
| 6762df415c | |||
| 1818b1ea62 | |||
| b67543f81c | |||
| 94ff7dc6fb | |||
| cc229aefae | |||
| 7d91cfb512 | |||
| 8548641dc1 | |||
| c46898592f | |||
| 362ead2760 | |||
| a6ea1e6b55 | |||
| 0f19df8a81 | |||
| ee5c842c7d | |||
| c487b702a2 | |||
| bb6613d0ae | |||
| 821c0fab09 | |||
| 5b1962303d | |||
| 41c4484222 | |||
| 4ebff9a130 | |||
| 6936658019 | |||
| b5b31e398c | |||
| f9f1aafe0c | |||
| d1b667fbce | |||
| 91465d8e6f | |||
| f8ad050dda | |||
| 0d004ccbab | |||
| 2e5eb63850 | |||
| f24ecee603 | |||
| c5635f21a3 | |||
| 605f1942ef | |||
| fec491fb12 | |||
| 794d271152 | |||
| 29362e45bc | |||
| a16beb98de | |||
| 38885e4301 | |||
| 136119f8ac | |||
| e3ec7394ab | |||
| ddd69d19c0 | |||
| 8ecc366582 | |||
| 4db54f8ddc | |||
| 8f9f6caa4e | |||
| 7e41f6ed62 | |||
| 159eb68a11 | |||
| 815231b1e0 | |||
| 0feb0d9244 | |||
| 1db138ed55 | |||
| 4c0d4dd780 | |||
| c626774da2 | |||
| acf43857a3 | |||
| e2f6c51fb0 | |||
| c4a7378466 | |||
| a17e9b6b02 | |||
| f978967e5e | |||
| fc413e2403 | |||
| 38719765bf | |||
| f3596f734d | |||
| 1d15fe069a | |||
| 72a5579d83 | |||
| cd0b47d068 | |||
| 4c93ab8c68 | |||
| c0ebe31560 | |||
| cc1ff93250 | |||
| 42ac2d2dde | |||
| d764111886 | |||
| 8cd6b8aa99 | |||
| da8a4fafcc | |||
| 9f9de389d5 | |||
| 7568b0e215 | |||
| a75663501d | |||
| 96ae288c4b | |||
| a3a826572f | |||
| fe7ad8ee05 | |||
| 3614a093e3 | |||
| 6325bcf5b2 | |||
| 307c2ffe3c | |||
| 06913ab74f | |||
| 506630200b | |||
| df194d567f | |||
| 9727603250 | |||
| a0c8428f8c | |||
| dd91812b11 | |||
| 10619f06b4 | |||
| 0a1e472fc2 | |||
| 4e92c71259 | |||
| 2236780190 | |||
| 3faffdce2d | |||
| d6242e9cac | |||
| 691204ceed | |||
| bd4d9c6fe2 | |||
| 3440f5cfbe | |||
| a518049fa2 | |||
| 35e309cf87 | |||
| e0fdddc73f | |||
| 0c07f7adcc | |||
| a48ed9a246 | |||
| d4a14af14d | |||
| f7e3ed13f9 | |||
| 71c4962ff6 | |||
| b713a7796e | |||
| 65e812d3a9 | |||
| 5c3085fe51 | |||
| 6af26e2306 | |||
| a914565f51 | |||
| 24893bf740 | |||
| 26cbea9e12 | |||
| f7fcd7447a | |||
| 16bd63fc26 | |||
| e158cda057 | |||
| 7121e2c770 | |||
| f122b3bbdf | |||
| 6717edcb87 | |||
| dee2e8e67d | |||
| 4544dabd56 | |||
| 222781abca | |||
| 55a098cae8 | |||
| 837c17c396 | |||
| f9bc74626d | |||
| 17c91152e0 | |||
| d414ef0d0f | |||
| e66aa25fce | |||
| 75d82e8666 | |||
| af42d2a54a | |||
| f5cd4f17f8 | |||
| 02c7770b57 | |||
| 0f049856a4 | |||
| bd14171b88 | |||
| e6ba930e65 | |||
| 61a6b9511a | |||
| 87efc67f48 | |||
| 9e2da6ec48 | |||
| 3f9f675c43 | |||
| 698399e61f | |||
| ec676fa15e | |||
| 122e3a9430 | |||
| 79a7f8a460 | |||
| bb85a84561 | |||
| be6fc35326 | |||
| 79de2a5de2 | |||
| ca1f1362cc | |||
| 0ca0d552eb | |||
| 8baead6107 | |||
| 4f5a29d6d1 | |||
| da7562367c | |||
| 6001c94f30 | |||
| 104a5998cb | |||
| 6cbd3ab096 | |||
| 7f9fa5730b | |||
| bdccc51437 | |||
| 0e039a1868 | |||
| 10ab037833 | |||
| 540a651fdf | |||
| ee893325c4 | |||
| 8120e57850 | |||
| 043e000459 | |||
| 66fb8f031b | |||
| 9e2bef146e | |||
| 4c642e9d3c | |||
| 30b19190dc | |||
| 840bc505f6 | |||
| 8c843ceefd | |||
| aa5a595762 | |||
| 9dfb940d80 | |||
| 1dbfeb7ecd | |||
| f4054b6954 | |||
| faaef83954 | |||
| 287543a0e6 | |||
| 7545755b00 | |||
| 26dc212f4c | |||
| a5128da67a | |||
| 37eedf5cdc | |||
| f2e680430a | |||
| 740a6a7ad5 | |||
| 1236e492a9 | |||
| 80db177f5a | |||
| 3d1cac313c | |||
| dc4a5ae1fd | |||
| da7b9a6bbc | |||
| 55de037035 | |||
| c468b114e4 | |||
| d96bd5269a | |||
| ed4148f20e | |||
| f8e2cc8008 | |||
| 5d32af8a6b | |||
| ed10863494 | |||
| 4e1717db4c | |||
| 159b68aab4 | |||
| d76cf6d337 | |||
| 69950e57f0 | |||
| d44ab3dbab | |||
| b199825c3b | |||
| 94becb89f6 | |||
| 1f4231e1f0 | |||
| bdcbd11d65 | |||
| 008160998a | |||
| 1cafb1eea5 | |||
| 392f1d70eb | |||
| d79d2611ca | |||
| e3cea042d6 | |||
| 679668e3c0 | |||
| 730269743f | |||
| bfc61824b9 | |||
| 444f9e40d5 | |||
| c5006321a7 | |||
| b9d3e7721e | |||
| 49a229835a | |||
| 414b47d653 | |||
| b62d087bb6 | |||
| 4704625e3a | |||
| 53c4797606 | |||
| 60b6c0c03d | |||
| 5f3ef9c0da | |||
| bb5a322ce2 | |||
| bb072faeee | |||
| a2be7b4548 | |||
| 7796ff0f69 | |||
| afd6b7ea27 | |||
| b62de4c521 | |||
| 2e8a74ecff | |||
| e94e90b046 | |||
| 7173764d6d | |||
| e4643f048a | |||
| 236c8c4eaf | |||
| 3b910645e7 | |||
| 9669363504 | |||
| b5d79bdccc | |||
| 1d3d705aae | |||
| 2ab466599d | |||
| 851026d3fa | |||
| 32da2ed706 | |||
| d8c50264cc | |||
| 8d81ae88da | |||
| f1f1eb040a | |||
| 36fa6e857b | |||
| b401267aa4 | |||
| e63b83c8c4 | |||
| 0ac8bf58ea | |||
| 7fb1c7e91d | |||
| 60690c78ae | |||
| 4b92808bbf | |||
| 73397a0973 | |||
| 35e25be1a4 | |||
| f7129b219e | |||
| e1153f8797 | |||
| ff28bc8b0a | |||
| 0b01489f7d | |||
| 7a69770026 | |||
| ec51e14451 | |||
| 86e9749d6c | |||
| aa89f30f2a | |||
| da794a866e | |||
| 705cd16dee | |||
| 0168a627a4 | |||
| 7b29568eb1 | |||
| a585379bbb | |||
| e240cd5ba2 | |||
| e043bbdd62 | |||
| 094436c23a | |||
| c6b2600c62 | |||
| d1eb2ea9e2 | |||
| 453d3eb567 | |||
| 53b7b131cb | |||
| bec9b9a3f7 | |||
| bf47951f3a | |||
| 604c8abb59 | |||
| ef4a4b0ab8 | |||
| 24bdb433c9 | |||
| 6006de5795 | |||
| a578c43810 | |||
| 74b758034e | |||
| 04571ff393 | |||
| 7adff28aa9 | |||
| 1589129ea1 | |||
| 97dcc79a7f | |||
| bc2feece4b | |||
| 1f17895b12 | |||
| 665f24d85f | |||
| 2df30d186e | |||
| 6451e10d3e | |||
| d222a9e9f2 | |||
| 00997db5ae | |||
| 2d5320c454 | |||
| 2fa6e278d2 | |||
| ef381fbb54 | |||
| a74b20f278 | |||
| f536bc94b2 | |||
| 95140f948f | |||
| afc540f6b7 | |||
| fcf2622c26 | |||
| d9ebc5398a | |||
| eea68c34ad | |||
| 8a2d0890a2 | |||
| 1a82943db2 | |||
| 3c36edec1f | |||
| 0f913e89db | |||
| 2b7ec1b023 | |||
| 33fa29fda0 | |||
| d3c229375c | |||
| c82d7c2dd2 | |||
| 553d76dab3 | |||
| d4f0ac2303 | |||
| 4588812d24 | |||
| 9467dbdd40 | |||
| 68c416e414 | |||
| 71c4fdbc85 | |||
| 7dbe42286d | |||
| b5579ca910 | |||
| cd2b255ae3 | |||
| 93f29a7598 | |||
| 32ef35b952 | |||
| abf22909f1 | |||
| a86e16ddde | |||
| 263fa064cd | |||
| 915172e9ef | |||
| 4d066b7e30 | |||
| a7f0705bcf | |||
| 16f18bfeff | |||
| 7a42e60bcb | |||
| aecdecbdf8 | |||
| a790db134d | |||
| 75b77d508d | |||
| 4240817a3a | |||
| 24307e85b7 | |||
| b030d0cf79 | |||
| b0d3a8e1b5 | |||
| 62456c1bed | |||
| 3f1f6720ee | |||
| ab0cbf3e12 | |||
| c12257a1a7 | |||
| e039577d66 | |||
| 9995466a18 | |||
| f424f450f2 | |||
| 677f67db48 | |||
| 47d1f5eecf | |||
| d8391d6fbd | |||
| 640cd059ce | |||
| a78cea7d8a | |||
| 7044cbbd67 | |||
| 292c15cd48 | |||
| 06a7f1d3da | |||
| efbf01b49d | |||
| 4b349805db | |||
| 47096e112a | |||
| 68add78230 | |||
| ebae65b6af | |||
| 460c0c8a42 | |||
| 528d1b03f1 | |||
| 9d33d9d6b0 | |||
| d9729b4a2e | |||
| 1db6c244bb | |||
| 13c5d25a2e | |||
| c166261513 | |||
| 84998a4d19 | |||
| 6b27d4ce11 | |||
| f11e136068 | |||
| 707ea554ac | |||
| 65f7190030 | |||
| a5a5c06716 | |||
| 9c832893af | |||
| 4e15901df1 | |||
| 9a32d08e9f | |||
| c811d416a7 | |||
| 92391bfdf9 | |||
| 6c1f2af53a | |||
| 7875f98b71 | |||
| 076fc4d72c | |||
| d7db1b9576 | |||
| 2a166f088d | |||
| 2175c68319 | |||
| 3418770fe1 | |||
| d7051e986f | |||
| f36d9bfa2a | |||
| e79a88856a | |||
| db2368cd0b | |||
| 0f9d26829c | |||
| 29404e34d9 | |||
| 14b64fef43 | |||
| e0f10c2b03 | |||
| 01aca02edc | |||
| 5cdfa0aaaf | |||
| 90921a9deb | |||
| d6a7dfc1a5 | |||
| 00093a2052 | |||
| 3a795de828 | |||
| cde60ed6b2 | |||
| b717e6f2d8 | |||
| 3aff1677cc | |||
| 9e97d79c81 | |||
| 47415937dd | |||
| aed649475e | |||
| 41e1f1ffa5 | |||
| 20b6e971c0 | |||
| c42e60a3d2 | |||
| 995a2ea618 | |||
| 13db60d382 | |||
| c9233d7446 | |||
| 6080c4fab1 | |||
| 820b2af43a | |||
| 1cb0053720 | |||
| 822a615c6c | |||
| 593557659c | |||
| c6e2b9ccc0 | |||
| b4780a41d3 | |||
| 4790dacbf7 | |||
| 4852f0580b | |||
| 9d7639a9d3 | |||
| 6c52368124 | |||
| c78eb50eb8 | |||
| 9ce0e8e17c | |||
| 32825e8a79 | |||
| cb8691a381 | |||
| 5ddcd60332 | |||
| 68cd4bdeab | |||
| ccd3e55b32 | |||
| 56ec7b9887 | |||
| 2d6ff40649 | |||
| 9bdd9bdecc | |||
| dd946f8ab5 | |||
| 593aec9ab1 | |||
| 6b173b5170 | |||
| 130301e32e | |||
| 2013838bfd | |||
| 879558b9ee | |||
| ee059c0910 | |||
| 6c6e0e3f73 | |||
| b1c8b48e6e | |||
| 6f05794bb8 | |||
| 346135fed3 | |||
| 69939108e1 | |||
| 674f454e70 | |||
| a881838836 | |||
| e4b50aa814 | |||
| fd8490c689 | |||
| d0a51048d7 | |||
| 506f131428 | |||
| e42c6bf0bb | |||
| 535f956682 | |||
| 4e94b85ec2 | |||
| 6b3b04ffb7 | |||
| 36bc3a453f | |||
| 99c069df15 | |||
| 04fd7ce9e1 | |||
| cc958947e5 | |||
| f44cd5d740 | |||
| bba2d63de8 | |||
| 3420bd6e06 | |||
| b10d846019 | |||
| 11ddb5c6ca | |||
| b37fed4cc8 | |||
| 5397eef234 | |||
| d311345aa5 | |||
| d6df615588 | |||
| ce6e30c09e | |||
| ee754b4a47 | |||
| 5f72b7438a | |||
| ea9607302a | |||
| 26bb17337e | |||
| 5e8491cf7f | |||
| e42c6ab520 | |||
| 9c039474b3 | |||
| b378316103 | |||
| a94c7dd788 | |||
| 823a7eac03 | |||
| cf2808ae45 | |||
| c382c885e4 | |||
| 7ae9e3a262 | |||
| 74d162f377 | |||
| ad7b453f03 | |||
| b2afc30d12 | |||
| 1076daa8c9 | |||
| 8394d72f48 | |||
| 018fd21741 | |||
| a1312465b5 | |||
| e2273ea676 | |||
| c6eaf0db36 | |||
| a0eca49795 | |||
| e0173ec4c7 | |||
| 99fa4581aa | |||
| 37b1a81fc7 | |||
| 4272536518 | |||
| 0d5a8a7383 | |||
| df6efe5d88 | |||
| d9dc9326f2 | |||
| b5fff09b54 | |||
| a96c4d707b | |||
| 0f9df18dfb | |||
| 8ea98f8cce | |||
| f2f7e6825f | |||
| 2f5e2f39cb | |||
| 4c11854927 | |||
| 6ce83aad2b | |||
| 2743f97892 | |||
| 978aef2ae7 | |||
| 48a12c605a | |||
| 95b4e61a07 | |||
| 2501691ea4 | |||
| a5a90fe6fc | |||
| 0fccd3707d | |||
| 253c069b26 | |||
| 2c7de8f328 | |||
| 64d203491c | |||
| b2ee6638e4 | |||
| 557410ffd7 | |||
| 40105094e7 | |||
| 0dba8d406b | |||
| 2ce5102473 | |||
| e3d64169ed | |||
| a5b565e193 | |||
| 7443fd0973 | |||
| ba613a1567 | |||
| 0bfdb50ade | |||
| a5f20829cb | |||
| abe3e5f597 | |||
| e12428efb9 | |||
| 0650dd7171 | |||
| 7c844909b9 | |||
| 898896f9e0 | |||
| 63ccc626f9 | |||
| 434ec7b6ea | |||
| b2549c317c | |||
| 20c01883c3 | |||
| 340a53fb80 | |||
| 25847a6192 | |||
| 69eb5cdd8e | |||
| 70d6caf95b | |||
| 47717fee88 | |||
| a9064a7871 | |||
| 21c26f48d0 | |||
| 857b4f90d9 | |||
| 97e702b963 | |||
| accb3e616d | |||
| 33786408f0 | |||
| 9a78857b31 | |||
| 1e730a74a0 | |||
| 46f7930787 | |||
| 68793ffe13 | |||
| 4637f14b7f | |||
| a3b853dd47 | |||
| d3aedbeb9a | |||
| da6a097dcc | |||
| 0ed5b364c6 | |||
| 2dbd14b6dc | |||
| 085f6e9560 | |||
| 20118bdfd2 | |||
| 088f41b334 | |||
| e4fdf171c7 | |||
| 6029973bdc | |||
| 995edf0566 | |||
| 5f32f9b1c8 | |||
| 264e5b7911 | |||
| a28d5585f5 | |||
| 082ae70d1d | |||
| 2aa958e058 | |||
| 290cf82936 | |||
| a872ff2d77 | |||
| 4ed9387801 | |||
| 225d5977ff | |||
| 4a4b80450a | |||
| 747d59b895 | |||
| ca95b561dc | |||
| 9df9ad975d | |||
| 9cd1587cf7 | |||
| 782ba32457 | |||
| d11819721d | |||
| 7ee3653342 | |||
| 9e3852f21c | |||
| 447d0ce0e2 | |||
| 49bb3f1387 | |||
| 53a89c953a | |||
| 75d713cdea | |||
| 32c104c660 | |||
| 0d2ed0784f | |||
| 479c611420 | |||
| d0556d6236 | |||
| 37e3fe5f1f | |||
| 9dfbbbcda4 | |||
| b1e1caba29 | |||
| b51e8bc191 | |||
| 27722463a7 | |||
| 3bc4e84ed3 | |||
| 60beddf6c8 | |||
| d00bb87f17 | |||
| 0f332bd9fb | |||
| e04e06d6e2 | |||
| 17fa5a9334 | |||
| 9b74901b40 | |||
| 78e6d7db95 | |||
| 2cf06bc3ee | |||
| 264820e3e8 | |||
| 979041a072 | |||
| ff344535ba | |||
| 1df35eb687 | |||
| cba96c9b35 | |||
| d7f0133f5f | |||
| e5d064d513 | |||
| c33a49fc5e | |||
| a837bb6681 | |||
| dbef6c73bc | |||
| fa2403c1d3 | |||
| c1916c0fb5 | |||
| dba4dcb4a5 | |||
| 9d26a9268b | |||
| 1b17072a89 | |||
| 7d46108c12 | |||
| cd53ec9bcc | |||
| 1ac32a5256 | |||
| 9e12c45d82 | |||
| 24d9d23743 | |||
| ce74333348 | |||
| 46f5325c15 | |||
| aa89b95075 | |||
| 27fc1672d4 | |||
| e6c5482b7c | |||
| 95dce5cdfc | |||
| 51139a5f56 | |||
| dd3ff0fcb5 | |||
| d088194585 | |||
| 5f187738e6 | |||
| c10d2e0d45 | |||
| 1a8f753303 | |||
| 23f7f5ebba | |||
| bdd145b0de | |||
| 0cbaed2443 | |||
| 99c0cbdf29 | |||
| 96985fb3fd | |||
| 981ca72ee6 | |||
| 6a32de4b47 | |||
| f5d0ed5b1c | |||
| 55801b48ec | |||
| 3ec870cb56 | |||
| cd0421ceb8 | |||
| 9a27beb79c | |||
| e6532b6d85 | |||
| 7d96cfa424 | |||
| c7af6725ca | |||
| feec7c5b40 | |||
| 07964a6112 | |||
| a93db40138 | |||
| b7c8afab2f | |||
| 6ca475def8 | |||
| d8e7adcdb4 | |||
| 113b175db7 | |||
| 40bf7c5285 | |||
| abeb337f45 | |||
| d0a0216602 | |||
| 2a0cfb608d | |||
| d33256f1dc | |||
| db2cd9e941 | |||
| 3e6f5de92f | |||
| 9f793dad28 | |||
| f2f5d4984d | |||
| 29fec4742e | |||
| 0a9a19305c | |||
| 4e9c432c14 | |||
| 6bf36d922c | |||
| 076d4e0ec5 | |||
| b87e6ccb76 | |||
| 22707edcbf | |||
| 7578298b3f | |||
| d2892fc799 | |||
| 21b2e5a059 | |||
| 878ae7ea89 | |||
| c657948824 | |||
| a39e71ca26 | |||
| 8f4e7f7fdc | |||
| a674450198 | |||
| 843f6e83a9 | |||
| 058ff94828 | |||
| 9378f38371 | |||
| 2dc39feabd | |||
| 09aad777f4 | |||
| da72a5fbcd | |||
| 1146a9b90b | |||
| 2fbfafc408 | |||
| b5dc1dde8b | |||
| 63b39c78ee | |||
| 13d9bcc0c7 | |||
| ba0d63d722 | |||
| 9672850d11 | |||
| 00e43197fd | |||
| 284ab11c7f | |||
| e62b222372 | |||
| a0e93009f0 | |||
| 5d4726446d | |||
| 010ac23e8a | |||
| cdfc67db01 | |||
| 6d869ef55b | |||
| 2fa6129c3a | |||
| bb6a921d1e | |||
| 9aaf81328f | |||
| 35225fe2d3 | |||
| 01266ece6b | |||
| 1b7415a81b | |||
| abdadf1ee1 | |||
| d7ae9fb4a2 | |||
| fb78592425 | |||
| af56c5033c | |||
| 3858e31942 | |||
| 37f0a37ed2 | |||
| 411f3256cc | |||
| 811c6a986f | |||
| 974acbf38c | |||
| 634b8b707f | |||
| 0e43271cc9 | |||
| 5ae1790e52 | |||
| 16997d85eb | |||
| 62d7d61381 | |||
| ae2a2d5b00 | |||
| bcdf04d00e | |||
| ba88be0fe9 | |||
| 8471c2d9d8 | |||
| dcc67863dc | |||
| ac7f50b4cd | |||
| 612d77eaab | |||
| 04996b2850 | |||
| 261beb046e | |||
| b8c43e55db | |||
| 13cf980879 | |||
| e6063fb26b | |||
| 1e4baa53f0 | |||
| 80ef5d761c | |||
| affd470820 | |||
| 89783ac0c2 | |||
| fe62afd3d9 | |||
| dca59d0eda | |||
| ec5f94adc8 | |||
| a38a2a0e4f | |||
| fe1978c6f5 | |||
| 509db0b08f | |||
| eae024027f | |||
| decfda2705 | |||
| 318781512b | |||
| 286d558c54 | |||
| 822c231f1c | |||
| 24fc2ae59e | |||
| 7b3d005662 | |||
| 04162aaa79 | |||
| db1adcac97 | |||
| 1e78262fc5 | |||
| 4497a16fb0 |
@@ -0,0 +1,14 @@
|
||||
# shell scripts should not use tabs to indent!
|
||||
*.bash text eol=lf core.whitespace whitespace=tab-in-indent,trailing-space,tabwidth=2
|
||||
*.sh text eol=lf core.whitespace whitespace=tab-in-indent,trailing-space,tabwidth=2
|
||||
|
||||
# files for systemd (shell-similar)
|
||||
*.path text eol=lf core.whitespace whitespace=tab-in-indent,trailing-space,tabwidth=2
|
||||
*.service text eol=lf core.whitespace whitespace=tab-in-indent,trailing-space,tabwidth=2
|
||||
*.timer text eol=lf core.whitespace whitespace=tab-in-indent,trailing-space,tabwidth=2
|
||||
|
||||
# go fmt will enforce this, but in case a user has not called "go fmt" allow GIT to catch this:
|
||||
*.go text eol=lf core.whitespace whitespace=indent-with-non-tab,trailing-space,tabwidth=4
|
||||
|
||||
*.yml text eol=lf core.whitespace whitespace=tab-in-indent,trailing-space,tabwidth=2
|
||||
.git* text eol=auto core.whitespace whitespace=trailing-space
|
||||
+14
-10
@@ -1,13 +1,17 @@
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
_gitignore/
|
||||
*.log
|
||||
Vagrantfile
|
||||
.vagrant/
|
||||
/.idea
|
||||
|
||||
dist/builds/
|
||||
dist/release/
|
||||
|
||||
error.log
|
||||
access.log
|
||||
|
||||
/*.conf
|
||||
Caddyfile
|
||||
|
||||
# artifacts from pprof tooling
|
||||
*.prof
|
||||
*.test
|
||||
|
||||
# mac specific
|
||||
.DS_Store
|
||||
|
||||
# go modules
|
||||
vendor
|
||||
og_static/
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.7.4
|
||||
- tip
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: tip
|
||||
fast_finish: true
|
||||
|
||||
before_install:
|
||||
# Decrypts a script that installs an authenticated cookie
|
||||
# for git to use when cloning from googlesource.com.
|
||||
# Bypasses "bandwidth limit exceeded" errors.
|
||||
# See github.com/golang/go/issues/12933
|
||||
- if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then openssl aes-256-cbc -K $encrypted_3df18f9af81d_key -iv $encrypted_3df18f9af81d_iv -in dist/gitcookie.sh.enc -out dist/gitcookie.sh -d; fi
|
||||
|
||||
install:
|
||||
- if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then bash dist/gitcookie.sh; fi
|
||||
- go get -t ./...
|
||||
- go get github.com/golang/lint/golint
|
||||
- go get github.com/gordonklaus/ineffassign
|
||||
|
||||
script:
|
||||
- diff <(echo -n) <(gofmt -s -d .)
|
||||
- ineffassign .
|
||||
- go vet ./...
|
||||
- go test -race ./...
|
||||
|
||||
after_script:
|
||||
- golint ./...
|
||||
@@ -1,10 +0,0 @@
|
||||
# This is the official list of Caddy Authors for copyright purposes.
|
||||
# Authors may be either individual people or legal entities.
|
||||
#
|
||||
# Not all individual contributors are authors. For the full list of
|
||||
# contributors, refer to the project's page on GitHub or the repo's
|
||||
# commit history.
|
||||
|
||||
Matthew Holt <Matthew.Holt@gmail.com>
|
||||
Light Code Labs <sales@lightcodelabs.com>
|
||||
Ardan Labs <info@ardanlabs.com>
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
## Contributing to Caddy
|
||||
|
||||
Welcome! Our community focuses on helping others and making Caddy the best it
|
||||
can be. We gladly accept contributions and encourage you to get involved!
|
||||
|
||||
|
||||
### Join us in the forum
|
||||
|
||||
The [Caddy forum](https://forum.caddyserver.com) is the place for all discussion
|
||||
that doesn't belong in issues or pull requests. Feel free to participate with us!
|
||||
|
||||
If you want to file a bug report or make an improvement to Caddy, however, you
|
||||
should submit an issue or pull request.
|
||||
|
||||
|
||||
### Bug reports
|
||||
|
||||
Please [search this repository](https://github.com/mholt/caddy/search?q=&type=Issues&utf8=%E2%9C%93)
|
||||
with a variety of keywords to ensure your bug is not already reported.
|
||||
|
||||
If unique, [open an issue](https://github.com/mholt/caddy/issues) and answer the
|
||||
questions so we can understand and reproduce the problematic behavior.
|
||||
|
||||
The burden is on you to convince us that it is actually a bug in Caddy. This is
|
||||
easiest to do when you write clear, concise instructions so we can reproduce
|
||||
the behavior (even if it seems obvious). The more detailed and specific you are,
|
||||
the faster we will be able to help you. Check out
|
||||
[How to Report Bugs Effectively](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html).
|
||||
|
||||
Please be kind. :smile: Remember that Caddy comes at no cost to you, and you're
|
||||
getting free help. If we helped you, please consider
|
||||
[donating](https://caddyserver.com/donate) - it keeps us motivated!
|
||||
|
||||
|
||||
### Minor improvements and new tests
|
||||
|
||||
Submit [pull requests](https://github.com/mholt/caddy/pulls) at any time for
|
||||
minor changes or new tests. Make sure to write tests to assert your change is
|
||||
working properly and is thoroughly covered. We'll ask most pull requests to be
|
||||
[squashed](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html),
|
||||
especially with small commits.
|
||||
|
||||
Your pull request may be thoroughly reviewed. This is because if we accept the
|
||||
PR, we also assume responsibility for it, although we would prefer you to
|
||||
help maintain your code after it gets merged.
|
||||
|
||||
|
||||
### Proposals, suggestions, ideas, new features
|
||||
|
||||
First, please [search](https://github.com/mholt/caddy/search?q=&type=Issues&utf8=%E2%9C%93)
|
||||
with a variety of keywords to ensure your suggestion/proposal is new.
|
||||
|
||||
If so, you may open either an issue or a pull request for discussion and
|
||||
feedback.
|
||||
|
||||
The advantage of issues is that you don't have to spend time implementing your
|
||||
idea, but you should still describe it thoroughly as if someone reading it would
|
||||
implement the whole thing starting from scratch.
|
||||
|
||||
The advantage of pull requests is that we can immediately see the impact the
|
||||
change will have on the project, what the code will look like, and how to
|
||||
improve it. The disadvantage of pull requests is that they are unlikely to get
|
||||
accepted without significant changes first, or it may be rejected entirely.
|
||||
Don't worry, that won't happen without an open discussion first.
|
||||
|
||||
If you are going to spend significant time writing code for a new pull request,
|
||||
best to open an issue to "claim" it and get feedback before you invest a lot of
|
||||
time. Not all pull requests are merged, and that's okay,
|
||||
[Read why.](https://github.com/turbolinks/turbolinks/pull/124#issuecomment-239826060)
|
||||
|
||||
Remember: pull requests should always be thoroughly documented both via godoc
|
||||
and with at least a rough draft of documentation that might go on the website
|
||||
for users to read.
|
||||
|
||||
|
||||
### Collaborator status
|
||||
|
||||
If your pull request is merged, congratulations! You're technically a
|
||||
collaborator. We may also grant you "Collaborator status" which means you can
|
||||
push to the repository and merge other pull requests. We hope that you will
|
||||
stay involved by reviewing pull requests, submitting more of your own, and
|
||||
resolving issues as you are able to. Thanks for making Caddy amazing!
|
||||
|
||||
We ask that collaborators will conduct thorough code reviews and be nice to
|
||||
new contributors. Before merging a PR, it's best to get the approval of
|
||||
at least one or two other collaborators and/or the project owner. We prefer
|
||||
squashed commits instead of many little, semantically-unimportant commits. Also,
|
||||
CI and other post-commit hooks must pass before being merged except in certain
|
||||
unusual circumstances.
|
||||
|
||||
Collaborator status may be removed for inactive users from time to time as
|
||||
we see fit; this is not an insult, just a basic security precaution in case
|
||||
the account becomes inactive or abandoned. Privileges can always be restored
|
||||
later.
|
||||
|
||||
**Reviewing pull requests:** Please help submit and review pull requests as
|
||||
you are able! We would ask that every pull request be reviewed by at least
|
||||
one collaborator who did not open the pull request before merging. This will
|
||||
help ensure high code quality as new collaborators are added to the project.
|
||||
|
||||
Read [CodeReviewComments](https://github.com/golang/go/wiki/CodeReviewComments)
|
||||
on the Go wiki for an idea of what we look for in good, clean Go code.
|
||||
|
||||
|
||||
|
||||
### Vulnerabilities
|
||||
|
||||
If you've found a vulnerability that is serious, please email me: Matthew dot
|
||||
Holt at Gmail. If it's not a big deal, a pull request will probably be faster.
|
||||
|
||||
|
||||
## Thank you
|
||||
|
||||
Thanks for your help! Caddy would not be what it is today without your
|
||||
contributions.
|
||||
@@ -0,0 +1,24 @@
|
||||
(Are you asking for help with using Caddy? Please use our forum instead: https://forum.caddyserver.com. If you are filing a bug report, please answer the following questions. If your issue is not a bug report, you do not need to use this template. Either way, please consider donating if we've helped you. Thanks!)
|
||||
|
||||
### 1. What version of Caddy are you running (`caddy -version`)?
|
||||
|
||||
|
||||
### 2. What are you trying to do?
|
||||
|
||||
|
||||
### 3. What is your entire Caddyfile?
|
||||
```text
|
||||
(Put Caddyfile here)
|
||||
```
|
||||
|
||||
### 4. How did you run Caddy (give the full command and describe the execution environment)?
|
||||
|
||||
|
||||
### 5. What did you expect to see?
|
||||
|
||||
|
||||
### 6. What did you see instead (give full error messages and/or log)?
|
||||
|
||||
|
||||
### 7. How can someone who is starting from scratch reproduce this behavior as minimally as possible?
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
@@ -179,7 +178,7 @@
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
@@ -187,7 +186,7 @@
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
@@ -1,396 +1,163 @@
|
||||
Caddy 2 Development Branch
|
||||
===========================
|
||||
<a href="https://caddyserver.com"><img src="https://caddyserver.com/resources/images/caddy-lower.png" alt="Caddy" width="350"></a>
|
||||
|
||||
This is the development branch for Caddy 2. This code (version 2) is not yet feature-complete or production-ready, but is already being used in production, and we encourage you to deploy it today on sites that are not very visible or important so that it can obtain crucial experience in the field.
|
||||
|
||||
Please file issues to propose new features and report bugs, and after the bug or feature has been discussed, submit a pull request! We need your help to build this web server into what you want it to be. (Caddy 2 issues and pull requests will usually receive priority over Caddy 1 issues and pull requests.)
|
||||
|
||||
**We want Caddy 2 to be the web server of the Go community!** We are looking for maintainers to represent the community. Please become involved (issues, PRs, [our forum](https://caddy.community) etc.) and express interest if you are committed to being a collaborator on the Caddy project.
|
||||
[](https://forum.caddyserver.com) [](https://twitter.com/caddyserver) [](https://godoc.org/github.com/mholt/caddy) [](https://travis-ci.org/mholt/caddy) [](https://ci.appveyor.com/project/mholt/caddy)
|
||||
[](https://goreportcard.com/report/mholt/caddy)
|
||||
|
||||
|
||||
### Menu
|
||||
Caddy is a general-purpose web server for Windows, Mac, Linux, BSD, and
|
||||
[Android](https://github.com/mholt/caddy/wiki/Running-Caddy-on-Android). It is
|
||||
a capable but easier alternative to other popular web servers.
|
||||
|
||||
- [Build from source](#build-from-source)
|
||||
[Releases](https://github.com/mholt/caddy/releases) ·
|
||||
[User Guide](https://caddyserver.com/docs) ·
|
||||
[Community](https://forum.caddyserver.com)
|
||||
|
||||
Try browsing [the code on Sourcegraph](https://sourcegraph.com/github.com/mholt/caddy)!
|
||||
|
||||
## Menu
|
||||
|
||||
- [Features](#features)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Configuration](#configuration)
|
||||
- [Full Documentation](#full-documentation)
|
||||
- [List of Improvements](#list-of-improvements)
|
||||
- [FAQ](#faq)
|
||||
- [Running from Source](#running-from-source)
|
||||
- [Running in Production](#running-in-production)
|
||||
- [Contributing](#contributing)
|
||||
- [About the Project](#about-the-project)
|
||||
|
||||
|
||||
## Build from source
|
||||
|
||||
Requirements:
|
||||
## Features
|
||||
|
||||
- [Go 1.13 or newer](https://golang.org/dl/)
|
||||
- Make sure you do not disable [Go modules](https://github.com/golang/go/wiki/Modules) (`export GO111MODULE=auto`)
|
||||
- **Easy configuration** with Caddyfile
|
||||
- **Automatic HTTPS** via [Let's Encrypt](https://letsencrypt.org); Caddy
|
||||
obtains and manages all cryptographic assets for you
|
||||
- **HTTP/2** enabled by default (powered by Go standard library)
|
||||
- **Virtual hosting** for hundreds of sites per server instance, including TLS
|
||||
SNI
|
||||
- Experimental **QUIC support** for those that like speed
|
||||
- TLS session ticket **key rotation** for more secure connections
|
||||
- **Brilliant extensibility** so Caddy can be customized for your needs
|
||||
- **Runs anywhere** with **no external dependencies** (not even libc)
|
||||
|
||||
Download the `v2` source code:
|
||||
|
||||
```bash
|
||||
$ git clone -b v2 "https://github.com/caddyserver/caddy.git"
|
||||
```
|
||||
|
||||
Build:
|
||||
|
||||
```bash
|
||||
$ cd caddy/cmd/caddy/
|
||||
$ go build
|
||||
```
|
||||
|
||||
That will put a `caddy(.exe)` binary into the current directory. You can move it into your PATH or use `go install` to do that automatically (assuming `$GOPATH/bin` is already in your PATH). You can also use `go run main.go` for quick, temporary builds while developing.
|
||||
|
||||
The initial build may be slow as dependencies are downloaded. Subsequent builds should be very fast. If you encounter any Go-module-related errors, try clearing your Go module cache (`$GOPATH/pkg/mod`) and read [the Go wiki page about modules for help](https://github.com/golang/go/wiki/Modules). If you have issues with Go modules, please consult the Go community for help. But if there is an actual error in Caddy, please report it to us.
|
||||
|
||||
|
||||
## Quick Start
|
||||
|
||||
(Until the stable 2.0 release, there may be breaking changes in v2, please be aware!)
|
||||
Caddy binaries have no dependencies and are available for every platform.
|
||||
Install Caddy any one of these ways:
|
||||
|
||||
These instructions assume an executable build of Caddy 2 is named `caddy` in the current folder. If it's in your PATH, you may omit the path to the binary (`./`).
|
||||
- **[Download page](https://caddyserver.com/download)** allows you to
|
||||
customize your build in the browser
|
||||
- **[Latest release](https://github.com/mholt/caddy/releases/latest)** for
|
||||
pre-built binaries
|
||||
- **curl [getcaddy.com](https://getcaddy.com)** for auto install:
|
||||
`curl https://getcaddy.com | bash`
|
||||
|
||||
Start Caddy:
|
||||
Once `caddy` is in your PATH, you can `cd` to your website's folder and run
|
||||
`caddy` to serve it. By default, Caddy serves the current directory at
|
||||
[localhost:2015](http://localhost:2015).
|
||||
|
||||
```bash
|
||||
$ ./caddy start
|
||||
```
|
||||
|
||||
There are no config files with Caddy 2. Instead, you POST configuration to it:
|
||||
|
||||
```bash
|
||||
$ curl -X POST "http://localhost:2019/load" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"example": {
|
||||
"listen": ["127.0.0.1:2080"],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [{
|
||||
"handler": "file_server",
|
||||
"browse": {}
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
```
|
||||
|
||||
Now visit http://localhost:2080 in your browser and you will see the contents of the current directory displayed.
|
||||
|
||||
To change Caddy's configuration, simply POST a new payload to that endpoint. Config changes are extremely lightweight and efficient, and should be graceful on all platforms -- _even Windows_.
|
||||
|
||||
Updating configuration using heredoc can be tedious, so you can still use a config file if you prefer. Put your configuration in any file (`caddy.json` for example) and then POST that instead:
|
||||
|
||||
```bash
|
||||
$ curl -X POST "http://localhost:2019/load" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @caddy.json
|
||||
```
|
||||
|
||||
Or you can tell Caddy to load its configuration from a file in the first place (this simply does the work of the above curl command for you):
|
||||
|
||||
```bash
|
||||
$ ./caddy start --config caddy.json
|
||||
```
|
||||
|
||||
To stop Caddy:
|
||||
|
||||
```bash
|
||||
$ ./caddy stop
|
||||
```
|
||||
|
||||
Note that this will stop any process named the same as `os.Args[0]`.
|
||||
|
||||
For other commands, please see [the Caddy 2 documentation](https://github.com/caddyserver/caddy/wiki/v2:-Documentation).
|
||||
|
||||
### Caddyfile
|
||||
|
||||
Caddy 2 can be configured with a Caddyfile, much like in v1, for example:
|
||||
To customize how your site is served, create a file named Caddyfile by your
|
||||
site and paste this into it:
|
||||
|
||||
```plain
|
||||
example.com
|
||||
localhost
|
||||
|
||||
templates
|
||||
encode gzip zstd
|
||||
try_files {path}.html {path}
|
||||
reverse_proxy /api localhost:9005
|
||||
file_server
|
||||
gzip
|
||||
browse
|
||||
websocket /echo cat
|
||||
ext .html
|
||||
log /var/log/access.log
|
||||
proxy /api 127.0.0.1:7005
|
||||
header /api Access-Control-Allow-Origin *
|
||||
```
|
||||
|
||||
Instead of being its primary mode of configuration, an internal _config adapter_ adapts the Caddyfile to Caddy's native JSON structure. You can see it in action with the [`adapt-config` command](https://github.com/caddyserver/caddy/wiki/v2:-Documentation#adapt-config):
|
||||
When you run `caddy` in that directory, it will automatically find and use
|
||||
that Caddyfile to configure itself.
|
||||
|
||||
```bash
|
||||
$ ./caddy adapt-config --input path/to/Caddyfile --adapter caddyfile --pretty
|
||||
```
|
||||
This simple file enables compression, allows directory browsing (for folders
|
||||
without an index file), hosts a WebSocket echo server at /echo, serves clean
|
||||
URLs, logs requests to access.log, proxies all API requests to a backend on
|
||||
port 7005, and adds the coveted `Access-Control-Allow-Origin: *` header for
|
||||
all responses from the API.
|
||||
|
||||
But if you just want to run Caddy with your Caddyfile directly, the CLI wraps this up for you nicely. Either of the following commands:
|
||||
Wow! Caddy can do a lot with just a few lines.
|
||||
|
||||
```bash
|
||||
$ ./caddy start
|
||||
$ ./caddy run
|
||||
```
|
||||
To host multiple sites and do more with the Caddyfile, please see the
|
||||
[Caddyfile documentation](https://caddyserver.com/docs/caddyfile).
|
||||
|
||||
will apply your Caddyfile if it is called `Caddyfile` in the current directory.
|
||||
Note that production sites are served over
|
||||
[HTTPS by default](https://caddyserver.com/docs/automatic-https).
|
||||
|
||||
If your Caddyfile is somewhere else, you can still use it:
|
||||
Caddy has a command line interface. Run `caddy -h` to view basic help or see
|
||||
the [CLI documentation](https://caddyserver.com/docs/cli) for details.
|
||||
|
||||
```bash
|
||||
$ ./caddy start|run --config path/to/Caddyfile --config-adapter caddyfile
|
||||
```
|
||||
**Running as root:** We advise against this. You can still listen on ports
|
||||
< 1024 using setcap like so: `sudo setcap cap_net_bind_service=+ep ./caddy`
|
||||
|
||||
[Learn more about the Caddyfile in v2.](https://github.com/caddyserver/caddy/wiki/v2:-Documentation#caddyfile-adapter)
|
||||
|
||||
|
||||
## Configuration
|
||||
## Running from Source
|
||||
|
||||
Caddy 2 exposes an unprecedented level of control compared to any web server in existence. In Caddy 2, you are usually setting the actual values of the initialized types in memory that power everything from your HTTP handlers and TLS handshakes to your storage medium. Caddy 2 is also ridiculously extensible, with a module system that makes vast improvements over Caddy 1's plugin system.
|
||||
Note: You will need **[Go 1.7](https://golang.org/dl/)** or newer.
|
||||
|
||||
Nearly all of Caddy 2's configuration is contained in a single config document, rather than being spread across CLI flags and env variables and a configuration file as with other web servers (and Caddy 1).
|
||||
1. `go get github.com/mholt/caddy/caddy`
|
||||
2. `cd` into your website's directory
|
||||
3. Run `caddy` (assuming `$GOPATH/bin` is in your `$PATH`)
|
||||
|
||||
To wield the power of this design, you need to know how the config document is structured. Please see the [the Caddy 2 documentation in our wiki](https://github.com/caddyserver/caddy/wiki/v2:-Documentation) for details about Caddy's config structure.
|
||||
Caddy's `main()` is in the caddy subfolder. To recompile Caddy, use
|
||||
`build.bash` found in that folder.
|
||||
|
||||
Configuration is normally given to Caddy through an API endpoint, which is likewise documented in the wiki pages. However, you can also use config files of various formats with [config adapters](https://github.com/caddyserver/caddy/wiki/v2:-Documentation#config-adapters).
|
||||
|
||||
|
||||
## Full Documentation
|
||||
## Running in Production
|
||||
|
||||
Caddy 2 is very much in development, so the documentation is an ongoing WIP, but the latest will be in our wiki for now:
|
||||
The Caddy project does not officially maintain any system-specific
|
||||
integrations, but your download file includes
|
||||
[unofficial resources](https://github.com/mholt/caddy/tree/master/dist/init)
|
||||
contributed by the community that you may find helpful for running Caddy in
|
||||
production.
|
||||
|
||||
**https://github.com/caddyserver/caddy/wiki/v2:-Documentation**
|
||||
How you choose to run Caddy is up to you. Many users are satisfied with
|
||||
`nohup caddy &`. Others use `screen`. Users who need Caddy to come back up
|
||||
after reboots either do so in the script that caused the reboot, add a command
|
||||
to an init script, or configure a service with their OS.
|
||||
|
||||
Note that breaking changes are expected until the stable 2.0 release.
|
||||
|
||||
|
||||
## List of Improvements
|
||||
## Contributing
|
||||
|
||||
The following is a non-comprehensive list of significant improvements over Caddy 1. Not everything in this list is finished yet, but they will be finished or at least will be possible with Caddy 2 or Caddy Enterprise:
|
||||
**[Join our community](https://forum.caddyserver.com) where you can chat with
|
||||
other Caddy users and developers!**
|
||||
|
||||
- Centralized configuration. No more disparate use of environment variables, config files (potentially multiple!), CLI flags, etc.
|
||||
- REST API. Control Caddy with HTTP requests to an administration endpoint. Changes are applied immediately and efficiently.
|
||||
- Dynamic configuration. Any and all specific config values can be modified directly through the admin API with a REST endpoint.
|
||||
- Enterprise: Change only specific configuration settings instead of needing to specify the whole config each time. This makes it safe and easy to change Caddy's config with manually-crafted curl commands, for example.
|
||||
- No configuration files. Except optionally to bootstrap its configuration at startup. You can still use config files if you wish, and we expect that most people will.
|
||||
- Enterprise: Export the current Caddy configuration with an API GET request.
|
||||
- Silky-smooth graceful reloads. Update the configuration up to dozens of times per second with no dropped requests and very little memory cost. Our unique graceful reload technology is lighter and faster **and works on all platforms, including Windows**.
|
||||
- An embedded scripting language! Caddy2 has native Starlark integration. Do things you never thought possible with higher performance than Lua, JavaScript, and other VMs. Starlark is expressive, familiar (dialect of Python), _almost_ Turing-complete, and highly efficient. (We're still improving performance here.)
|
||||
- Using [XDG standards](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html#variables) instead of dumping all assets in `$HOME/.caddy`.
|
||||
- Caddy plugins are now called "Caddy modules" (although the terms "plugin" and "module" may be used interchangably). Caddy modules are a concept unrelated [Go modules](https://github.com/golang/go/wiki/Modules), except that Caddy modules may be implemented by Go modules. Caddy modules are centrally-registered, properly namespaced, and generically loaded & configured, as opposed to how scattered and unorganized Caddy 1-era plugins are.
|
||||
- Modules are easier to write, since they do not have to both deserialize their own configuration from a configuration DSL and provision themselves like plugins did. Modules are initialized pre-configured and have the ability to validate the configuration and perform provisioning steps if necessary.
|
||||
- Can specify different storage mechanisms in different parts of the configuration, if more than one is needed.
|
||||
- "Top-level" Caddy modules are simply called "apps" because literally any long-lived application can be served by Caddy 2.
|
||||
- Even more of Caddy is made of modules, allowing for unparalleled extensibility, flexibility, and control. Caddy 2 is arguably the most flexible, extensible, programmable web server ever made.
|
||||
- TLS improvements!
|
||||
- TLS configuration is now centralized and decoupled from specific sites
|
||||
- A single certificate cache is used process-wide, reducing duplication and improving memory use
|
||||
- Customize how to manage each certificate ("automation policies") based on the hostname
|
||||
- Automation policy doesn't have to be limited to just ACME - could be any way to manage certificates
|
||||
- Fine-grained control over TLS handshakes
|
||||
- If an ACME challenge fails, other enabled challenges will be tried (no other web server does this)
|
||||
- Enterprise: TLS Session Ticket Ephemeral Keys (STEKs) can be rotated in a cluster for increased performance (no other web server does this either!)
|
||||
- Enterprise: Ability to select a specific certificate per ClientHello given multiple qualifying certificates
|
||||
- Enterprise: Provide TLS certificates without persisting them to disk; keep private keys entirely in memory
|
||||
- All-new HTTP server core
|
||||
- Listeners can be configured for any network type, address, and port range
|
||||
- Customizable TLS connection policies
|
||||
- HTTP handlers are configured by "routes" which consist of matcher and handler components. Match matches an HTTP request, and handle defines the list of handlers to invoke as a result of the match.
|
||||
- Some matchers are regular expressions, which expose capture groups to placeholders.
|
||||
- New matchers include negation and matching based on remote IP address / CIDR ranges.
|
||||
- Placeholders are vastly improved generally
|
||||
- Placeholders (variables) are more properly namespaced.
|
||||
- Multiple routes may match an HTTP request, creating a "composite route" quickly on the fly.
|
||||
- The actual handler for any given request is its composite route.
|
||||
- User defines the order of middlewares (careful! easy to break things).
|
||||
- Adding middlewares no longer requires changes to Caddy's code base (there is no authoritative list).
|
||||
- Routes may be marked as terminal, meaning no more routes will be matched.
|
||||
- Routes may be grouped so that only the first matching route in a group is applied.
|
||||
- Requests may be "re-handled" if they are modified and need to be sent through the chain again (internal redirect).
|
||||
- Vastly more powerful static file server, with native content-negotiation abilities
|
||||
- Done away with URL-rewriting hacks often needed in Caddy 1
|
||||
- Highly descriptive/traceable errors
|
||||
- Very flexible error handling, with the ability to specify a whole list of routes just for error cases
|
||||
- More control over automatic HTTPS: disable entirely, disable only HTTP->HTTPS redirects, disable only cert management, and for certain names, etc.
|
||||
- Enterprise: Use Starlark to build custom, dynamic HTTP handlers at request-time
|
||||
- We are finding that -- on average -- Caddy 2's Starlark handlers are ~1.25-2x faster than NGINX+Lua.
|
||||
Please see our [contributing guidelines](https://github.com/mholt/caddy/blob/master/CONTRIBUTING.md)
|
||||
and check out the [developer wiki](https://github.com/mholt/caddy/wiki).
|
||||
|
||||
And a few major features still being worked on:
|
||||
We use GitHub issues and pull requests only for discussing bug reports and
|
||||
the development of specific changes. We welcome all other topics on the
|
||||
[forum](https://forum.caddyserver.com)!
|
||||
|
||||
- Logging
|
||||
- Kubernetes ingress controller (mostly done, just polishing it -- and it's amazing)
|
||||
- More config adapters. Caddy's native JSON config structure is powerful and complex. Config adapters upsample various formats to Caddy's native config. There are already adapters for Caddyfile, JSON 5, and JSON-C. Planned are NGINX config, YAML, and TOML. The community might be interested in building Traefik and Apache config adapters!
|
||||
If you want to contribute to the documentation, please submit pull requests to [caddyserver/caddyserver.com](https://github.com/caddyserver/caddyserver.com).
|
||||
|
||||
Thanks for making Caddy -- and the Web -- better!
|
||||
|
||||
Special thanks to
|
||||
[](https://www.digitalocean.com)
|
||||
for hosting the Caddy project.
|
||||
|
||||
## FAQ
|
||||
|
||||
### How do I configure Caddy 2?
|
||||
|
||||
Caddy's primary mode of configuration is a REST API, which accepts a JSON document. The JSON structure is described [in the wiki](https://github.com/caddyserver/caddy/wiki/v2:-Documentation). The advantages of exposing this low-level structure are 1) it has near-parity with actual memory initialization, 2) it allows us to offer wrappers over this configuration to any degree of convenience that is needed, and 3) it performs very well under rapid config changes.
|
||||
## About the Project
|
||||
|
||||
Basically, you will [start Caddy](https://github.com/caddyserver/caddy/wiki/v2:-Documentation#start), then [POST a JSON config to its API endpoint](https://github.com/caddyserver/caddy/wiki/v2:-Documentation#post-load).
|
||||
Caddy was born out of the need for a "batteries-included" web server that runs
|
||||
anywhere and doesn't have to take its configuration with it. Caddy took
|
||||
inspiration from [spark](https://github.com/rif/spark),
|
||||
[nginx](https://github.com/nginx/nginx), lighttpd,
|
||||
[Websocketd](https://github.com/joewalnes/websocketd)
|
||||
and [Vagrant](https://www.vagrantup.com/),
|
||||
which provides a pleasant mixture of features from each of them.
|
||||
|
||||
Although this makes Caddy 2 highly programmable, not everyone will want to configure Caddy via JSON with an API. Sometimes we just want to give Caddy a simple, static config file and have it do its thing. That's what **[config adapters](https://github.com/caddyserver/caddy/wiki/v2:-Documentation#config-adapters)** are for! You can configure Caddy more ways than one, depending on your needs and preferences. See the next questions that explain this more.
|
||||
**The name "Caddy":** The name of the software is "Caddy", not "Caddy Server"
|
||||
or "CaddyServer". Please call it "Caddy" or, if you wish to clarify, "the
|
||||
Caddy web server". See [brand guidelines](https://caddyserver.com/brand).
|
||||
|
||||
### Caddy 2 feels harder to use. How is this an improvement over Caddy 1?
|
||||
|
||||
Caddy's ease of use is one of the main reasons it is special. We are not taking that away in Caddy 2, but first we had to be sure to tackle the fundamental design limitations with Caddy 1. Usability can then be layered on top. This approach has several advantages which we discuss in the next question.
|
||||
|
||||
### What about the Caddyfile; are there easier ways to configure Caddy 2?
|
||||
|
||||
Yes! Caddy's native JSON configuration via API is nice when you are automating config changes at scale, but if you just have a simple, static configuration in a file, you can do that too with the [Caddyfile](https://github.com/caddyserver/caddy/wiki/v2:-Documentation#caddyfile-adapter).
|
||||
|
||||
The v2 Caddyfile is very similar to the v1 Caddyfile, but they are not compatible. Several improvements have been made to request matching and directives in v2, giving you more power with less complexity and fewer inconsistencies.
|
||||
|
||||
Caddy's default _config adapter_ is the Caddyfile adapter. This takes a Caddyfile as input and [outputs the JSON config](https://github.com/caddyserver/caddy/wiki/v2:-Documentation#adapt-config). You can even run Caddy directly without having to see or think about the underlying JSON config.
|
||||
|
||||
The following _config adapters_ are already being built or plan to be built:
|
||||
|
||||
- Caddyfile
|
||||
- JSON 5
|
||||
- JSON-C
|
||||
- nginx
|
||||
- YAML
|
||||
- TOML
|
||||
- any others that the community would like to contribute
|
||||
|
||||
Config adapters allow you to configure Caddy not just one way but _any_ of these ways. For example, you'll be able to bring your existing NGINX config to Caddy and it will spit out the Caddy config JSON you need (to the best of its ability). How cool is that! You can then easily tweak the resulting config by hand, if necessary.
|
||||
|
||||
All config adapters vary in their theoretical expressiveness; that is, if you need more advanced configuration you'll have to drop down to the JSON config, because the Caddyfile or an nginx config may not be expressive enough.
|
||||
|
||||
However, we expect that most users will be able to use the Caddyfile (or another easy config adapter) exclusively for their sites.
|
||||
|
||||
### Why JSON for configuration? Why not _<any other serialization format>_?
|
||||
|
||||
We know there might be strong opinions on this one. Regardless, for Caddy 2, we've decided to go with JSON. If that proves to be a fatal mistake, then Caddy 3 probably won't use JSON.
|
||||
|
||||
JSON may not be the fastest, the most compact, the easiest to write, serialization format that exists. But those aren't our goals. It has withstood the test of time and checks all our boxes.
|
||||
|
||||
- It is almost entirely ubiquitous. JSON works natively in web browsers and has mature libraries in pretty much every language.
|
||||
- It is human-readable (as opposed to a binary format).
|
||||
- It is easy to tweak by hand. Although composing raw JSON by hand is not awesome, this will not be mainstream once our config adapters are done.
|
||||
- It is generally easy to convert other serializations or config formats into JSON, as opposed to the other way around.
|
||||
- Even though JSON deserialization is not fast per-se, that kind of performance is not really a concern since config reloads are not the server's hottest path like HTTP request handling or TLS handshakes are. Even with JSON, Caddy 2 can handle dozens of config changes per second, which is probably plenty for now.
|
||||
- It maps almost 1:1 to the actual, in-memory values that power your HTTP handlers and other parts of the server (no need to parse a config file with some arbitrary DSL and do a bunch of extra pre-processing).
|
||||
|
||||
Ultimately, we think all these properties are appropriate -- if not ideal -- for a web server configuration.
|
||||
|
||||
If you're still not happy with the choice of JSON, feel free to contribute a config adapter of your own choice!
|
||||
|
||||
Or just use YAML or TOML, which seamlessly translate to JSON.
|
||||
|
||||
### JSON is declarative; what if I need more programmability (i.e. imperative syntax)?
|
||||
|
||||
NGINX also realized the need for imperative logic in declarative configs, so they tried "if" statements, [but it was a bad idea](https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/).
|
||||
|
||||
We have good news. Caddy 2 can give you the power of imperative logic without the perils of mixing declarative and imperative config such as befell NGINX. We do this by allowing embedded imperative syntax awithin the Caddy's declarative config.
|
||||
|
||||
Caddy 2's configuration is declarative because configuration is very much declarative in nature. Configuration is a tricky medium, as it is read and written by both computers and humans. Computers use it, but humans constantly refer to it and update it. Declarative syntaxes are fairly straightforward to make sense of, whereas it is difficult to reason about imperative logic.
|
||||
|
||||
However, sometimes computation is useful, and in some cases, the only way to express what you need. This can be illustrated really well in the simple case of trying to decide whether a particular HTTP middleware should be invoked as part of an HTTP request. A lot of the time, such logic is as simple as: "GET requests for any path starting with /foo/bar", which can be expressed declaratively in JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/foo/bar"
|
||||
}
|
||||
```
|
||||
|
||||
But what if you need to match /foo/bar OR /topaz? How do you express that OR clause? Maybe an array:
|
||||
|
||||
```json
|
||||
{
|
||||
"method": ["GET"],
|
||||
"path": ["/foo/bar", "/topaz"]
|
||||
}
|
||||
```
|
||||
|
||||
Now what if you need add a NOT or AND clause? JSON quickly tires out. As you learn about Caddy 2's request matching, you will see how we handled this. Caddy 2's JSON gives you the ability to express moderately-complex logic such as:
|
||||
|
||||
```js
|
||||
// this is not actual Caddy config, just logic pseudocode
|
||||
IF (Host = "example.com")
|
||||
OR (Host = "sub.example.com" AND Path != "/foo/bar")
|
||||
```
|
||||
|
||||
Already, this is more expressive power than most web servers offer with their native config, yet Caddy 2 offers this in JSON.
|
||||
|
||||
But in most web servers, to make logic this complex feasible, you'll generally call out to Lua or some extra DSL. For example, in NGINX you could use a Lua module to express this logic. Traefik 2.0 has [yet another kind of clunky-looking custom DSL](https://blog.containo.us/back-to-traefik-2-0-2f9aa17be305#d22e) just for this.
|
||||
|
||||
Caddy 2 solves this in a novel way with [Starlark expressions](https://godoc.org/go.starlark.net/starlark#Eval). Starlark is a familiar dialect of Python! So, no new DSLs to learn and no VMs to slow things down:
|
||||
|
||||
```python
|
||||
req.host == 'example.com' ||
|
||||
(req.host == 'sub.example.com' && req.path != '/foo/bar')
|
||||
```
|
||||
|
||||
Starlark performs at least as well as NGINX+Lua (more performance tests ongoing, as well as optimizations to make it even faster!) and because it's basically Python, it's familiar and easy to use.
|
||||
|
||||
In summary: Caddy 2 config is declarative, but can be imperative where that is useful.
|
||||
|
||||
### What will Caddy 2 be licensed as?
|
||||
|
||||
Caddy 2 is licensed under the Apache 2.0 open source license. There are no official Caddy 2 distributions that are proprietary.
|
||||
|
||||
### What is Caddy Enterprise?
|
||||
|
||||
Caddy Enterprise is a collection of plugins for Caddy 2 which provide features and performance that are crucial in business settings. Caddy Enterprise is not a separate web server and does not even use a separate code base from Caddy 2; it is not even a separate branch that merges the open source core in every once in a while. In other words, open source users aren't missing out on a "better" web server, but Enterprise provides features that are used by businesses.
|
||||
|
||||
Caddy Enterprise is for businesses that need more advanced features for higher scalability and easier management of clusters. It includes:
|
||||
|
||||
- a web UI
|
||||
- performance improvements within a cluster
|
||||
- advanced TLS controls
|
||||
- fine-grained config changes (i.e. ability to change only certain parts of the configuration)
|
||||
- training and support
|
||||
- advanced HTTP handlers for authentication, metrics, debugging, and more
|
||||
- dynamic HTTP handlers and TLS handshakes with Starlark
|
||||
|
||||
Caddy Enterprise can be customized for each customer according to their needs.
|
||||
|
||||
Caddy 2 and Caddy Enterprise offer equal levels of security and, as mentioned, share the same open source code base.
|
||||
|
||||
### Does Caddy 2 have telemetry?
|
||||
|
||||
No. There was not enough academic interest to continue supporting it. If telemetry does get added later, it will not be on by default or will be vastly reduced in its scope.
|
||||
|
||||
## Does Caddy 2 use HTTPS by default?
|
||||
|
||||
Yes. HTTPS is automatic and enabled by default when possible, just like in Caddy 1. Basically, if your HTTP routes specify a `host` matcher with qualifying domain names, those names will be enabled for automatic HTTPS. Automatic HTTPS is disabled for domains which match certificates that are manually loaded by your config.
|
||||
|
||||
## How do I avoid Let's Encrypt rate limits with Caddy 2?
|
||||
|
||||
As you are testing and developing with Caddy 2, you may wish to use test ("staging") certificates from Let's Encrypt to avoid rate limits. By default, Caddy 2 uses Let's Encrypt's production endpoint to get real certificates for your domains, but their [rate limits](https://letsencrypt.org/docs/rate-limits/) forbid testing and development use of this endpoint for good reasons. You can switch to their [staging endpoint](https://letsencrypt.org/docs/staging-environment/) by adding the staging CA to your automation policy in the `tls` app:
|
||||
|
||||
```json
|
||||
"tls": {
|
||||
"automation": {
|
||||
"policies": [
|
||||
{
|
||||
"management": {
|
||||
"module": "acme",
|
||||
"ca": "https://acme-staging-v02.api.letsencrypt.org/directory"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Or with the Caddyfile:
|
||||
|
||||
```
|
||||
tls {
|
||||
ca https://acme-staging-v02.api.letsencrypt.org/directory
|
||||
}
|
||||
```
|
||||
|
||||
## Can we get some access controls on the admin endpoint?
|
||||
|
||||
Yeah, that's coming. For now, you can use a unix socket that is properly permissioned for some basic security.
|
||||
*Author on Twitter: [@mholt6](https://twitter.com/mholt6)*
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/pprof"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/mholt/certmagic"
|
||||
"github.com/rs/cors"
|
||||
)
|
||||
|
||||
var (
|
||||
cfgEndptSrv *http.Server
|
||||
cfgEndptSrvMu sync.Mutex
|
||||
)
|
||||
|
||||
// AdminConfig configures the admin endpoint.
|
||||
type AdminConfig struct {
|
||||
Listen string `json:"listen,omitempty"`
|
||||
}
|
||||
|
||||
// DefaultAdminConfig is the default configuration
|
||||
// for the administration endpoint.
|
||||
var DefaultAdminConfig = &AdminConfig{
|
||||
Listen: DefaultAdminListen,
|
||||
}
|
||||
|
||||
// StartAdmin starts Caddy's administration endpoint,
|
||||
// bootstrapping it with an optional configuration
|
||||
// in the format of JSON bytes. It opens a listener
|
||||
// resource. When no longer needed, StopAdmin should
|
||||
// be called.
|
||||
func StartAdmin(initialConfigJSON []byte) error {
|
||||
cfgEndptSrvMu.Lock()
|
||||
defer cfgEndptSrvMu.Unlock()
|
||||
|
||||
adminConfig := DefaultAdminConfig
|
||||
if len(initialConfigJSON) > 0 {
|
||||
var config *Config
|
||||
err := json.Unmarshal(initialConfigJSON, &config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unmarshaling bootstrap config: %v", err)
|
||||
}
|
||||
if config != nil && config.Admin != nil {
|
||||
adminConfig = config.Admin
|
||||
}
|
||||
if cfgEndptSrv != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
err := cfgEndptSrv.Shutdown(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("shutting down old admin endpoint: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// extract a singular listener address
|
||||
netw, listenAddrs, err := ParseNetworkAddress(adminConfig.Listen)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing admin listener address: %v", err)
|
||||
}
|
||||
if len(listenAddrs) != 1 {
|
||||
return fmt.Errorf("admin endpoint must have exactly one listener; cannot listen on %v", listenAddrs)
|
||||
}
|
||||
ln, err := net.Listen(netw, listenAddrs[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/load", handleLoadConfig)
|
||||
mux.HandleFunc("/stop", handleStop)
|
||||
|
||||
///// BEGIN PPROF STUFF (TODO: Temporary) /////
|
||||
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
||||
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
||||
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
||||
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
|
||||
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
|
||||
///// END PPROF STUFF //////
|
||||
|
||||
for _, m := range GetModules("admin.routers") {
|
||||
adminrtr := m.New().(AdminRouter)
|
||||
for _, route := range adminrtr.Routes() {
|
||||
mux.Handle(route.Pattern, route)
|
||||
}
|
||||
}
|
||||
|
||||
handler := cors.Default().Handler(mux)
|
||||
|
||||
cfgEndptSrv = &http.Server{
|
||||
Handler: handler,
|
||||
ReadTimeout: 5 * time.Second,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
IdleTimeout: 5 * time.Second,
|
||||
MaxHeaderBytes: 1024 * 256,
|
||||
}
|
||||
|
||||
go cfgEndptSrv.Serve(ln)
|
||||
|
||||
log.Println("Caddy 2 admin endpoint listening on", adminConfig.Listen)
|
||||
|
||||
if len(initialConfigJSON) > 0 {
|
||||
err := Load(bytes.NewReader(initialConfigJSON))
|
||||
if err != nil {
|
||||
return fmt.Errorf("loading initial config: %v", err)
|
||||
}
|
||||
log.Println("Caddy 2 serving initial configuration")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// StopAdmin stops the API endpoint.
|
||||
func StopAdmin() error {
|
||||
cfgEndptSrvMu.Lock()
|
||||
defer cfgEndptSrvMu.Unlock()
|
||||
|
||||
if cfgEndptSrv == nil {
|
||||
return fmt.Errorf("no server")
|
||||
}
|
||||
|
||||
err := cfgEndptSrv.Shutdown(context.Background()) // TODO
|
||||
if err != nil {
|
||||
return fmt.Errorf("shutting down server: %v", err)
|
||||
}
|
||||
|
||||
cfgEndptSrv = nil
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AdminRouter is a type which can return routes for the admin API.
|
||||
type AdminRouter interface {
|
||||
Routes() []AdminRoute
|
||||
}
|
||||
|
||||
// AdminRoute represents a route for the admin endpoint.
|
||||
type AdminRoute struct {
|
||||
http.Handler
|
||||
Pattern string
|
||||
}
|
||||
|
||||
func handleLoadConfig(w http.ResponseWriter, r *http.Request) {
|
||||
r.Close = true
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var payload io.Reader = r.Body
|
||||
|
||||
// if the config is formatted other than Caddy's native
|
||||
// JSON, we need to adapt it before loading it
|
||||
if ctHeader := r.Header.Get("Content-Type"); ctHeader != "" {
|
||||
ct, _, err := mime.ParseMediaType(ctHeader)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid Content-Type: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !strings.HasSuffix(ct, "/json") {
|
||||
slashIdx := strings.Index(ct, "/")
|
||||
if slashIdx < 0 {
|
||||
http.Error(w, "Malformed Content-Type", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
adapterName := ct[slashIdx+1:]
|
||||
cfgAdapter := caddyconfig.GetAdapter(adapterName)
|
||||
if cfgAdapter == nil {
|
||||
http.Error(w, "Unrecognized config adapter: "+adapterName, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, 1024*1024))
|
||||
if err != nil {
|
||||
http.Error(w, "Error reading request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
result, warnings, err := cfgAdapter.Adapt(body, nil)
|
||||
if err != nil {
|
||||
log.Printf("[ADMIN][ERROR] adapting config from %s: %v", adapterName, err)
|
||||
http.Error(w, fmt.Sprintf("Adapting config from %s: %v", adapterName, err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(warnings) > 0 {
|
||||
respBody, err := json.Marshal(warnings)
|
||||
if err != nil {
|
||||
log.Printf("[ADMIN][ERROR] marshaling warnings: %v", err)
|
||||
}
|
||||
w.Write(respBody)
|
||||
}
|
||||
payload = bytes.NewReader(result)
|
||||
}
|
||||
}
|
||||
|
||||
err := Load(payload)
|
||||
if err != nil {
|
||||
log.Printf("[ADMIN][ERROR] loading config: %v", err)
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func handleStop(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
log.Println("[ADMIN] Initiating shutdown")
|
||||
if err := stopAndCleanup(); err != nil {
|
||||
log.Printf("[ADMIN][ERROR] stopping: %v \n", err)
|
||||
}
|
||||
log.Println("[ADMIN] Exiting")
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func stopAndCleanup() error {
|
||||
if err := Stop(); err != nil {
|
||||
return err
|
||||
}
|
||||
certmagic.CleanUpOwnLocks()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Load loads and starts a configuration.
|
||||
func Load(r io.Reader) error {
|
||||
buf := bufPool.Get().(*bytes.Buffer)
|
||||
buf.Reset()
|
||||
defer bufPool.Put(buf)
|
||||
|
||||
_, err := io.Copy(buf, io.LimitReader(r, 1024*1024))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var cfg *Config
|
||||
err = json.Unmarshal(buf.Bytes(), &cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decoding config: %v", err)
|
||||
}
|
||||
|
||||
err = Run(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("running: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DefaultAdminListen is the address for the admin
|
||||
// listener, if none is specified at startup.
|
||||
var DefaultAdminListen = "localhost:2019"
|
||||
|
||||
var bufPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return new(bytes.Buffer)
|
||||
},
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddy
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkLoad(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
r := strings.NewReader(`{
|
||||
"testval": "Yippee!",
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"myserver": {
|
||||
"listen": ["tcp/localhost:8080-8084"],
|
||||
"read_timeout": "30s"
|
||||
},
|
||||
"yourserver": {
|
||||
"listen": ["127.0.0.1:5000"],
|
||||
"read_header_timeout": "15s"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`)
|
||||
Load(r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
version: "{build}"
|
||||
|
||||
os: Windows Server 2012 R2
|
||||
|
||||
clone_folder: c:\gopath\src\github.com\mholt\caddy
|
||||
|
||||
environment:
|
||||
GOPATH: c:\gopath
|
||||
|
||||
install:
|
||||
- rmdir c:\go /s /q
|
||||
- appveyor DownloadFile https://storage.googleapis.com/golang/go1.7.4.windows-amd64.zip
|
||||
- 7z x go1.7.4.windows-amd64.zip -y -oC:\ > NUL
|
||||
- go version
|
||||
- go env
|
||||
- go get -t ./...
|
||||
- go get github.com/golang/lint/golint
|
||||
- go get github.com/gordonklaus/ineffassign
|
||||
- set PATH=%GOPATH%\bin;%PATH%
|
||||
|
||||
build: off
|
||||
|
||||
test_script:
|
||||
- go vet ./...
|
||||
- go test -race ./...
|
||||
- ineffassign .
|
||||
|
||||
after_test:
|
||||
- golint ./...
|
||||
|
||||
deploy: off
|
||||
@@ -0,0 +1,34 @@
|
||||
package caddy
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// AssetsPath returns the path to the folder
|
||||
// where the application may store data. If
|
||||
// CADDYPATH env variable is set, that value
|
||||
// is used. Otherwise, the path is the result
|
||||
// of evaluating "$HOME/.caddy".
|
||||
func AssetsPath() string {
|
||||
if caddyPath := os.Getenv("CADDYPATH"); caddyPath != "" {
|
||||
return caddyPath
|
||||
}
|
||||
return filepath.Join(userHomeDir(), ".caddy")
|
||||
}
|
||||
|
||||
// userHomeDir returns the user's home directory according to
|
||||
// environment variables.
|
||||
//
|
||||
// Credit: http://stackoverflow.com/a/7922977/1048862
|
||||
func userHomeDir() string {
|
||||
if runtime.GOOS == "windows" {
|
||||
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
|
||||
if home == "" {
|
||||
home = os.Getenv("USERPROFILE")
|
||||
}
|
||||
return home
|
||||
}
|
||||
return os.Getenv("HOME")
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package caddy
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAssetsPath(t *testing.T) {
|
||||
if actual := AssetsPath(); !strings.HasSuffix(actual, ".caddy") {
|
||||
t.Errorf("Expected path to be a .caddy folder, got: %v", actual)
|
||||
}
|
||||
|
||||
os.Setenv("CADDYPATH", "testpath")
|
||||
if actual, expected := AssetsPath(), "testpath"; actual != expected {
|
||||
t.Errorf("Expected path to be %v, got: %v", expected, actual)
|
||||
}
|
||||
os.Setenv("CADDYPATH", "")
|
||||
}
|
||||
Executable
+56
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Caddy build script. Automates proper versioning.
|
||||
#
|
||||
# Usage:
|
||||
#
|
||||
# $ ./build.bash [output_filename] [git_repo]
|
||||
#
|
||||
# Outputs compiled program in current directory.
|
||||
# Default git repo is current directory.
|
||||
# Builds always take place from current directory.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
: ${output_filename:="${1:-}"}
|
||||
: ${output_filename:=""}
|
||||
|
||||
: ${git_repo:="${2:-}"}
|
||||
: ${git_repo:="."}
|
||||
|
||||
pkg=github.com/mholt/caddy/caddy/caddymain
|
||||
ldflags=()
|
||||
|
||||
# Timestamp of build
|
||||
name="${pkg}.buildDate"
|
||||
value=$(date -u +"%a %b %d %H:%M:%S %Z %Y")
|
||||
ldflags+=("-X" "\"${name}=${value}\"")
|
||||
|
||||
# Current tag, if HEAD is on a tag
|
||||
name="${pkg}.gitTag"
|
||||
set +e
|
||||
value="$(git -C "${git_repo}" describe --exact-match HEAD 2>/dev/null)"
|
||||
set -e
|
||||
ldflags+=("-X" "\"${name}=${value}\"")
|
||||
|
||||
# Nearest tag on branch
|
||||
name="${pkg}.gitNearestTag"
|
||||
value="$(git -C "${git_repo}" describe --abbrev=0 --tags HEAD)"
|
||||
ldflags+=("-X" "\"${name}=${value}\"")
|
||||
|
||||
# Commit SHA
|
||||
name="${pkg}.gitCommit"
|
||||
value="$(git -C "${git_repo}" rev-parse --short HEAD)"
|
||||
ldflags+=("-X" "\"${name}=${value}\"")
|
||||
|
||||
# Summary of uncommitted changes
|
||||
name="${pkg}.gitShortStat"
|
||||
value="$(git -C "${git_repo}" diff-index --shortstat HEAD)"
|
||||
ldflags+=("-X" "\"${name}=${value}\"")
|
||||
|
||||
# List of modified files
|
||||
name="${pkg}.gitFilesModified"
|
||||
value="$(git -C "${git_repo}" diff-index --name-only HEAD)"
|
||||
ldflags+=("-X" "\"${name}=${value}\"")
|
||||
|
||||
go build -ldflags "${ldflags[*]}" -o "${output_filename}"
|
||||
@@ -0,0 +1,290 @@
|
||||
package caddymain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
|
||||
"github.com/xenolf/lego/acme"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
// plug in the HTTP server type
|
||||
_ "github.com/mholt/caddy/caddyhttp"
|
||||
|
||||
"github.com/mholt/caddy/caddytls"
|
||||
// This is where other plugins get plugged in (imported)
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.TrapSignals()
|
||||
setVersion()
|
||||
|
||||
flag.BoolVar(&caddytls.Agreed, "agree", false, "Agree to the CA's Subscriber Agreement")
|
||||
flag.StringVar(&caddytls.DefaultCAUrl, "ca", "https://acme-v01.api.letsencrypt.org/directory", "URL to certificate authority's ACME server directory")
|
||||
flag.StringVar(&conf, "conf", "", "Caddyfile to load (default \""+caddy.DefaultConfigFile+"\")")
|
||||
flag.StringVar(&cpu, "cpu", "100%", "CPU cap")
|
||||
flag.BoolVar(&plugins, "plugins", false, "List installed plugins")
|
||||
flag.StringVar(&caddytls.DefaultEmail, "email", "", "Default ACME CA account email address")
|
||||
flag.DurationVar(&acme.HTTPClient.Timeout, "catimeout", acme.HTTPClient.Timeout, "Default ACME CA HTTP timeout")
|
||||
flag.StringVar(&logfile, "log", "", "Process log file")
|
||||
flag.StringVar(&caddy.PidFile, "pidfile", "", "Path to write pid file")
|
||||
flag.BoolVar(&caddy.Quiet, "quiet", false, "Quiet mode (no initialization output)")
|
||||
flag.StringVar(&revoke, "revoke", "", "Hostname for which to revoke the certificate")
|
||||
flag.StringVar(&serverType, "type", "http", "Type of server to run")
|
||||
flag.BoolVar(&version, "version", false, "Show version")
|
||||
|
||||
caddy.RegisterCaddyfileLoader("flag", caddy.LoaderFunc(confLoader))
|
||||
caddy.SetDefaultCaddyfileLoader("default", caddy.LoaderFunc(defaultLoader))
|
||||
}
|
||||
|
||||
// Run is Caddy's main() function.
|
||||
func Run() {
|
||||
flag.Parse()
|
||||
|
||||
caddy.AppName = appName
|
||||
caddy.AppVersion = appVersion
|
||||
acme.UserAgent = appName + "/" + appVersion
|
||||
|
||||
// Set up process log before anything bad happens
|
||||
switch logfile {
|
||||
case "stdout":
|
||||
log.SetOutput(os.Stdout)
|
||||
case "stderr":
|
||||
log.SetOutput(os.Stderr)
|
||||
case "":
|
||||
log.SetOutput(ioutil.Discard)
|
||||
default:
|
||||
log.SetOutput(&lumberjack.Logger{
|
||||
Filename: logfile,
|
||||
MaxSize: 100,
|
||||
MaxAge: 14,
|
||||
MaxBackups: 10,
|
||||
})
|
||||
}
|
||||
|
||||
// Check for one-time actions
|
||||
if revoke != "" {
|
||||
err := caddytls.Revoke(revoke)
|
||||
if err != nil {
|
||||
mustLogFatalf(err.Error())
|
||||
}
|
||||
fmt.Printf("Revoked certificate for %s\n", revoke)
|
||||
os.Exit(0)
|
||||
}
|
||||
if version {
|
||||
fmt.Printf("%s %s\n", appName, appVersion)
|
||||
if devBuild && gitShortStat != "" {
|
||||
fmt.Printf("%s\n%s\n", gitShortStat, gitFilesModified)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
if plugins {
|
||||
fmt.Println(caddy.DescribePlugins())
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
moveStorage() // TODO: This is temporary for the 0.9 release, or until most users upgrade to 0.9+
|
||||
|
||||
// Set CPU cap
|
||||
err := setCPU(cpu)
|
||||
if err != nil {
|
||||
mustLogFatalf(err.Error())
|
||||
}
|
||||
|
||||
// Get Caddyfile input
|
||||
caddyfile, err := caddy.LoadCaddyfile(serverType)
|
||||
if err != nil {
|
||||
mustLogFatalf(err.Error())
|
||||
}
|
||||
|
||||
// Start your engines
|
||||
instance, err := caddy.Start(caddyfile)
|
||||
if err != nil {
|
||||
mustLogFatalf(err.Error())
|
||||
}
|
||||
|
||||
// Twiddle your thumbs
|
||||
instance.Wait()
|
||||
}
|
||||
|
||||
// mustLogFatalf wraps log.Fatalf() in a way that ensures the
|
||||
// output is always printed to stderr so the user can see it
|
||||
// if the user is still there, even if the process log was not
|
||||
// enabled. If this process is an upgrade, however, and the user
|
||||
// might not be there anymore, this just logs to the process
|
||||
// log and exits.
|
||||
func mustLogFatalf(format string, args ...interface{}) {
|
||||
if !caddy.IsUpgrade() {
|
||||
log.SetOutput(os.Stderr)
|
||||
}
|
||||
log.Fatalf(format, args...)
|
||||
}
|
||||
|
||||
// confLoader loads the Caddyfile using the -conf flag.
|
||||
func confLoader(serverType string) (caddy.Input, error) {
|
||||
if conf == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if conf == "stdin" {
|
||||
return caddy.CaddyfileFromPipe(os.Stdin, serverType)
|
||||
}
|
||||
|
||||
contents, err := ioutil.ReadFile(conf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return caddy.CaddyfileInput{
|
||||
Contents: contents,
|
||||
Filepath: conf,
|
||||
ServerTypeName: serverType,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// defaultLoader loads the Caddyfile from the current working directory.
|
||||
func defaultLoader(serverType string) (caddy.Input, error) {
|
||||
contents, err := ioutil.ReadFile(caddy.DefaultConfigFile)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return caddy.CaddyfileInput{
|
||||
Contents: contents,
|
||||
Filepath: caddy.DefaultConfigFile,
|
||||
ServerTypeName: serverType,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// moveStorage moves the old certificate storage location by
|
||||
// renaming the "letsencrypt" folder to the hostname of the
|
||||
// CA URL. This is TEMPORARY until most users have upgraded to 0.9+.
|
||||
func moveStorage() {
|
||||
oldPath := filepath.Join(caddy.AssetsPath(), "letsencrypt")
|
||||
_, err := os.Stat(oldPath)
|
||||
if os.IsNotExist(err) {
|
||||
return
|
||||
}
|
||||
// Just use a default config to get default (file) storage
|
||||
fileStorage, err := new(caddytls.Config).StorageFor(caddytls.DefaultCAUrl)
|
||||
if err != nil {
|
||||
mustLogFatalf("[ERROR] Unable to get new path for certificate storage: %v", err)
|
||||
}
|
||||
newPath := fileStorage.(*caddytls.FileStorage).Path
|
||||
err = os.MkdirAll(string(newPath), 0700)
|
||||
if err != nil {
|
||||
mustLogFatalf("[ERROR] Unable to make new certificate storage path: %v\n\nPlease follow instructions at:\nhttps://github.com/mholt/caddy/issues/902#issuecomment-228876011", err)
|
||||
}
|
||||
err = os.Rename(oldPath, string(newPath))
|
||||
if err != nil {
|
||||
mustLogFatalf("[ERROR] Unable to migrate certificate storage: %v\n\nPlease follow instructions at:\nhttps://github.com/mholt/caddy/issues/902#issuecomment-228876011", err)
|
||||
}
|
||||
// convert mixed case folder and file names to lowercase
|
||||
var done bool // walking is recursive and preloads the file names, so we must restart walk after a change until no changes
|
||||
for !done {
|
||||
done = true
|
||||
filepath.Walk(string(newPath), func(path string, info os.FileInfo, err error) error {
|
||||
// must be careful to only lowercase the base of the path, not the whole thing!!
|
||||
base := filepath.Base(path)
|
||||
if lowerBase := strings.ToLower(base); base != lowerBase {
|
||||
lowerPath := filepath.Join(filepath.Dir(path), lowerBase)
|
||||
err = os.Rename(path, lowerPath)
|
||||
if err != nil {
|
||||
mustLogFatalf("[ERROR] Unable to lower-case: %v\n\nPlease follow instructions at:\nhttps://github.com/mholt/caddy/issues/902#issuecomment-228876011", err)
|
||||
}
|
||||
// terminate traversal and restart since Walk needs the updated file list with new file names
|
||||
done = false
|
||||
return errors.New("start over")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// setVersion figures out the version information
|
||||
// based on variables set by -ldflags.
|
||||
func setVersion() {
|
||||
// A development build is one that's not at a tag or has uncommitted changes
|
||||
devBuild = gitTag == "" || gitShortStat != ""
|
||||
|
||||
// Only set the appVersion if -ldflags was used
|
||||
if gitNearestTag != "" || gitTag != "" {
|
||||
if devBuild && gitNearestTag != "" {
|
||||
appVersion = fmt.Sprintf("%s (+%s %s)",
|
||||
strings.TrimPrefix(gitNearestTag, "v"), gitCommit, buildDate)
|
||||
} else if gitTag != "" {
|
||||
appVersion = strings.TrimPrefix(gitTag, "v")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// setCPU parses string cpu and sets GOMAXPROCS
|
||||
// according to its value. It accepts either
|
||||
// a number (e.g. 3) or a percent (e.g. 50%).
|
||||
func setCPU(cpu string) error {
|
||||
var numCPU int
|
||||
|
||||
availCPU := runtime.NumCPU()
|
||||
|
||||
if strings.HasSuffix(cpu, "%") {
|
||||
// Percent
|
||||
var percent float32
|
||||
pctStr := cpu[:len(cpu)-1]
|
||||
pctInt, err := strconv.Atoi(pctStr)
|
||||
if err != nil || pctInt < 1 || pctInt > 100 {
|
||||
return errors.New("invalid CPU value: percentage must be between 1-100")
|
||||
}
|
||||
percent = float32(pctInt) / 100
|
||||
numCPU = int(float32(availCPU) * percent)
|
||||
} else {
|
||||
// Number
|
||||
num, err := strconv.Atoi(cpu)
|
||||
if err != nil || num < 1 {
|
||||
return errors.New("invalid CPU value: provide a number or percent greater than 0")
|
||||
}
|
||||
numCPU = num
|
||||
}
|
||||
|
||||
if numCPU > availCPU {
|
||||
numCPU = availCPU
|
||||
}
|
||||
|
||||
runtime.GOMAXPROCS(numCPU)
|
||||
return nil
|
||||
}
|
||||
|
||||
const appName = "Caddy"
|
||||
|
||||
// Flags that control program flow or startup
|
||||
var (
|
||||
serverType string
|
||||
conf string
|
||||
cpu string
|
||||
logfile string
|
||||
revoke string
|
||||
version bool
|
||||
plugins bool
|
||||
)
|
||||
|
||||
// Build information obtained with the help of -ldflags
|
||||
var (
|
||||
appVersion = "(untracked dev build)" // inferred at startup
|
||||
devBuild = true // inferred at startup
|
||||
|
||||
buildDate string // date -u
|
||||
gitTag string // git describe --exact-match HEAD 2> /dev/null
|
||||
gitNearestTag string // git describe --abbrev=0 --tags HEAD
|
||||
gitCommit string // git rev-parse HEAD
|
||||
gitShortStat string // git diff-index --shortstat
|
||||
gitFilesModified string // git diff-index --name-only HEAD
|
||||
)
|
||||
@@ -0,0 +1,44 @@
|
||||
package caddymain
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSetCPU(t *testing.T) {
|
||||
currentCPU := runtime.GOMAXPROCS(-1)
|
||||
maxCPU := runtime.NumCPU()
|
||||
halfCPU := int(0.5 * float32(maxCPU))
|
||||
if halfCPU < 1 {
|
||||
halfCPU = 1
|
||||
}
|
||||
for i, test := range []struct {
|
||||
input string
|
||||
output int
|
||||
shouldErr bool
|
||||
}{
|
||||
{"1", 1, false},
|
||||
{"-1", currentCPU, true},
|
||||
{"0", currentCPU, true},
|
||||
{"100%", maxCPU, false},
|
||||
{"50%", halfCPU, false},
|
||||
{"110%", currentCPU, true},
|
||||
{"-10%", currentCPU, true},
|
||||
{"invalid input", currentCPU, true},
|
||||
{"invalid input%", currentCPU, true},
|
||||
{"9999", maxCPU, false}, // over available CPU
|
||||
} {
|
||||
err := setCPU(test.input)
|
||||
if test.shouldErr && err == nil {
|
||||
t.Errorf("Test %d: Expected error, but there wasn't any", i)
|
||||
}
|
||||
if !test.shouldErr && err != nil {
|
||||
t.Errorf("Test %d: Expected no error, but there was one: %v", i, err)
|
||||
}
|
||||
if actual, expected := runtime.GOMAXPROCS(-1), test.output; actual != expected {
|
||||
t.Errorf("Test %d: GOMAXPROCS was %d but expected %d", i, actual, expected)
|
||||
}
|
||||
// teardown
|
||||
runtime.GOMAXPROCS(currentCPU)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// By moving the application's package main logic into
|
||||
// a package other than main, it becomes much easier to
|
||||
// wrap caddy for custom builds that are go-gettable.
|
||||
// https://forum.caddyserver.com/t/my-wish-for-0-9-go-gettable-custom-builds/59?u=matt
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/mholt/caddy/caddy/caddymain"
|
||||
|
||||
var run = caddymain.Run // replaced for tests
|
||||
|
||||
func main() {
|
||||
run()
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
// This works because it does not have the same signature as the
|
||||
// conventional "TestMain" function described in the testing package
|
||||
// godoc.
|
||||
func TestMain(t *testing.T) {
|
||||
var ran bool
|
||||
run = func() {
|
||||
ran = true
|
||||
}
|
||||
main()
|
||||
if !ran {
|
||||
t.Error("Expected Run() to be called, but it wasn't")
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package caddy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
/*
|
||||
// TODO
|
||||
func TestCaddyStartStop(t *testing.T) {
|
||||
caddyfile := "localhost:1984"
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
_, err := Start(CaddyfileInput{Contents: []byte(caddyfile)})
|
||||
if err != nil {
|
||||
t.Fatalf("Error starting, iteration %d: %v", i, err)
|
||||
}
|
||||
|
||||
client := http.Client{
|
||||
Timeout: time.Duration(2 * time.Second),
|
||||
}
|
||||
resp, err := client.Get("http://localhost:1984")
|
||||
if err != nil {
|
||||
t.Fatalf("Expected GET request to succeed (iteration %d), but it failed: %v", i, err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
err = Stop()
|
||||
if err != nil {
|
||||
t.Fatalf("Error stopping, iteration %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
func TestIsLoopback(t *testing.T) {
|
||||
for i, test := range []struct {
|
||||
input string
|
||||
expect bool
|
||||
}{
|
||||
{"example.com", false},
|
||||
{"localhost", true},
|
||||
{"localhost:1234", true},
|
||||
{"localhost:", true},
|
||||
{"127.0.0.1", true},
|
||||
{"127.0.0.1:443", true},
|
||||
{"127.0.1.5", true},
|
||||
{"10.0.0.5", false},
|
||||
{"12.7.0.1", false},
|
||||
{"[::1]", true},
|
||||
{"[::1]:1234", true},
|
||||
{"::1", true},
|
||||
{"::", false},
|
||||
{"[::]", false},
|
||||
{"local", false},
|
||||
} {
|
||||
if got, want := IsLoopback(test.input), test.expect; got != want {
|
||||
t.Errorf("Test %d (%s): expected %v but was %v", i, test.input, want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListenerAddrEqual(t *testing.T) {
|
||||
ln1, err := net.Listen("tcp", "[::]:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln1.Close()
|
||||
|
||||
ln1port := strconv.Itoa(ln1.Addr().(*net.TCPAddr).Port)
|
||||
|
||||
ln2, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln2.Close()
|
||||
|
||||
ln2port := strconv.Itoa(ln2.Addr().(*net.TCPAddr).Port)
|
||||
|
||||
for i, test := range []struct {
|
||||
ln net.Listener
|
||||
addr string
|
||||
expect bool
|
||||
}{
|
||||
{ln1, ":1234", false},
|
||||
{ln1, "0.0.0.0:1234", false},
|
||||
{ln1, "0.0.0.0", false},
|
||||
{ln1, ":" + ln1port + "", true},
|
||||
{ln1, "0.0.0.0:" + ln1port + "", true},
|
||||
{ln2, ":" + ln2port + "", false},
|
||||
{ln2, "127.0.0.1:1234", false},
|
||||
{ln2, "127.0.0.1", false},
|
||||
{ln2, "127.0.0.1:" + ln2port + "", true},
|
||||
} {
|
||||
if got, want := listenerAddrEqual(test.ln, test.addr), test.expect; got != want {
|
||||
t.Errorf("Test %d (%s == %s): expected %v but was %v", i, test.addr, test.ln.Addr().String(), want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
)
|
||||
|
||||
// Adapter adapts Caddyfile to Caddy JSON.
|
||||
type Adapter struct {
|
||||
ServerType ServerType
|
||||
}
|
||||
|
||||
// Adapt converts the Caddyfile config in body to Caddy JSON.
|
||||
func (a Adapter) Adapt(body []byte, options map[string]interface{}) ([]byte, []caddyconfig.Warning, error) {
|
||||
if a.ServerType == nil {
|
||||
return nil, nil, fmt.Errorf("no server type")
|
||||
}
|
||||
if options == nil {
|
||||
options = make(map[string]interface{})
|
||||
}
|
||||
|
||||
filename, _ := options["filename"].(string)
|
||||
if filename == "" {
|
||||
filename = "Caddyfile"
|
||||
}
|
||||
|
||||
serverBlocks, err := Parse(filename, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
cfg, warnings, err := a.ServerType.Setup(serverBlocks, options)
|
||||
if err != nil {
|
||||
return nil, warnings, err
|
||||
}
|
||||
|
||||
marshalFunc := json.Marshal
|
||||
if options["pretty"] == "true" {
|
||||
marshalFunc = caddyconfig.JSONIndent
|
||||
}
|
||||
result, err := marshalFunc(cfg)
|
||||
|
||||
return result, warnings, err
|
||||
}
|
||||
|
||||
// Unmarshaler is a type that can unmarshal
|
||||
// Caddyfile tokens to set itself up for a
|
||||
// JSON encoding. The goal of an unmarshaler
|
||||
// is not to set itself up for actual use,
|
||||
// but to set itself up for being marshaled
|
||||
// into JSON. Caddyfile-unmarshaled values
|
||||
// will not be used directly; they will be
|
||||
// encoded as JSON and then used from that.
|
||||
type Unmarshaler interface {
|
||||
UnmarshalCaddyfile(d *Dispenser) error
|
||||
}
|
||||
|
||||
// ServerType is a type that can evaluate a Caddyfile and set up a caddy config.
|
||||
type ServerType interface {
|
||||
// Setup takes the server blocks which
|
||||
// contain tokens, as well as options
|
||||
// (e.g. CLI flags) and creates a Caddy
|
||||
// config, along with any warnings or
|
||||
// an error.
|
||||
Setup([]ServerBlock, map[string]interface{}) (*caddy.Config, []caddyconfig.Warning, error)
|
||||
}
|
||||
|
||||
// Interface guard
|
||||
var _ caddyconfig.Adapter = (*Adapter)(nil)
|
||||
@@ -1,371 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Dispenser is a type that dispenses tokens, similarly to a lexer,
|
||||
// except that it can do so with some notion of structure. An empty
|
||||
// Dispenser is invalid; call NewDispenser to make a proper instance.
|
||||
type Dispenser struct {
|
||||
tokens []Token
|
||||
cursor int
|
||||
nesting int
|
||||
}
|
||||
|
||||
// NewDispenser returns a Dispenser filled with the given tokens.
|
||||
func NewDispenser(tokens []Token) *Dispenser {
|
||||
return &Dispenser{
|
||||
tokens: tokens,
|
||||
cursor: -1,
|
||||
}
|
||||
}
|
||||
|
||||
// Next loads the next token. Returns true if a token
|
||||
// was loaded; false otherwise. If false, all tokens
|
||||
// have been consumed.
|
||||
func (d *Dispenser) Next() bool {
|
||||
if d.cursor < len(d.tokens)-1 {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Prev moves to the previous token. It does the inverse
|
||||
// of Next(), except this function may decrement the cursor
|
||||
// to -1 so that the next call to Next() points to the
|
||||
// first token; this allows dispensing to "start over". This
|
||||
// method returns true if the cursor ends up pointing to a
|
||||
// valid token.
|
||||
func (d *Dispenser) Prev() bool {
|
||||
if d.cursor > -1 {
|
||||
d.cursor--
|
||||
return d.cursor > -1
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NextArg loads the next token if it is on the same
|
||||
// line and if it is not a block opening (open curly
|
||||
// brace). Returns true if an argument token was
|
||||
// loaded; false otherwise. If false, all tokens on
|
||||
// the line have been consumed except for potentially
|
||||
// a block opening. It handles imported tokens
|
||||
// correctly.
|
||||
func (d *Dispenser) NextArg() bool {
|
||||
if !d.nextOnSameLine() {
|
||||
return false
|
||||
}
|
||||
if d.Val() == "{" {
|
||||
// roll back; a block opening is not an argument
|
||||
d.cursor--
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// nextOnSameLine advances the cursor if the next
|
||||
// token is on the same line of the same file.
|
||||
func (d *Dispenser) nextOnSameLine() bool {
|
||||
if d.cursor < 0 {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
if d.cursor >= len(d.tokens) {
|
||||
return false
|
||||
}
|
||||
if d.cursor < len(d.tokens)-1 &&
|
||||
d.tokens[d.cursor].File == d.tokens[d.cursor+1].File &&
|
||||
d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) == d.tokens[d.cursor+1].Line {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NextLine loads the next token only if it is not on the same
|
||||
// line as the current token, and returns true if a token was
|
||||
// loaded; false otherwise. If false, there is not another token
|
||||
// or it is on the same line. It handles imported tokens correctly.
|
||||
func (d *Dispenser) NextLine() bool {
|
||||
if d.cursor < 0 {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
if d.cursor >= len(d.tokens) {
|
||||
return false
|
||||
}
|
||||
if d.cursor < len(d.tokens)-1 &&
|
||||
(d.tokens[d.cursor].File != d.tokens[d.cursor+1].File ||
|
||||
d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) < d.tokens[d.cursor+1].Line) {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NextBlock can be used as the condition of a for loop
|
||||
// to load the next token as long as it opens a block or
|
||||
// is already in a block nested more than initialNestingLevel.
|
||||
// In other words, a loop over NextBlock() will iterate
|
||||
// all tokens in the block assuming the next token is an
|
||||
// open curly brace, until the matching closing brace.
|
||||
// The open and closing brace tokens for the outer-most
|
||||
// block will be consumed internally and omitted from
|
||||
// the iteration.
|
||||
//
|
||||
// Proper use of this method looks like this:
|
||||
//
|
||||
// for nesting := d.Nesting(); d.NextBlock(nesting); {
|
||||
// }
|
||||
//
|
||||
// However, in simple cases where it is known that the
|
||||
// Dispenser is new and has not already traversed state
|
||||
// by a loop over NextBlock(), this will do:
|
||||
//
|
||||
// for d.NextBlock(0) {
|
||||
// }
|
||||
//
|
||||
// As with other token parsing logic, a loop over
|
||||
// NextBlock() should be contained within a loop over
|
||||
// Next(), as it is usually prudent to skip the initial
|
||||
// token.
|
||||
func (d *Dispenser) NextBlock(initialNestingLevel int) bool {
|
||||
if d.nesting > initialNestingLevel {
|
||||
if !d.Next() {
|
||||
return false // should be EOF error
|
||||
}
|
||||
if d.Val() == "}" {
|
||||
d.nesting--
|
||||
}
|
||||
return d.nesting > initialNestingLevel
|
||||
}
|
||||
if !d.nextOnSameLine() { // block must open on same line
|
||||
return false
|
||||
}
|
||||
if d.Val() != "{" {
|
||||
d.cursor-- // roll back if not opening brace
|
||||
return false
|
||||
}
|
||||
d.Next() // consume open curly brace
|
||||
if d.Val() == "}" {
|
||||
return false // open and then closed right away
|
||||
}
|
||||
d.nesting++
|
||||
return true
|
||||
}
|
||||
|
||||
// Nesting returns the current nesting level. Necessary
|
||||
// if using NextBlock()
|
||||
func (d *Dispenser) Nesting() int {
|
||||
return d.nesting
|
||||
}
|
||||
|
||||
// Val gets the text of the current token. If there is no token
|
||||
// loaded, it returns empty string.
|
||||
func (d *Dispenser) Val() string {
|
||||
if d.cursor < 0 || d.cursor >= len(d.tokens) {
|
||||
return ""
|
||||
}
|
||||
return d.tokens[d.cursor].Text
|
||||
}
|
||||
|
||||
// Line gets the line number of the current token.
|
||||
// If there is no token loaded, it returns 0.
|
||||
func (d *Dispenser) Line() int {
|
||||
if d.cursor < 0 || d.cursor >= len(d.tokens) {
|
||||
return 0
|
||||
}
|
||||
return d.tokens[d.cursor].Line
|
||||
}
|
||||
|
||||
// File gets the filename where the current token originated.
|
||||
func (d *Dispenser) File() string {
|
||||
if d.cursor < 0 || d.cursor >= len(d.tokens) {
|
||||
return ""
|
||||
}
|
||||
return d.tokens[d.cursor].File
|
||||
}
|
||||
|
||||
// Args is a convenience function that loads the next arguments
|
||||
// (tokens on the same line) into an arbitrary number of strings
|
||||
// pointed to in targets. If there are not enough argument tokens
|
||||
// available to fill targets, false is returned and the remaining
|
||||
// targets are left unchanged. If all the targets are filled,
|
||||
// then true is returned.
|
||||
func (d *Dispenser) Args(targets ...*string) bool {
|
||||
for i := 0; i < len(targets); i++ {
|
||||
if !d.NextArg() {
|
||||
return false
|
||||
}
|
||||
*targets[i] = d.Val()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// AllArgs is like Args, but if there are more argument tokens
|
||||
// available than there are targets, false is returned. The
|
||||
// number of available argument tokens must match the number of
|
||||
// targets exactly to return true.
|
||||
func (d *Dispenser) AllArgs(targets ...*string) bool {
|
||||
if !d.Args(targets...) {
|
||||
return false
|
||||
}
|
||||
if d.NextArg() {
|
||||
d.Prev()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// RemainingArgs loads any more arguments (tokens on the same line)
|
||||
// into a slice and returns them. Open curly brace tokens also indicate
|
||||
// the end of arguments, and the curly brace is not included in
|
||||
// the return value nor is it loaded.
|
||||
func (d *Dispenser) RemainingArgs() []string {
|
||||
var args []string
|
||||
for d.NextArg() {
|
||||
args = append(args, d.Val())
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
// NewFromNextTokens returns a new dispenser with a copy of
|
||||
// the tokens from the current token until the end of the
|
||||
// "directive" whether that be to the end of the line or
|
||||
// the end of a block that starts at the end of the line;
|
||||
// in other words, until the end of the segment.
|
||||
func (d *Dispenser) NewFromNextTokens() *Dispenser {
|
||||
tkns := []Token{d.Token()}
|
||||
for d.NextArg() {
|
||||
tkns = append(tkns, d.Token())
|
||||
}
|
||||
var openedBlock bool
|
||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
||||
if !openedBlock {
|
||||
// because NextBlock() consumes the initial open
|
||||
// curly brace, we rewind here to append it, since
|
||||
// our case is special in that we want to include
|
||||
// all the tokens including surrounding curly braces
|
||||
// for a new dispenser to have
|
||||
d.Prev()
|
||||
tkns = append(tkns, d.Token())
|
||||
d.Next()
|
||||
openedBlock = true
|
||||
}
|
||||
tkns = append(tkns, d.Token())
|
||||
}
|
||||
if openedBlock {
|
||||
// include closing brace accordingly
|
||||
tkns = append(tkns, d.Token())
|
||||
}
|
||||
return NewDispenser(tkns)
|
||||
}
|
||||
|
||||
// Token returns the current token.
|
||||
func (d *Dispenser) Token() Token {
|
||||
if d.cursor < 0 || d.cursor >= len(d.tokens) {
|
||||
return Token{}
|
||||
}
|
||||
return d.tokens[d.cursor]
|
||||
}
|
||||
|
||||
// Reset sets d's cursor to the beginning, as
|
||||
// if this was a new and unused dispenser.
|
||||
func (d *Dispenser) Reset() {
|
||||
d.cursor = -1
|
||||
d.nesting = 0
|
||||
}
|
||||
|
||||
// ArgErr returns an argument error, meaning that another
|
||||
// argument was expected but not found. In other words,
|
||||
// a line break or open curly brace was encountered instead of
|
||||
// an argument.
|
||||
func (d *Dispenser) ArgErr() error {
|
||||
if d.Val() == "{" {
|
||||
return d.Err("Unexpected token '{', expecting argument")
|
||||
}
|
||||
return d.Errf("Wrong argument count or unexpected line ending after '%s'", d.Val())
|
||||
}
|
||||
|
||||
// SyntaxErr creates a generic syntax error which explains what was
|
||||
// found and what was expected.
|
||||
func (d *Dispenser) SyntaxErr(expected string) error {
|
||||
msg := fmt.Sprintf("%s:%d - Syntax error: Unexpected token '%s', expecting '%s'", d.File(), d.Line(), d.Val(), expected)
|
||||
return errors.New(msg)
|
||||
}
|
||||
|
||||
// EOFErr returns an error indicating that the dispenser reached
|
||||
// the end of the input when searching for the next token.
|
||||
func (d *Dispenser) EOFErr() error {
|
||||
return d.Errf("Unexpected EOF")
|
||||
}
|
||||
|
||||
// Err generates a custom parse-time error with a message of msg.
|
||||
func (d *Dispenser) Err(msg string) error {
|
||||
msg = fmt.Sprintf("%s:%d - Error during parsing: %s", d.File(), d.Line(), msg)
|
||||
return errors.New(msg)
|
||||
}
|
||||
|
||||
// Errf is like Err, but for formatted error messages
|
||||
func (d *Dispenser) Errf(format string, args ...interface{}) error {
|
||||
return d.Err(fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// Delete deletes the current token and returns the updated slice
|
||||
// of tokens. The cursor is not advanced to the next token.
|
||||
// Because deletion modifies the underlying slice, this method
|
||||
// should only be called if you have access to the original slice
|
||||
// of tokens and/or are using the slice of tokens outside this
|
||||
// Dispenser instance. If you do not re-assign the slice with the
|
||||
// return value of this method, inconsistencies in the token
|
||||
// array will become apparent (or worse, hide from you like they
|
||||
// did me for 3 and a half freaking hours late one night).
|
||||
func (d *Dispenser) Delete() []Token {
|
||||
if d.cursor >= 0 && d.cursor < len(d.tokens)-1 {
|
||||
d.tokens = append(d.tokens[:d.cursor], d.tokens[d.cursor+1:]...)
|
||||
d.cursor--
|
||||
}
|
||||
return d.tokens
|
||||
}
|
||||
|
||||
// numLineBreaks counts how many line breaks are in the token
|
||||
// value given by the token index tknIdx. It returns 0 if the
|
||||
// token does not exist or there are no line breaks.
|
||||
func (d *Dispenser) numLineBreaks(tknIdx int) int {
|
||||
if tknIdx < 0 || tknIdx >= len(d.tokens) {
|
||||
return 0
|
||||
}
|
||||
return strings.Count(d.tokens[tknIdx].Text, "\n")
|
||||
}
|
||||
|
||||
// isNewLine determines whether the current token is on a different
|
||||
// line (higher line number) than the previous token. It handles imported
|
||||
// tokens correctly. If there isn't a previous token, it returns true.
|
||||
func (d *Dispenser) isNewLine() bool {
|
||||
if d.cursor < 1 {
|
||||
return true
|
||||
}
|
||||
if d.cursor > len(d.tokens)-1 {
|
||||
return false
|
||||
}
|
||||
return d.tokens[d.cursor-1].File != d.tokens[d.cursor].File ||
|
||||
d.tokens[d.cursor-1].Line+d.numLineBreaks(d.cursor-1) < d.tokens[d.cursor].Line
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyconfig
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Adapter is a type which can adapt a configuration to Caddy JSON.
|
||||
// It returns the results and any warnings, or an error.
|
||||
type Adapter interface {
|
||||
Adapt(body []byte, options map[string]interface{}) ([]byte, []Warning, error)
|
||||
}
|
||||
|
||||
// Warning represents a warning or notice related to conversion.
|
||||
type Warning struct {
|
||||
File string
|
||||
Line int
|
||||
Directive string
|
||||
Message string
|
||||
}
|
||||
|
||||
// JSON encodes val as JSON, returning it as a json.RawMessage. Any
|
||||
// marshaling errors (which are highly unlikely with correct code)
|
||||
// are converted to warnings. This is convenient when filling config
|
||||
// structs that require a json.RawMessage, without having to worry
|
||||
// about errors.
|
||||
func JSON(val interface{}, warnings *[]Warning) json.RawMessage {
|
||||
b, err := json.Marshal(val)
|
||||
if err != nil {
|
||||
if warnings != nil {
|
||||
*warnings = append(*warnings, Warning{Message: err.Error()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// JSONModuleObject is like JSON, except it marshals val into a JSON object
|
||||
// and then adds a key to that object named fieldName with the value fieldVal.
|
||||
// This is useful for JSON-encoding module values where the module name has to
|
||||
// be described within the object by a certain key; for example,
|
||||
// "responder": "file_server" for a file server HTTP responder. The val must
|
||||
// encode into a map[string]interface{} (i.e. it must be a struct or map),
|
||||
// and any errors are converted into warnings, so this can be conveniently
|
||||
// used when filling a struct. For correct code, there should be no errors.
|
||||
func JSONModuleObject(val interface{}, fieldName, fieldVal string, warnings *[]Warning) json.RawMessage {
|
||||
// encode to a JSON object first
|
||||
enc, err := json.Marshal(val)
|
||||
if err != nil {
|
||||
if warnings != nil {
|
||||
*warnings = append(*warnings, Warning{Message: err.Error()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// then decode the object
|
||||
var tmp map[string]interface{}
|
||||
err = json.Unmarshal(enc, &tmp)
|
||||
if err != nil {
|
||||
if warnings != nil {
|
||||
*warnings = append(*warnings, Warning{Message: err.Error()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// so we can easily add the module's field with its appointed value
|
||||
tmp[fieldName] = fieldVal
|
||||
|
||||
// then re-marshal as JSON
|
||||
result, err := json.Marshal(tmp)
|
||||
if err != nil {
|
||||
if warnings != nil {
|
||||
*warnings = append(*warnings, Warning{Message: err.Error()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// JSONIndent is used to JSON-marshal the final resulting Caddy
|
||||
// configuration in a consistent, human-readable way.
|
||||
func JSONIndent(val interface{}) ([]byte, error) {
|
||||
return json.MarshalIndent(val, "", "\t")
|
||||
}
|
||||
|
||||
// RegisterAdapter registers a config adapter with the given name.
|
||||
// This should usually be done at init-time.
|
||||
func RegisterAdapter(name string, adapter Adapter) error {
|
||||
if _, ok := configAdapters[name]; ok {
|
||||
return fmt.Errorf("%s: already registered", name)
|
||||
}
|
||||
configAdapters[name] = adapter
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAdapter returns the adapter with the given name,
|
||||
// or nil if one with that name is not registered.
|
||||
func GetAdapter(name string) Adapter {
|
||||
return configAdapters[name]
|
||||
}
|
||||
|
||||
var configAdapters = make(map[string]Adapter)
|
||||
@@ -1,332 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||
"github.com/mholt/certmagic"
|
||||
)
|
||||
|
||||
// mapAddressToServerBlocks returns a map of listener address to list of server
|
||||
// blocks that will be served on that address. To do this, each server block is
|
||||
// expanded so that each one is considered individually, although keys of a
|
||||
// server block that share the same address stay grouped together so the config
|
||||
// isn't repeated unnecessarily. For example, this Caddyfile:
|
||||
//
|
||||
// example.com {
|
||||
// bind 127.0.0.1
|
||||
// }
|
||||
// www.example.com, example.net/path, localhost:9999 {
|
||||
// bind 127.0.0.1 1.2.3.4
|
||||
// }
|
||||
//
|
||||
// has two server blocks to start with. But expressed in this Caddyfile are
|
||||
// actually 4 listener addresses: 127.0.0.1:443, 1.2.3.4:443, 127.0.0.1:9999,
|
||||
// and 127.0.0.1:9999. This is because the bind directive is applied to each
|
||||
// key of its server block (specifying the host part), and each key may have
|
||||
// a different port. And we definitely need to be sure that a site which is
|
||||
// bound to be served on a specific interface is not served on others just
|
||||
// beceause that is more convenient: it would be a potential security risk
|
||||
// if the difference between interfaces means private vs. public.
|
||||
//
|
||||
// So what this function does for the example above is iterate each server
|
||||
// block, and for each server block, iterate its keys. For the first, it
|
||||
// finds one key (example.com) and determines its listener address
|
||||
// (127.0.0.1:443 - because of 'bind' and automatic HTTPS). It then adds
|
||||
// the listener address to the map value returned by this function, with
|
||||
// the first server block as one of its associations.
|
||||
//
|
||||
// It then iterates each key on the second server block and associates them
|
||||
// with one or more listener addresses. Indeed, each key in this block has
|
||||
// two listener addresses because of the 'bind' directive. Once we know
|
||||
// which addresses serve which keys, we can create a new server block for
|
||||
// each address containing the contents of the server block and only those
|
||||
// specific keys of the server block which use that address.
|
||||
//
|
||||
// It is possible and even likely that some keys in the returned map have
|
||||
// the exact same list of server blocks (i.e. they are identical). This
|
||||
// happens when multiple hosts are declared with a 'bind' directive and
|
||||
// the resulting listener addresses are not shared by any other server
|
||||
// block (or the other server blocks are exactly identical in their token
|
||||
// contents). This happens with our example above because 1.2.3.4:443
|
||||
// and 1.2.3.4:9999 are used exclusively with the second server block. This
|
||||
// repetition may be undesirable, so call consolidateAddrMappings() to map
|
||||
// multiple addresses to the same lists of server blocks (a many:many mapping).
|
||||
// (Doing this is essentially a map-reduce technique.)
|
||||
func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBlock) (map[string][]serverBlock, error) {
|
||||
sbmap := make(map[string][]serverBlock)
|
||||
|
||||
for i, sblock := range originalServerBlocks {
|
||||
// within a server block, we need to map all the listener addresses
|
||||
// implied by the server block to the keys of the server block which
|
||||
// will be served by them; this has the effect of treating each
|
||||
// key of a server block as its own, but without having to repeat its
|
||||
// contents in cases where multiple keys really can be served together
|
||||
addrToKeys := make(map[string][]string)
|
||||
for j, key := range sblock.block.Keys {
|
||||
// a key can have multiple listener addresses if there are multiple
|
||||
// arguments to the 'bind' directive (although they will all have
|
||||
// the same port, since the port is defined by the key or is implicit
|
||||
// through automatic HTTPS)
|
||||
addrs, err := st.listenerAddrsForServerBlockKey(sblock, key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("server block %d, key %d (%s): determining listener address: %v", i, j, key, err)
|
||||
}
|
||||
|
||||
// associate this key with each listener address it is served on
|
||||
for _, addr := range addrs {
|
||||
addrToKeys[addr] = append(addrToKeys[addr], key)
|
||||
}
|
||||
}
|
||||
|
||||
// now that we know which addresses serve which keys of this
|
||||
// server block, we iterate that mapping and create a list of
|
||||
// new server blocks for each address where the keys of the
|
||||
// server block are only the ones which use the address; but
|
||||
// the contents (tokens) are of course the same
|
||||
for addr, keys := range addrToKeys {
|
||||
sbmap[addr] = append(sbmap[addr], serverBlock{
|
||||
block: caddyfile.ServerBlock{
|
||||
Keys: keys,
|
||||
Segments: sblock.block.Segments,
|
||||
},
|
||||
pile: sblock.pile,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return sbmap, nil
|
||||
}
|
||||
|
||||
// consolidateAddrMappings eliminates repetition of identical server blocks in a mapping of
|
||||
// single listener addresses to lists of server blocks. Since multiple addresses may serve
|
||||
// identical sites (server block contents), this function turns a 1:many mapping into a
|
||||
// many:many mapping. Server block contents (tokens) must be exactly identical so that
|
||||
// reflect.DeepEqual returns true in order for the addresses to be combined. Identical
|
||||
// entries are deleted from the addrToServerBlocks map. Essentially, each pairing (each
|
||||
// association from multiple addresses to multiple server blocks; i.e. each element of
|
||||
// the returned slice) becomes a server definition in the output JSON.
|
||||
func (st *ServerType) consolidateAddrMappings(addrToServerBlocks map[string][]serverBlock) []sbAddrAssociation {
|
||||
var sbaddrs []sbAddrAssociation
|
||||
for addr, sblocks := range addrToServerBlocks {
|
||||
// we start with knowing that at least this address
|
||||
// maps to these server blocks
|
||||
a := sbAddrAssociation{
|
||||
addresses: []string{addr},
|
||||
serverBlocks: sblocks,
|
||||
}
|
||||
|
||||
// now find other addresses that map to identical
|
||||
// server blocks and add them to our list of
|
||||
// addresses, while removing them from the map
|
||||
for otherAddr, otherSblocks := range addrToServerBlocks {
|
||||
if addr == otherAddr {
|
||||
continue
|
||||
}
|
||||
if reflect.DeepEqual(sblocks, otherSblocks) {
|
||||
a.addresses = append(a.addresses, otherAddr)
|
||||
delete(addrToServerBlocks, otherAddr)
|
||||
}
|
||||
}
|
||||
|
||||
sbaddrs = append(sbaddrs, a)
|
||||
}
|
||||
return sbaddrs
|
||||
}
|
||||
|
||||
func (st *ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key string) ([]string, error) {
|
||||
addr, err := ParseAddress(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing key: %v", err)
|
||||
}
|
||||
addr = addr.Normalize()
|
||||
|
||||
lnPort := defaultPort
|
||||
if addr.Port != "" {
|
||||
// port explicitly defined
|
||||
lnPort = addr.Port
|
||||
} else if certmagic.HostQualifies(addr.Host) {
|
||||
// automatic HTTPS
|
||||
lnPort = strconv.Itoa(certmagic.HTTPSPort)
|
||||
}
|
||||
|
||||
// the bind directive specifies hosts, but is optional
|
||||
var lnHosts []string
|
||||
for _, cfgVal := range sblock.pile["bind"] {
|
||||
lnHosts = append(lnHosts, cfgVal.Value.([]string)...)
|
||||
}
|
||||
if len(lnHosts) == 0 {
|
||||
lnHosts = []string{""}
|
||||
}
|
||||
|
||||
// use a map to prevent duplication
|
||||
listeners := make(map[string]struct{})
|
||||
for _, host := range lnHosts {
|
||||
listeners[net.JoinHostPort(host, lnPort)] = struct{}{}
|
||||
}
|
||||
|
||||
// now turn map into list
|
||||
var listenersList []string
|
||||
for lnStr := range listeners {
|
||||
listenersList = append(listenersList, lnStr)
|
||||
}
|
||||
// sort.Strings(listenersList) // TODO: is sorting necessary?
|
||||
|
||||
return listenersList, nil
|
||||
}
|
||||
|
||||
// Address represents a site address. It contains
|
||||
// the original input value, and the component
|
||||
// parts of an address. The component parts may be
|
||||
// updated to the correct values as setup proceeds,
|
||||
// but the original value should never be changed.
|
||||
//
|
||||
// The Host field must be in a normalized form.
|
||||
type Address struct {
|
||||
Original, Scheme, Host, Port, Path string
|
||||
}
|
||||
|
||||
// ParseAddress parses an address string into a structured format with separate
|
||||
// scheme, host, port, and path portions, as well as the original input string.
|
||||
func ParseAddress(str string) (Address, error) {
|
||||
httpPort, httpsPort := strconv.Itoa(certmagic.HTTPPort), strconv.Itoa(certmagic.HTTPSPort)
|
||||
|
||||
input := str
|
||||
|
||||
// Split input into components (prepend with // to force host portion by default)
|
||||
if !strings.Contains(str, "//") && !strings.HasPrefix(str, "/") {
|
||||
str = "//" + str
|
||||
}
|
||||
|
||||
u, err := url.Parse(str)
|
||||
if err != nil {
|
||||
return Address{}, err
|
||||
}
|
||||
|
||||
// separate host and port
|
||||
host, port, err := net.SplitHostPort(u.Host)
|
||||
if err != nil {
|
||||
host, port, err = net.SplitHostPort(u.Host + ":")
|
||||
if err != nil {
|
||||
host = u.Host
|
||||
}
|
||||
}
|
||||
|
||||
// see if we can set port based off scheme
|
||||
if port == "" {
|
||||
if u.Scheme == "http" {
|
||||
port = httpPort
|
||||
} else if u.Scheme == "https" {
|
||||
port = httpsPort
|
||||
}
|
||||
}
|
||||
|
||||
// error if scheme and port combination violate convention
|
||||
if (u.Scheme == "http" && port == httpsPort) || (u.Scheme == "https" && port == httpPort) {
|
||||
return Address{}, fmt.Errorf("[%s] scheme and port violate convention", input)
|
||||
}
|
||||
|
||||
return Address{Original: input, Scheme: u.Scheme, Host: host, Port: port, Path: u.Path}, err
|
||||
}
|
||||
|
||||
// TODO: which of the methods on Address are even used?
|
||||
|
||||
// String returns a human-readable form of a. It will
|
||||
// be a cleaned-up and filled-out URL string.
|
||||
func (a Address) String() string {
|
||||
if a.Host == "" && a.Port == "" {
|
||||
return ""
|
||||
}
|
||||
scheme := a.Scheme
|
||||
if scheme == "" {
|
||||
if a.Port == strconv.Itoa(certmagic.HTTPSPort) {
|
||||
scheme = "https"
|
||||
} else {
|
||||
scheme = "http"
|
||||
}
|
||||
}
|
||||
s := scheme
|
||||
if s != "" {
|
||||
s += "://"
|
||||
}
|
||||
if a.Port != "" &&
|
||||
((scheme == "https" && a.Port != strconv.Itoa(caddyhttp.DefaultHTTPSPort)) ||
|
||||
(scheme == "http" && a.Port != strconv.Itoa(caddyhttp.DefaultHTTPPort))) {
|
||||
s += net.JoinHostPort(a.Host, a.Port)
|
||||
} else {
|
||||
s += a.Host
|
||||
}
|
||||
if a.Path != "" {
|
||||
s += a.Path
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Normalize returns a normalized version of a.
|
||||
func (a Address) Normalize() Address {
|
||||
path := a.Path
|
||||
if !caseSensitivePath {
|
||||
path = strings.ToLower(path)
|
||||
}
|
||||
|
||||
// ensure host is normalized if it's an IP address
|
||||
host := a.Host
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
host = ip.String()
|
||||
}
|
||||
|
||||
return Address{
|
||||
Original: a.Original,
|
||||
Scheme: strings.ToLower(a.Scheme),
|
||||
Host: strings.ToLower(host),
|
||||
Port: a.Port,
|
||||
Path: path,
|
||||
}
|
||||
}
|
||||
|
||||
// Key returns a string form of a, much like String() does, but this
|
||||
// method doesn't add anything default that wasn't in the original.
|
||||
func (a Address) Key() string {
|
||||
res := ""
|
||||
if a.Scheme != "" {
|
||||
res += a.Scheme + "://"
|
||||
}
|
||||
if a.Host != "" {
|
||||
res += a.Host
|
||||
}
|
||||
// insert port only if the original has its own explicit port
|
||||
if a.Port != "" &&
|
||||
len(a.Original) >= len(res) &&
|
||||
strings.HasPrefix(a.Original[len(res):], ":"+a.Port) {
|
||||
res += ":" + a.Port
|
||||
}
|
||||
if a.Path != "" {
|
||||
res += a.Path
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPort = "2015"
|
||||
caseSensitivePath = false // TODO: Used?
|
||||
)
|
||||
@@ -1,166 +0,0 @@
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseAddress(t *testing.T) {
|
||||
for i, test := range []struct {
|
||||
input string
|
||||
scheme, host, port, path string
|
||||
shouldErr bool
|
||||
}{
|
||||
{`localhost`, "", "localhost", "", "", false},
|
||||
{`localhost:1234`, "", "localhost", "1234", "", false},
|
||||
{`localhost:`, "", "localhost", "", "", false},
|
||||
{`0.0.0.0`, "", "0.0.0.0", "", "", false},
|
||||
{`127.0.0.1:1234`, "", "127.0.0.1", "1234", "", false},
|
||||
{`:1234`, "", "", "1234", "", false},
|
||||
{`[::1]`, "", "::1", "", "", false},
|
||||
{`[::1]:1234`, "", "::1", "1234", "", false},
|
||||
{`:`, "", "", "", "", false},
|
||||
{`:http`, "", "", "", "", true},
|
||||
{`:https`, "", "", "", "", true},
|
||||
{`localhost:http`, "", "", "", "", true}, // using service name in port is verboten, as of Go 1.12.8
|
||||
{`localhost:https`, "", "", "", "", true},
|
||||
{`http://localhost:https`, "", "", "", "", true}, // conflict
|
||||
{`http://localhost:http`, "", "", "", "", true}, // repeated scheme
|
||||
{`host:https/path`, "", "", "", "", true},
|
||||
{`http://localhost:443`, "", "", "", "", true}, // not conventional
|
||||
{`https://localhost:80`, "", "", "", "", true}, // not conventional
|
||||
{`http://localhost`, "http", "localhost", "80", "", false},
|
||||
{`https://localhost`, "https", "localhost", "443", "", false},
|
||||
{`http://127.0.0.1`, "http", "127.0.0.1", "80", "", false},
|
||||
{`https://127.0.0.1`, "https", "127.0.0.1", "443", "", false},
|
||||
{`http://[::1]`, "http", "::1", "80", "", false},
|
||||
{`http://localhost:1234`, "http", "localhost", "1234", "", false},
|
||||
{`https://127.0.0.1:1234`, "https", "127.0.0.1", "1234", "", false},
|
||||
{`http://[::1]:1234`, "http", "::1", "1234", "", false},
|
||||
{``, "", "", "", "", false},
|
||||
{`::1`, "", "::1", "", "", true},
|
||||
{`localhost::`, "", "localhost::", "", "", true},
|
||||
{`#$%@`, "", "", "", "", true},
|
||||
{`host/path`, "", "host", "", "/path", false},
|
||||
{`http://host/`, "http", "host", "80", "/", false},
|
||||
{`//asdf`, "", "asdf", "", "", false},
|
||||
{`:1234/asdf`, "", "", "1234", "/asdf", false},
|
||||
{`http://host/path`, "http", "host", "80", "/path", false},
|
||||
{`https://host:443/path/foo`, "https", "host", "443", "/path/foo", false},
|
||||
{`host:80/path`, "", "host", "80", "/path", false},
|
||||
{`/path`, "", "", "", "/path", false},
|
||||
} {
|
||||
actual, err := ParseAddress(test.input)
|
||||
|
||||
if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d (%s): Expected no error, but had error: %v", i, test.input, err)
|
||||
}
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d (%s): Expected error, but had none", i, test.input)
|
||||
}
|
||||
|
||||
if !test.shouldErr && actual.Original != test.input {
|
||||
t.Errorf("Test %d (%s): Expected original '%s', got '%s'", i, test.input, test.input, actual.Original)
|
||||
}
|
||||
if actual.Scheme != test.scheme {
|
||||
t.Errorf("Test %d (%s): Expected scheme '%s', got '%s'", i, test.input, test.scheme, actual.Scheme)
|
||||
}
|
||||
if actual.Host != test.host {
|
||||
t.Errorf("Test %d (%s): Expected host '%s', got '%s'", i, test.input, test.host, actual.Host)
|
||||
}
|
||||
if actual.Port != test.port {
|
||||
t.Errorf("Test %d (%s): Expected port '%s', got '%s'", i, test.input, test.port, actual.Port)
|
||||
}
|
||||
if actual.Path != test.path {
|
||||
t.Errorf("Test %d (%s): Expected path '%s', got '%s'", i, test.input, test.path, actual.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddressString(t *testing.T) {
|
||||
for i, test := range []struct {
|
||||
addr Address
|
||||
expected string
|
||||
}{
|
||||
{Address{Scheme: "http", Host: "host", Port: "1234", Path: "/path"}, "http://host:1234/path"},
|
||||
{Address{Scheme: "", Host: "host", Port: "", Path: ""}, "http://host"},
|
||||
{Address{Scheme: "", Host: "host", Port: "80", Path: ""}, "http://host"},
|
||||
{Address{Scheme: "", Host: "host", Port: "443", Path: ""}, "https://host"},
|
||||
{Address{Scheme: "https", Host: "host", Port: "443", Path: ""}, "https://host"},
|
||||
{Address{Scheme: "https", Host: "host", Port: "", Path: ""}, "https://host"},
|
||||
{Address{Scheme: "", Host: "host", Port: "80", Path: "/path"}, "http://host/path"},
|
||||
{Address{Scheme: "http", Host: "", Port: "1234", Path: ""}, "http://:1234"},
|
||||
{Address{Scheme: "", Host: "", Port: "", Path: ""}, ""},
|
||||
} {
|
||||
actual := test.addr.String()
|
||||
if actual != test.expected {
|
||||
t.Errorf("Test %d: expected '%s' but got '%s'", i, test.expected, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyNormalization(t *testing.T) {
|
||||
testCases := []struct {
|
||||
input string
|
||||
expect string
|
||||
}{
|
||||
{
|
||||
input: "http://host:1234/path",
|
||||
expect: "http://host:1234/path",
|
||||
},
|
||||
{
|
||||
input: "HTTP://A/ABCDEF",
|
||||
expect: "http://a/ABCDEF",
|
||||
},
|
||||
{
|
||||
input: "A/ABCDEF",
|
||||
expect: "a/ABCDEF",
|
||||
},
|
||||
{
|
||||
input: "A:2015/Path",
|
||||
expect: "a:2015/Path",
|
||||
},
|
||||
{
|
||||
input: ":80",
|
||||
expect: ":80",
|
||||
},
|
||||
{
|
||||
input: ":443",
|
||||
expect: ":443",
|
||||
},
|
||||
{
|
||||
input: ":1234",
|
||||
expect: ":1234",
|
||||
},
|
||||
{
|
||||
input: "",
|
||||
expect: "",
|
||||
},
|
||||
{
|
||||
input: ":",
|
||||
expect: "",
|
||||
},
|
||||
{
|
||||
input: "[::]",
|
||||
expect: "::",
|
||||
},
|
||||
}
|
||||
for i, tc := range testCases {
|
||||
addr, err := ParseAddress(tc.input)
|
||||
if err != nil {
|
||||
t.Errorf("Test %d: Parsing address '%s': %v", i, tc.input, err)
|
||||
continue
|
||||
}
|
||||
expect := tc.expect
|
||||
if !caseSensitivePath {
|
||||
// every other part of the address should be lowercased when normalized,
|
||||
// so simply lower-case the whole thing to do case-insensitive comparison
|
||||
// of the path as well
|
||||
expect = strings.ToLower(expect)
|
||||
}
|
||||
if actual := addr.Normalize().Key(); actual != expect {
|
||||
t.Errorf("Test %d: Normalized key for address '%s' was '%s' but expected '%s'", i, tc.input, actual, expect)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,265 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterDirective("bind", parseBind)
|
||||
RegisterDirective("root", parseRoot)
|
||||
RegisterDirective("tls", parseTLS)
|
||||
RegisterHandlerDirective("redir", parseRedir)
|
||||
RegisterHandlerDirective("respond", parseRespond)
|
||||
}
|
||||
|
||||
func parseBind(h Helper) ([]ConfigValue, error) {
|
||||
var lnHosts []string
|
||||
for h.Next() {
|
||||
lnHosts = append(lnHosts, h.RemainingArgs()...)
|
||||
}
|
||||
return h.NewBindAddresses(lnHosts), nil
|
||||
}
|
||||
|
||||
func parseRoot(h Helper) ([]ConfigValue, error) {
|
||||
if !h.Next() {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
|
||||
matcherSet, ok, err := h.MatcherToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
// no matcher token; oops
|
||||
h.Dispenser.Prev()
|
||||
}
|
||||
|
||||
if !h.NextArg() {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
root := h.Val()
|
||||
if h.NextArg() {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
|
||||
varsHandler := caddyhttp.VarsMiddleware{"root": root}
|
||||
route := caddyhttp.Route{
|
||||
HandlersRaw: []json.RawMessage{
|
||||
caddyconfig.JSONModuleObject(varsHandler, "handler", "vars", nil),
|
||||
},
|
||||
}
|
||||
if matcherSet != nil {
|
||||
route.MatcherSetsRaw = []map[string]json.RawMessage{matcherSet}
|
||||
}
|
||||
|
||||
return h.NewVarsRoute(route), nil
|
||||
}
|
||||
|
||||
func parseTLS(h Helper) ([]ConfigValue, error) {
|
||||
var configVals []ConfigValue
|
||||
|
||||
cp := new(caddytls.ConnectionPolicy)
|
||||
var fileLoader caddytls.FileLoader
|
||||
var folderLoader caddytls.FolderLoader
|
||||
var mgr caddytls.ACMEManagerMaker
|
||||
var off bool
|
||||
|
||||
for h.Next() {
|
||||
// file certificate loader
|
||||
firstLine := h.RemainingArgs()
|
||||
switch len(firstLine) {
|
||||
case 0:
|
||||
case 1:
|
||||
if firstLine[0] == "off" {
|
||||
off = true
|
||||
} else {
|
||||
mgr.Email = firstLine[0]
|
||||
}
|
||||
case 2:
|
||||
fileLoader = append(fileLoader, caddytls.CertKeyFilePair{
|
||||
Certificate: firstLine[0],
|
||||
Key: firstLine[1],
|
||||
// TODO: add tags, for enterprise module's certificate selection
|
||||
})
|
||||
default:
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
|
||||
var hasBlock bool
|
||||
for h.NextBlock(0) {
|
||||
hasBlock = true
|
||||
|
||||
switch h.Val() {
|
||||
|
||||
// connection policy
|
||||
case "protocols":
|
||||
args := h.RemainingArgs()
|
||||
if len(args) == 0 {
|
||||
return nil, h.SyntaxErr("one or two protocols")
|
||||
}
|
||||
if len(args) > 0 {
|
||||
if _, ok := caddytls.SupportedProtocols[args[0]]; !ok {
|
||||
return nil, h.Errf("Wrong protocol name or protocol not supported: '%s'", args[0])
|
||||
}
|
||||
cp.ProtocolMin = args[0]
|
||||
}
|
||||
if len(args) > 1 {
|
||||
if _, ok := caddytls.SupportedProtocols[args[1]]; !ok {
|
||||
return nil, h.Errf("Wrong protocol name or protocol not supported: '%s'", args[1])
|
||||
}
|
||||
cp.ProtocolMax = args[1]
|
||||
}
|
||||
case "ciphers":
|
||||
for h.NextArg() {
|
||||
if _, ok := caddytls.SupportedCipherSuites[h.Val()]; !ok {
|
||||
return nil, h.Errf("Wrong cipher suite name or cipher suite not supported: '%s'", h.Val())
|
||||
}
|
||||
cp.CipherSuites = append(cp.CipherSuites, h.Val())
|
||||
}
|
||||
case "curves":
|
||||
for h.NextArg() {
|
||||
if _, ok := caddytls.SupportedCurves[h.Val()]; !ok {
|
||||
return nil, h.Errf("Wrong curve name or curve not supported: '%s'", h.Val())
|
||||
}
|
||||
cp.Curves = append(cp.Curves, h.Val())
|
||||
}
|
||||
case "alpn":
|
||||
args := h.RemainingArgs()
|
||||
if len(args) == 0 {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
cp.ALPN = args
|
||||
|
||||
// certificate folder loader
|
||||
case "load":
|
||||
folderLoader = append(folderLoader, h.RemainingArgs()...)
|
||||
|
||||
// automation policy
|
||||
case "ca":
|
||||
arg := h.RemainingArgs()
|
||||
if len(arg) != 1 {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
mgr.CA = arg[0]
|
||||
|
||||
// TODO: other properties for automation manager
|
||||
}
|
||||
}
|
||||
|
||||
// a naked tls directive is not allowed
|
||||
if len(firstLine) == 0 && !hasBlock {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
}
|
||||
|
||||
// connection policy
|
||||
configVals = append(configVals, ConfigValue{
|
||||
Class: "tls.connection_policy",
|
||||
Value: cp,
|
||||
})
|
||||
|
||||
// certificate loaders
|
||||
if len(fileLoader) > 0 {
|
||||
configVals = append(configVals, ConfigValue{
|
||||
Class: "tls.certificate_loader",
|
||||
Value: fileLoader,
|
||||
})
|
||||
}
|
||||
if len(folderLoader) > 0 {
|
||||
configVals = append(configVals, ConfigValue{
|
||||
Class: "tls.certificate_loader",
|
||||
Value: folderLoader,
|
||||
})
|
||||
}
|
||||
|
||||
// automation policy
|
||||
if off {
|
||||
configVals = append(configVals, ConfigValue{
|
||||
Class: "tls.off",
|
||||
Value: true,
|
||||
})
|
||||
} else if !reflect.DeepEqual(mgr, caddytls.ACMEManagerMaker{}) {
|
||||
configVals = append(configVals, ConfigValue{
|
||||
Class: "tls.automation_manager",
|
||||
Value: mgr,
|
||||
})
|
||||
}
|
||||
|
||||
return configVals, nil
|
||||
}
|
||||
|
||||
func parseRedir(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||
if !h.Next() {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
|
||||
if !h.NextArg() {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
to := h.Val()
|
||||
|
||||
var code string
|
||||
if h.NextArg() {
|
||||
code = h.Val()
|
||||
}
|
||||
if code == "permanent" {
|
||||
code = "301"
|
||||
}
|
||||
if code == "temporary" || code == "" {
|
||||
code = "307"
|
||||
}
|
||||
var body string
|
||||
if code == "meta" {
|
||||
// Script tag comes first since that will better imitate a redirect in the browser's
|
||||
// history, but the meta tag is a fallback for most non-JS clients.
|
||||
const metaRedir = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Redirecting...</title>
|
||||
<script>window.location.replace("%s");</script>
|
||||
<meta http-equiv="refresh" content="0; URL='%s'">
|
||||
</head>
|
||||
<body>Redirecting to <a href="%s">%s</a>...</body>
|
||||
</html>
|
||||
`
|
||||
safeTo := html.EscapeString(to)
|
||||
body = fmt.Sprintf(metaRedir, safeTo, safeTo, safeTo, safeTo)
|
||||
}
|
||||
|
||||
return caddyhttp.StaticResponse{
|
||||
StatusCode: caddyhttp.WeakString(code),
|
||||
Headers: http.Header{"Location": []string{to}},
|
||||
Body: body,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseRespond(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||
sr := new(caddyhttp.StaticResponse)
|
||||
err := sr.UnmarshalCaddyfile(h.Dispenser)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sr, nil
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||
)
|
||||
|
||||
// defaultDirectiveOrder specifies the order
|
||||
// to apply directives in HTTP routes.
|
||||
var defaultDirectiveOrder = []string{
|
||||
"rewrite",
|
||||
"try_files",
|
||||
"headers",
|
||||
"request_header",
|
||||
"encode",
|
||||
"templates",
|
||||
"redir",
|
||||
"respond",
|
||||
"reverse_proxy",
|
||||
"php_fastcgi",
|
||||
"file_server",
|
||||
}
|
||||
|
||||
// RegisterDirective registers a unique directive dir with an
|
||||
// associated unmarshaling (setup) function. When directive dir
|
||||
// is encountered in a Caddyfile, setupFunc will be called to
|
||||
// unmarshal its tokens.
|
||||
func RegisterDirective(dir string, setupFunc UnmarshalFunc) {
|
||||
if _, ok := registeredDirectives[dir]; ok {
|
||||
panic("directive " + dir + " already registered")
|
||||
}
|
||||
registeredDirectives[dir] = setupFunc
|
||||
}
|
||||
|
||||
// RegisterHandlerDirective is like RegisterDirective, but for
|
||||
// directives which specifically output only an HTTP handler.
|
||||
func RegisterHandlerDirective(dir string, setupFunc UnmarshalHandlerFunc) {
|
||||
RegisterDirective(dir, func(h Helper) ([]ConfigValue, error) {
|
||||
if !h.Next() {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
|
||||
matcherSet, ok, err := h.MatcherToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
h.Dispenser.Delete() // strip matcher token
|
||||
}
|
||||
|
||||
h.Dispenser.Reset() // pretend this lookahead never happened
|
||||
val, err := setupFunc(h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return h.NewRoute(matcherSet, val), nil
|
||||
})
|
||||
}
|
||||
|
||||
// Helper is a type which helps setup a value from
|
||||
// Caddyfile tokens.
|
||||
type Helper struct {
|
||||
*caddyfile.Dispenser
|
||||
warnings *[]caddyconfig.Warning
|
||||
matcherDefs map[string]map[string]json.RawMessage
|
||||
parentBlock caddyfile.ServerBlock
|
||||
}
|
||||
|
||||
// Caddyfiles returns the list of config files from
|
||||
// which tokens in the current server block were loaded.
|
||||
func (h Helper) Caddyfiles() []string {
|
||||
// first obtain set of names of files involved
|
||||
// in this server block, without duplicates
|
||||
files := make(map[string]struct{})
|
||||
for _, segment := range h.parentBlock.Segments {
|
||||
for _, token := range segment {
|
||||
files[token.File] = struct{}{}
|
||||
}
|
||||
}
|
||||
// then convert the set into a slice
|
||||
filesSlice := make([]string, 0, len(files))
|
||||
for file := range files {
|
||||
filesSlice = append(filesSlice, file)
|
||||
}
|
||||
return filesSlice
|
||||
}
|
||||
|
||||
// JSON converts val into JSON. Any errors are added to warnings.
|
||||
func (h Helper) JSON(val interface{}, warnings *[]caddyconfig.Warning) json.RawMessage {
|
||||
return caddyconfig.JSON(val, h.warnings)
|
||||
}
|
||||
|
||||
// MatcherToken assumes the current token is (possibly) a matcher, and
|
||||
// if so, returns the matcher set along with a true value. If the current
|
||||
// token is not a matcher, nil and false is returned. Note that a true
|
||||
// value may be returned with a nil matcher set if it is a catch-all.
|
||||
func (h Helper) MatcherToken() (map[string]json.RawMessage, bool, error) {
|
||||
if !h.NextArg() {
|
||||
return nil, false, nil
|
||||
}
|
||||
return matcherSetFromMatcherToken(h.Dispenser.Token(), h.matcherDefs, h.warnings)
|
||||
}
|
||||
|
||||
// NewRoute returns config values relevant to creating a new HTTP route.
|
||||
func (h Helper) NewRoute(matcherSet map[string]json.RawMessage,
|
||||
handler caddyhttp.MiddlewareHandler) []ConfigValue {
|
||||
mod, err := caddy.GetModule(caddy.GetModuleName(handler))
|
||||
if err != nil {
|
||||
// TODO: append to warnings
|
||||
}
|
||||
var matcherSetsRaw []map[string]json.RawMessage
|
||||
if matcherSet != nil {
|
||||
matcherSetsRaw = append(matcherSetsRaw, matcherSet)
|
||||
}
|
||||
return []ConfigValue{
|
||||
{
|
||||
Class: "route",
|
||||
Value: caddyhttp.Route{
|
||||
MatcherSetsRaw: matcherSetsRaw,
|
||||
HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", mod.ID(), h.warnings)},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewBindAddresses returns config values relevant to adding
|
||||
// listener bind addresses to the config.
|
||||
func (h Helper) NewBindAddresses(addrs []string) []ConfigValue {
|
||||
return []ConfigValue{{Class: "bind", Value: addrs}}
|
||||
}
|
||||
|
||||
// NewVarsRoute returns config values relevant to adding a
|
||||
// "vars" wrapper route to the config.
|
||||
func (h Helper) NewVarsRoute(route caddyhttp.Route) []ConfigValue {
|
||||
return []ConfigValue{{Class: "var", Value: route}}
|
||||
}
|
||||
|
||||
// ConfigValue represents a value to be added to the final
|
||||
// configuration, or a value to be consulted when building
|
||||
// the final configuration.
|
||||
type ConfigValue struct {
|
||||
// The kind of value this is. As the config is
|
||||
// being built, the adapter will look in the
|
||||
// "pile" for values belonging to a certain
|
||||
// class when it is setting up a certain part
|
||||
// of the config. The associated value will be
|
||||
// type-asserted and placed accordingly.
|
||||
Class string
|
||||
|
||||
// The value to be used when building the config.
|
||||
// Generally its type is associated with the
|
||||
// name of the Class.
|
||||
Value interface{}
|
||||
|
||||
directive string
|
||||
}
|
||||
|
||||
// serverBlock pairs a Caddyfile server block
|
||||
// with a "pile" of config values, keyed by class
|
||||
// name.
|
||||
type serverBlock struct {
|
||||
block caddyfile.ServerBlock
|
||||
pile map[string][]ConfigValue // config values obtained from directives
|
||||
}
|
||||
|
||||
type (
|
||||
// UnmarshalFunc is a function which can unmarshal Caddyfile
|
||||
// tokens into zero or more config values using a Helper type.
|
||||
// These are passed in a call to RegisterDirective.
|
||||
UnmarshalFunc func(h Helper) ([]ConfigValue, error)
|
||||
|
||||
// UnmarshalHandlerFunc is like UnmarshalFunc, except the
|
||||
// output of the unmarshaling is an HTTP handler. This
|
||||
// function does not need to deal with HTTP request matching
|
||||
// which is abstracted away. Since writing HTTP handlers
|
||||
// with Caddyfile support is very common, this is a more
|
||||
// convenient way to add a handler to the chain since a lot
|
||||
// of the details common to HTTP handlers are taken care of
|
||||
// for you. These are passed to a call to
|
||||
// RegisterHandlerDirective.
|
||||
UnmarshalHandlerFunc func(h Helper) (caddyhttp.MiddlewareHandler, error)
|
||||
)
|
||||
|
||||
var registeredDirectives = make(map[string]UnmarshalFunc)
|
||||
@@ -1,56 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||
)
|
||||
|
||||
func (st *ServerType) parseMatcherDefinitions(d *caddyfile.Dispenser) (map[string]map[string]json.RawMessage, error) {
|
||||
matchers := make(map[string]map[string]json.RawMessage)
|
||||
for d.Next() {
|
||||
definitionName := d.Val()
|
||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
||||
matcherName := d.Val()
|
||||
mod, err := caddy.GetModule("http.matchers." + matcherName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getting matcher module '%s': %v", matcherName, err)
|
||||
}
|
||||
unm, ok := mod.New().(caddyfile.Unmarshaler)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("matcher module '%s' is not a Caddyfile unmarshaler", matcherName)
|
||||
}
|
||||
err = unm.UnmarshalCaddyfile(d.NewFromNextTokens())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rm, ok := unm.(caddyhttp.RequestMatcher)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("matcher module '%s' is not a request matcher", matcherName)
|
||||
}
|
||||
if _, ok := matchers[definitionName]; !ok {
|
||||
matchers[definitionName] = make(map[string]json.RawMessage)
|
||||
}
|
||||
matchers[definitionName][matcherName] = caddyconfig.JSON(rm, nil)
|
||||
}
|
||||
}
|
||||
return matchers, nil
|
||||
}
|
||||
@@ -1,567 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
||||
"github.com/mholt/certmagic"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddyconfig.RegisterAdapter("caddyfile", caddyfile.Adapter{ServerType: ServerType{}})
|
||||
}
|
||||
|
||||
// ServerType can set up a config from an HTTP Caddyfile.
|
||||
type ServerType struct {
|
||||
}
|
||||
|
||||
// Setup makes a config from the tokens.
|
||||
func (st ServerType) Setup(originalServerBlocks []caddyfile.ServerBlock,
|
||||
options map[string]interface{}) (*caddy.Config, []caddyconfig.Warning, error) {
|
||||
var warnings []caddyconfig.Warning
|
||||
|
||||
var serverBlocks []serverBlock
|
||||
for _, sblock := range originalServerBlocks {
|
||||
serverBlocks = append(serverBlocks, serverBlock{
|
||||
block: sblock,
|
||||
pile: make(map[string][]ConfigValue),
|
||||
})
|
||||
}
|
||||
|
||||
// global configuration
|
||||
if len(serverBlocks) > 0 && len(serverBlocks[0].block.Keys) == 0 {
|
||||
sb := serverBlocks[0]
|
||||
for _, segment := range sb.block.Segments {
|
||||
dir := segment.Directive()
|
||||
var val interface{}
|
||||
var err error
|
||||
disp := caddyfile.NewDispenser(segment)
|
||||
switch dir {
|
||||
case "http_port":
|
||||
val, err = parseOptHTTPPort(disp)
|
||||
case "https_port":
|
||||
val, err = parseOptHTTPSPort(disp)
|
||||
case "handler_order":
|
||||
val, err = parseOptHandlerOrder(disp)
|
||||
case "experimental_http3":
|
||||
val, err = parseOptExperimentalHTTP3(disp)
|
||||
case "storage":
|
||||
val, err = parseOptStorage(disp)
|
||||
default:
|
||||
return nil, warnings, fmt.Errorf("unrecognized parameter name: %s", dir)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, warnings, fmt.Errorf("%s: %v", dir, err)
|
||||
}
|
||||
options[dir] = val
|
||||
}
|
||||
serverBlocks = serverBlocks[1:]
|
||||
}
|
||||
|
||||
for _, sb := range serverBlocks {
|
||||
// replace shorthand placeholders (which are
|
||||
// convenient when writing a Caddyfile) with
|
||||
// their actual placeholder identifiers or
|
||||
// variable names
|
||||
replacer := strings.NewReplacer(
|
||||
"{uri}", "{http.request.uri}",
|
||||
"{path}", "{http.request.uri.path}",
|
||||
"{host}", "{http.request.host}",
|
||||
"{hostport}", "{http.request.hostport}",
|
||||
"{method}", "{http.request.method}",
|
||||
"{scheme}", "{http.request.scheme}",
|
||||
"{file}", "{http.request.uri.path.file}",
|
||||
"{dir}", "{http.request.uri.path.dir}",
|
||||
"{query}", "{http.request.uri.query_string}",
|
||||
)
|
||||
for _, segment := range sb.block.Segments {
|
||||
for i := 0; i < len(segment); i++ {
|
||||
segment[i].Text = replacer.Replace(segment[i].Text)
|
||||
}
|
||||
}
|
||||
|
||||
if len(sb.block.Keys) == 0 {
|
||||
return nil, warnings, fmt.Errorf("server block without any key is global configuration, and if used, it must be first")
|
||||
}
|
||||
|
||||
// extract matcher definitions
|
||||
d := sb.block.DispenseDirective("matcher")
|
||||
matcherDefs, err := st.parseMatcherDefinitions(d)
|
||||
if err != nil {
|
||||
return nil, warnings, err
|
||||
}
|
||||
|
||||
for _, segment := range sb.block.Segments {
|
||||
dir := segment.Directive()
|
||||
if dir == "matcher" {
|
||||
// TODO: This is a special case because we pre-processed it; handle this better
|
||||
continue
|
||||
}
|
||||
if dirFunc, ok := registeredDirectives[dir]; ok {
|
||||
results, err := dirFunc(Helper{
|
||||
Dispenser: caddyfile.NewDispenser(segment),
|
||||
warnings: &warnings,
|
||||
matcherDefs: matcherDefs,
|
||||
parentBlock: sb.block,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, warnings, fmt.Errorf("parsing caddyfile tokens for '%s': %v", dir, err)
|
||||
}
|
||||
for _, result := range results {
|
||||
result.directive = dir
|
||||
sb.pile[result.Class] = append(sb.pile[result.Class], result)
|
||||
}
|
||||
} else {
|
||||
tkn := segment[0]
|
||||
return nil, warnings, fmt.Errorf("%s:%d: unrecognized directive: %s", tkn.File, tkn.Line, dir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// map
|
||||
sbmap, err := st.mapAddressToServerBlocks(serverBlocks)
|
||||
if err != nil {
|
||||
return nil, warnings, err
|
||||
}
|
||||
|
||||
// reduce
|
||||
pairings := st.consolidateAddrMappings(sbmap)
|
||||
|
||||
// each pairing of listener addresses to list of server
|
||||
// blocks is basically a server definition
|
||||
servers, err := st.serversFromPairings(pairings, options, &warnings)
|
||||
if err != nil {
|
||||
return nil, warnings, err
|
||||
}
|
||||
|
||||
// now that each server is configured, make the HTTP app
|
||||
httpApp := caddyhttp.App{
|
||||
HTTPPort: tryInt(options["http_port"], &warnings),
|
||||
HTTPSPort: tryInt(options["https_port"], &warnings),
|
||||
Servers: servers,
|
||||
}
|
||||
|
||||
// now for the TLS app! (TODO: refactor into own func)
|
||||
tlsApp := caddytls.TLS{Certificates: make(map[string]json.RawMessage)}
|
||||
for _, p := range pairings {
|
||||
for _, sblock := range p.serverBlocks {
|
||||
// tls automation policies
|
||||
if mmVals, ok := sblock.pile["tls.automation_manager"]; ok {
|
||||
for _, mmVal := range mmVals {
|
||||
mm := mmVal.Value.(caddytls.ManagerMaker)
|
||||
sblockHosts, err := st.autoHTTPSHosts(sblock)
|
||||
if err != nil {
|
||||
return nil, warnings, err
|
||||
}
|
||||
tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, caddytls.AutomationPolicy{
|
||||
Hosts: sblockHosts,
|
||||
ManagementRaw: caddyconfig.JSONModuleObject(mm, "module", mm.(caddy.Module).CaddyModule().ID(), &warnings),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// tls certificate loaders
|
||||
if clVals, ok := sblock.pile["tls.certificate_loader"]; ok {
|
||||
for _, clVal := range clVals {
|
||||
loader := clVal.Value.(caddytls.CertificateLoader)
|
||||
loaderName := caddy.GetModuleID(loader)
|
||||
tlsApp.Certificates[loaderName] = caddyconfig.JSON(loader, &warnings)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// consolidate automation policies that are the exact same
|
||||
tlsApp.Automation.Policies = consolidateAutomationPolicies(tlsApp.Automation.Policies)
|
||||
|
||||
// if experimental HTTP/3 is enabled, enable it on each server
|
||||
if enableH3, ok := options["experimental_http3"].(bool); ok && enableH3 {
|
||||
for _, srv := range httpApp.Servers {
|
||||
srv.ExperimentalHTTP3 = true
|
||||
}
|
||||
}
|
||||
|
||||
// annnd the top-level config, then we're done!
|
||||
cfg := &caddy.Config{AppsRaw: make(map[string]json.RawMessage)}
|
||||
if !reflect.DeepEqual(httpApp, caddyhttp.App{}) {
|
||||
cfg.AppsRaw["http"] = caddyconfig.JSON(httpApp, &warnings)
|
||||
}
|
||||
if !reflect.DeepEqual(tlsApp, caddytls.TLS{}) {
|
||||
cfg.AppsRaw["tls"] = caddyconfig.JSON(tlsApp, &warnings)
|
||||
}
|
||||
if storageCvtr, ok := options["storage"].(caddy.StorageConverter); ok {
|
||||
cfg.StorageRaw = caddyconfig.JSON(storageCvtr, &warnings)
|
||||
}
|
||||
|
||||
return cfg, warnings, nil
|
||||
}
|
||||
|
||||
// hostsFromServerBlockKeys returns a list of all the
|
||||
// hostnames found in the keys of the server block sb.
|
||||
// The list may not be in a consistent order.
|
||||
func (st *ServerType) hostsFromServerBlockKeys(sb caddyfile.ServerBlock) ([]string, error) {
|
||||
// first get each unique hostname
|
||||
hostMap := make(map[string]struct{})
|
||||
for _, sblockKey := range sb.Keys {
|
||||
addr, err := ParseAddress(sblockKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing server block key: %v", err)
|
||||
}
|
||||
addr = addr.Normalize()
|
||||
hostMap[addr.Host] = struct{}{}
|
||||
}
|
||||
|
||||
// convert map to slice
|
||||
sblockHosts := make([]string, 0, len(hostMap))
|
||||
for host := range hostMap {
|
||||
sblockHosts = append(sblockHosts, host)
|
||||
}
|
||||
|
||||
return sblockHosts, nil
|
||||
}
|
||||
|
||||
// serversFromPairings creates the servers for each pairing of addresses
|
||||
// to server blocks. Each pairing is essentially a server definition.
|
||||
func (st *ServerType) serversFromPairings(
|
||||
pairings []sbAddrAssociation,
|
||||
options map[string]interface{},
|
||||
warnings *[]caddyconfig.Warning,
|
||||
) (map[string]*caddyhttp.Server, error) {
|
||||
servers := make(map[string]*caddyhttp.Server)
|
||||
|
||||
for i, p := range pairings {
|
||||
srv := &caddyhttp.Server{
|
||||
Listen: p.addresses,
|
||||
}
|
||||
|
||||
for _, sblock := range p.serverBlocks {
|
||||
matcherSetsEnc, err := st.compileEncodedMatcherSets(sblock.block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("server block %v: compiling matcher sets: %v", sblock.block.Keys, err)
|
||||
}
|
||||
|
||||
// if there are user-defined variables, then siteVarSubroute will
|
||||
// wrap the handlerSubroute; otherwise handlerSubroute will be the
|
||||
// site's primary subroute.
|
||||
siteVarSubroute, handlerSubroute := new(caddyhttp.Subroute), new(caddyhttp.Subroute)
|
||||
|
||||
// tls: connection policies and toggle auto HTTPS
|
||||
|
||||
autoHTTPSQualifiedHosts, err := st.autoHTTPSHosts(sblock)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := sblock.pile["tls.off"]; ok && len(autoHTTPSQualifiedHosts) > 0 {
|
||||
// tls off: disable TLS (and automatic HTTPS) for server block's names
|
||||
if srv.AutoHTTPS == nil {
|
||||
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
||||
}
|
||||
srv.AutoHTTPS.Skip = append(srv.AutoHTTPS.Skip, autoHTTPSQualifiedHosts...)
|
||||
} else if cpVals, ok := sblock.pile["tls.connection_policy"]; ok {
|
||||
// tls connection policies
|
||||
for _, cpVal := range cpVals {
|
||||
cp := cpVal.Value.(*caddytls.ConnectionPolicy)
|
||||
// only create if there is a non-empty policy
|
||||
if !reflect.DeepEqual(cp, new(caddytls.ConnectionPolicy)) {
|
||||
// make sure the policy covers all hostnames from the block
|
||||
hosts, err := st.hostsFromServerBlockKeys(sblock.block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// TODO: are matchers needed if every hostname of the config is matched?
|
||||
cp.Matchers = map[string]json.RawMessage{
|
||||
"sni": caddyconfig.JSON(hosts, warnings), // make sure to match all hosts, not just auto-HTTPS-qualified ones
|
||||
}
|
||||
srv.TLSConnPolicies = append(srv.TLSConnPolicies, cp)
|
||||
}
|
||||
}
|
||||
// TODO: consolidate equal conn policies
|
||||
}
|
||||
|
||||
// vars: special routes that will have to wrap the normal handlers
|
||||
// so that these variables can be used across their matchers too
|
||||
for _, cfgVal := range sblock.pile["var"] {
|
||||
siteVarSubroute.Routes = append(siteVarSubroute.Routes, cfgVal.Value.(caddyhttp.Route))
|
||||
}
|
||||
|
||||
// set up each handler directive - the order of the handlers
|
||||
// as they are added to the routes depends on user preference
|
||||
dirRoutes := sblock.pile["route"]
|
||||
handlerOrder, ok := options["handler_order"].([]string)
|
||||
if !ok {
|
||||
handlerOrder = defaultDirectiveOrder
|
||||
}
|
||||
if len(handlerOrder) == 1 && handlerOrder[0] == "appearance" {
|
||||
handlerOrder = nil
|
||||
}
|
||||
if handlerOrder != nil {
|
||||
dirPositions := make(map[string]int)
|
||||
for i, dir := range handlerOrder {
|
||||
dirPositions[dir] = i
|
||||
}
|
||||
sort.SliceStable(dirRoutes, func(i, j int) bool {
|
||||
iDir, jDir := dirRoutes[i].directive, dirRoutes[j].directive
|
||||
return dirPositions[iDir] < dirPositions[jDir]
|
||||
})
|
||||
}
|
||||
for _, r := range dirRoutes {
|
||||
handlerSubroute.Routes = append(handlerSubroute.Routes, r.Value.(caddyhttp.Route))
|
||||
}
|
||||
|
||||
// the route that contains the site's handlers will
|
||||
// be assumed to be the sub-route for this site...
|
||||
siteSubroute := handlerSubroute
|
||||
|
||||
// ... unless, of course, there are variables that might
|
||||
// be used by the site's matchers or handlers, in which
|
||||
// case we need to nest the handlers in a sub-sub-route,
|
||||
// and the variables go in the sub-route so the variables
|
||||
// get evaluated first
|
||||
if len(siteVarSubroute.Routes) > 0 {
|
||||
subSubRoute := caddyhttp.Subroute{Routes: siteSubroute.Routes}
|
||||
siteSubroute.Routes = append(
|
||||
siteVarSubroute.Routes,
|
||||
caddyhttp.Route{
|
||||
HandlersRaw: []json.RawMessage{
|
||||
caddyconfig.JSONModuleObject(subSubRoute, "handler", "subroute", warnings),
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
siteSubroute.Routes = consolidateRoutes(siteSubroute.Routes)
|
||||
|
||||
srv.Routes = append(srv.Routes, caddyhttp.Route{
|
||||
MatcherSetsRaw: matcherSetsEnc,
|
||||
HandlersRaw: []json.RawMessage{
|
||||
caddyconfig.JSONModuleObject(siteSubroute, "handler", "subroute", warnings),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
srv.Routes = consolidateRoutes(srv.Routes)
|
||||
|
||||
servers[fmt.Sprintf("srv%d", i)] = srv
|
||||
}
|
||||
|
||||
return servers, nil
|
||||
}
|
||||
|
||||
func (st ServerType) autoHTTPSHosts(sb serverBlock) ([]string, error) {
|
||||
// get the hosts for this server block...
|
||||
hosts, err := st.hostsFromServerBlockKeys(sb.block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// ...and of those, which ones qualify for auto HTTPS
|
||||
var autoHTTPSQualifiedHosts []string
|
||||
for _, h := range hosts {
|
||||
if certmagic.HostQualifies(h) {
|
||||
autoHTTPSQualifiedHosts = append(autoHTTPSQualifiedHosts, h)
|
||||
}
|
||||
}
|
||||
return autoHTTPSQualifiedHosts, nil
|
||||
}
|
||||
|
||||
// consolidateRoutes combines routes with the same properties
|
||||
// (same matchers, same Terminal and Group settings) for a
|
||||
// cleaner overall output.
|
||||
func consolidateRoutes(routes caddyhttp.RouteList) caddyhttp.RouteList {
|
||||
for i := 0; i < len(routes)-1; i++ {
|
||||
if reflect.DeepEqual(routes[i].MatcherSetsRaw, routes[i+1].MatcherSetsRaw) &&
|
||||
routes[i].Terminal == routes[i+1].Terminal &&
|
||||
routes[i].Group == routes[i+1].Group {
|
||||
// keep the handlers in the same order, then splice out repetitive route
|
||||
routes[i].HandlersRaw = append(routes[i].HandlersRaw, routes[i+1].HandlersRaw...)
|
||||
routes = append(routes[:i+1], routes[i+2:]...)
|
||||
i--
|
||||
}
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
// consolidateAutomationPolicies combines automation policies that are the same,
|
||||
// for a cleaner overall output.
|
||||
func consolidateAutomationPolicies(aps []caddytls.AutomationPolicy) []caddytls.AutomationPolicy {
|
||||
for i := 0; i < len(aps); i++ {
|
||||
for j := 0; j < len(aps); j++ {
|
||||
if j == i {
|
||||
continue
|
||||
}
|
||||
if reflect.DeepEqual(aps[i].ManagementRaw, aps[j].ManagementRaw) {
|
||||
aps[i].Hosts = append(aps[i].Hosts, aps[j].Hosts...)
|
||||
}
|
||||
aps = append(aps[:j], aps[j+1:]...)
|
||||
i--
|
||||
break
|
||||
}
|
||||
}
|
||||
return aps
|
||||
}
|
||||
|
||||
func matcherSetFromMatcherToken(
|
||||
tkn caddyfile.Token,
|
||||
matcherDefs map[string]map[string]json.RawMessage,
|
||||
warnings *[]caddyconfig.Warning,
|
||||
) (map[string]json.RawMessage, bool, error) {
|
||||
// matcher tokens can be wildcards, simple path matchers,
|
||||
// or refer to a pre-defined matcher by some name
|
||||
if tkn.Text == "*" {
|
||||
// match all requests == no matchers, so nothing to do
|
||||
return nil, true, nil
|
||||
} else if strings.HasPrefix(tkn.Text, "/") {
|
||||
// convenient way to specify a single path match
|
||||
return map[string]json.RawMessage{
|
||||
"path": caddyconfig.JSON(caddyhttp.MatchPath{tkn.Text}, warnings),
|
||||
}, true, nil
|
||||
} else if strings.HasPrefix(tkn.Text, "match:") {
|
||||
// pre-defined matcher
|
||||
matcherName := strings.TrimPrefix(tkn.Text, "match:")
|
||||
m, ok := matcherDefs[matcherName]
|
||||
if !ok {
|
||||
return nil, false, fmt.Errorf("unrecognized matcher name: %+v", matcherName)
|
||||
}
|
||||
return m, true, nil
|
||||
}
|
||||
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
func (st *ServerType) compileEncodedMatcherSets(sblock caddyfile.ServerBlock) ([]map[string]json.RawMessage, error) {
|
||||
type hostPathPair struct {
|
||||
hostm caddyhttp.MatchHost
|
||||
pathm caddyhttp.MatchPath
|
||||
}
|
||||
|
||||
// keep routes with common host and path matchers together
|
||||
var matcherPairs []*hostPathPair
|
||||
|
||||
for _, key := range sblock.Keys {
|
||||
addr, err := ParseAddress(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("server block %v: parsing and standardizing address '%s': %v", sblock.Keys, key, err)
|
||||
}
|
||||
addr = addr.Normalize()
|
||||
|
||||
// choose a matcher pair that should be shared by this
|
||||
// server block; if none exists yet, create one
|
||||
var chosenMatcherPair *hostPathPair
|
||||
for _, mp := range matcherPairs {
|
||||
if (len(mp.pathm) == 0 && addr.Path == "") ||
|
||||
(len(mp.pathm) == 1 && mp.pathm[0] == addr.Path) {
|
||||
chosenMatcherPair = mp
|
||||
break
|
||||
}
|
||||
}
|
||||
if chosenMatcherPair == nil {
|
||||
chosenMatcherPair = new(hostPathPair)
|
||||
if addr.Path != "" {
|
||||
chosenMatcherPair.pathm = []string{addr.Path}
|
||||
}
|
||||
matcherPairs = append(matcherPairs, chosenMatcherPair)
|
||||
}
|
||||
|
||||
// add this server block's keys to the matcher
|
||||
// pair if it doesn't already exist
|
||||
if addr.Host != "" {
|
||||
var found bool
|
||||
for _, h := range chosenMatcherPair.hostm {
|
||||
if h == addr.Host {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
chosenMatcherPair.hostm = append(chosenMatcherPair.hostm, addr.Host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// iterate each pairing of host and path matchers and
|
||||
// put them into a map for JSON encoding
|
||||
var matcherSets []map[string]caddyhttp.RequestMatcher
|
||||
for _, mp := range matcherPairs {
|
||||
matcherSet := make(map[string]caddyhttp.RequestMatcher)
|
||||
if len(mp.hostm) > 0 {
|
||||
matcherSet["host"] = mp.hostm
|
||||
}
|
||||
if len(mp.pathm) > 0 {
|
||||
matcherSet["path"] = mp.pathm
|
||||
}
|
||||
if len(matcherSet) > 0 {
|
||||
matcherSets = append(matcherSets, matcherSet)
|
||||
}
|
||||
}
|
||||
|
||||
// finally, encode each of the matcher sets
|
||||
var matcherSetsEnc []map[string]json.RawMessage
|
||||
for _, ms := range matcherSets {
|
||||
msEncoded, err := encodeMatcherSet(ms)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("server block %v: %v", sblock.Keys, err)
|
||||
}
|
||||
matcherSetsEnc = append(matcherSetsEnc, msEncoded)
|
||||
}
|
||||
|
||||
return matcherSetsEnc, nil
|
||||
}
|
||||
|
||||
func encodeMatcherSet(matchers map[string]caddyhttp.RequestMatcher) (map[string]json.RawMessage, error) {
|
||||
msEncoded := make(map[string]json.RawMessage)
|
||||
for matcherName, val := range matchers {
|
||||
jsonBytes, err := json.Marshal(val)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshaling matcher set %#v: %v", matchers, err)
|
||||
}
|
||||
msEncoded[matcherName] = jsonBytes
|
||||
}
|
||||
return msEncoded, nil
|
||||
}
|
||||
|
||||
// tryInt tries to convert val to an integer. If it fails,
|
||||
// it downgrades the error to a warning and returns 0.
|
||||
func tryInt(val interface{}, warnings *[]caddyconfig.Warning) int {
|
||||
intVal, ok := val.(int)
|
||||
if val != nil && !ok && warnings != nil {
|
||||
*warnings = append(*warnings, caddyconfig.Warning{Message: "not an integer type"})
|
||||
}
|
||||
return intVal
|
||||
}
|
||||
|
||||
type matcherSetAndTokens struct {
|
||||
matcherSet map[string]json.RawMessage
|
||||
tokens []caddyfile.Token
|
||||
}
|
||||
|
||||
// sbAddrAssocation is a mapping from a list of
|
||||
// addresses to a list of server blocks that are
|
||||
// served on those addresses.
|
||||
type sbAddrAssociation struct {
|
||||
addresses []string
|
||||
serverBlocks []serverBlock
|
||||
}
|
||||
|
||||
// Interface guard
|
||||
var _ caddyfile.ServerType = (*ServerType)(nil)
|
||||
@@ -1,110 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||
)
|
||||
|
||||
func parseOptHTTPPort(d *caddyfile.Dispenser) (int, error) {
|
||||
var httpPort int
|
||||
for d.Next() {
|
||||
var httpPortStr string
|
||||
if !d.AllArgs(&httpPortStr) {
|
||||
return 0, d.ArgErr()
|
||||
}
|
||||
var err error
|
||||
httpPort, err = strconv.Atoi(httpPortStr)
|
||||
if err != nil {
|
||||
return 0, d.Errf("converting port '%s' to integer value: %v", httpPortStr, err)
|
||||
}
|
||||
}
|
||||
return httpPort, nil
|
||||
}
|
||||
|
||||
func parseOptHTTPSPort(d *caddyfile.Dispenser) (int, error) {
|
||||
var httpsPort int
|
||||
for d.Next() {
|
||||
var httpsPortStr string
|
||||
if !d.AllArgs(&httpsPortStr) {
|
||||
return 0, d.ArgErr()
|
||||
}
|
||||
var err error
|
||||
httpsPort, err = strconv.Atoi(httpsPortStr)
|
||||
if err != nil {
|
||||
return 0, d.Errf("converting port '%s' to integer value: %v", httpsPortStr, err)
|
||||
}
|
||||
}
|
||||
return httpsPort, nil
|
||||
}
|
||||
|
||||
func parseOptExperimentalHTTP3(d *caddyfile.Dispenser) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func parseOptHandlerOrder(d *caddyfile.Dispenser) ([]string, error) {
|
||||
if !d.Next() {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
order := d.RemainingArgs()
|
||||
if len(order) == 1 && order[0] == "appearance" {
|
||||
return []string{"appearance"}, nil
|
||||
}
|
||||
if len(order) > 0 && d.NextBlock(0) {
|
||||
return nil, d.Err("cannot open block if there are arguments")
|
||||
}
|
||||
for d.NextBlock(0) {
|
||||
order = append(order, d.Val())
|
||||
if d.NextArg() {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
}
|
||||
if len(order) == 0 {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
func parseOptStorage(d *caddyfile.Dispenser) (caddy.StorageConverter, error) {
|
||||
if !d.Next() {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
args := d.RemainingArgs()
|
||||
if len(args) != 1 {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
modName := args[0]
|
||||
mod, err := caddy.GetModule("caddy.storage." + modName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getting storage module '%s': %v", modName, err)
|
||||
}
|
||||
unm, ok := mod.New().(caddyfile.Unmarshaler)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("storage module '%s' is not a Caddyfile unmarshaler", mod.Name)
|
||||
}
|
||||
err = unm.UnmarshalCaddyfile(d.NewFromNextTokens())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storage, ok := unm.(caddy.StorageConverter)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("module %s is not a StorageConverter", mod.Name)
|
||||
}
|
||||
return storage, nil
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package json5adapter
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/ilibs/json5"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddyconfig.RegisterAdapter("json5", Adapter{})
|
||||
}
|
||||
|
||||
// Adapter adapts JSON5 to Caddy JSON.
|
||||
type Adapter struct{}
|
||||
|
||||
// Adapt converts the JSON5 config in body to Caddy JSON.
|
||||
func (a Adapter) Adapt(body []byte, options map[string]interface{}) (result []byte, warnings []caddyconfig.Warning, err error) {
|
||||
var decoded interface{}
|
||||
err = json5.Unmarshal(body, &decoded)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
result, err = json.Marshal(decoded)
|
||||
return
|
||||
}
|
||||
|
||||
// Interface guard
|
||||
var _ caddyconfig.Adapter = (*Adapter)(nil)
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package jsoncadapter
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/muhammadmuzzammil1998/jsonc"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddyconfig.RegisterAdapter("jsonc", Adapter{})
|
||||
}
|
||||
|
||||
// Adapter adapts JSON-C to Caddy JSON.
|
||||
type Adapter struct{}
|
||||
|
||||
// Adapt converts the JSON-C config in body to Caddy JSON.
|
||||
func (a Adapter) Adapt(body []byte, options map[string]interface{}) (result []byte, warnings []caddyconfig.Warning, err error) {
|
||||
result = jsonc.ToJSON(body)
|
||||
|
||||
// any errors in the JSON will be
|
||||
// reported during config load, but
|
||||
// we can at least warn here that
|
||||
// it is not valid JSON
|
||||
if !json.Valid(result) {
|
||||
warnings = append(warnings, caddyconfig.Warning{
|
||||
Message: "Resulting JSON is invalid.",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Interface guard
|
||||
var _ caddyconfig.Adapter = (*Adapter)(nil)
|
||||
@@ -0,0 +1,252 @@
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Dispenser is a type that dispenses tokens, similarly to a lexer,
|
||||
// except that it can do so with some notion of structure and has
|
||||
// some really convenient methods.
|
||||
type Dispenser struct {
|
||||
filename string
|
||||
tokens []Token
|
||||
cursor int
|
||||
nesting int
|
||||
}
|
||||
|
||||
// NewDispenser returns a Dispenser, ready to use for parsing the given input.
|
||||
func NewDispenser(filename string, input io.Reader) Dispenser {
|
||||
tokens, _ := allTokens(input) // ignoring error because nothing to do with it
|
||||
return Dispenser{
|
||||
filename: filename,
|
||||
tokens: tokens,
|
||||
cursor: -1,
|
||||
}
|
||||
}
|
||||
|
||||
// NewDispenserTokens returns a Dispenser filled with the given tokens.
|
||||
func NewDispenserTokens(filename string, tokens []Token) Dispenser {
|
||||
return Dispenser{
|
||||
filename: filename,
|
||||
tokens: tokens,
|
||||
cursor: -1,
|
||||
}
|
||||
}
|
||||
|
||||
// Next loads the next token. Returns true if a token
|
||||
// was loaded; false otherwise. If false, all tokens
|
||||
// have been consumed.
|
||||
func (d *Dispenser) Next() bool {
|
||||
if d.cursor < len(d.tokens)-1 {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NextArg loads the next token if it is on the same
|
||||
// line. Returns true if a token was loaded; false
|
||||
// otherwise. If false, all tokens on the line have
|
||||
// been consumed. It handles imported tokens correctly.
|
||||
func (d *Dispenser) NextArg() bool {
|
||||
if d.cursor < 0 {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
if d.cursor >= len(d.tokens) {
|
||||
return false
|
||||
}
|
||||
if d.cursor < len(d.tokens)-1 &&
|
||||
d.tokens[d.cursor].File == d.tokens[d.cursor+1].File &&
|
||||
d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) == d.tokens[d.cursor+1].Line {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NextLine loads the next token only if it is not on the same
|
||||
// line as the current token, and returns true if a token was
|
||||
// loaded; false otherwise. If false, there is not another token
|
||||
// or it is on the same line. It handles imported tokens correctly.
|
||||
func (d *Dispenser) NextLine() bool {
|
||||
if d.cursor < 0 {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
if d.cursor >= len(d.tokens) {
|
||||
return false
|
||||
}
|
||||
if d.cursor < len(d.tokens)-1 &&
|
||||
(d.tokens[d.cursor].File != d.tokens[d.cursor+1].File ||
|
||||
d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) < d.tokens[d.cursor+1].Line) {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NextBlock can be used as the condition of a for loop
|
||||
// to load the next token as long as it opens a block or
|
||||
// is already in a block. It returns true if a token was
|
||||
// loaded, or false when the block's closing curly brace
|
||||
// was loaded and thus the block ended. Nested blocks are
|
||||
// not supported.
|
||||
func (d *Dispenser) NextBlock() bool {
|
||||
if d.nesting > 0 {
|
||||
d.Next()
|
||||
if d.Val() == "}" {
|
||||
d.nesting--
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if !d.NextArg() { // block must open on same line
|
||||
return false
|
||||
}
|
||||
if d.Val() != "{" {
|
||||
d.cursor-- // roll back if not opening brace
|
||||
return false
|
||||
}
|
||||
d.Next()
|
||||
if d.Val() == "}" {
|
||||
// Open and then closed right away
|
||||
return false
|
||||
}
|
||||
d.nesting++
|
||||
return true
|
||||
}
|
||||
|
||||
// IncrNest adds a level of nesting to the dispenser.
|
||||
func (d *Dispenser) IncrNest() {
|
||||
d.nesting++
|
||||
return
|
||||
}
|
||||
|
||||
// Val gets the text of the current token. If there is no token
|
||||
// loaded, it returns empty string.
|
||||
func (d *Dispenser) Val() string {
|
||||
if d.cursor < 0 || d.cursor >= len(d.tokens) {
|
||||
return ""
|
||||
}
|
||||
return d.tokens[d.cursor].Text
|
||||
}
|
||||
|
||||
// Line gets the line number of the current token. If there is no token
|
||||
// loaded, it returns 0.
|
||||
func (d *Dispenser) Line() int {
|
||||
if d.cursor < 0 || d.cursor >= len(d.tokens) {
|
||||
return 0
|
||||
}
|
||||
return d.tokens[d.cursor].Line
|
||||
}
|
||||
|
||||
// File gets the filename of the current token. If there is no token loaded,
|
||||
// it returns the filename originally given when parsing started.
|
||||
func (d *Dispenser) File() string {
|
||||
if d.cursor < 0 || d.cursor >= len(d.tokens) {
|
||||
return d.filename
|
||||
}
|
||||
if tokenFilename := d.tokens[d.cursor].File; tokenFilename != "" {
|
||||
return tokenFilename
|
||||
}
|
||||
return d.filename
|
||||
}
|
||||
|
||||
// Args is a convenience function that loads the next arguments
|
||||
// (tokens on the same line) into an arbitrary number of strings
|
||||
// pointed to in targets. If there are fewer tokens available
|
||||
// than string pointers, the remaining strings will not be changed
|
||||
// and false will be returned. If there were enough tokens available
|
||||
// to fill the arguments, then true will be returned.
|
||||
func (d *Dispenser) Args(targets ...*string) bool {
|
||||
enough := true
|
||||
for i := 0; i < len(targets); i++ {
|
||||
if !d.NextArg() {
|
||||
enough = false
|
||||
break
|
||||
}
|
||||
*targets[i] = d.Val()
|
||||
}
|
||||
return enough
|
||||
}
|
||||
|
||||
// RemainingArgs loads any more arguments (tokens on the same line)
|
||||
// into a slice and returns them. Open curly brace tokens also indicate
|
||||
// the end of arguments, and the curly brace is not included in
|
||||
// the return value nor is it loaded.
|
||||
func (d *Dispenser) RemainingArgs() []string {
|
||||
var args []string
|
||||
|
||||
for d.NextArg() {
|
||||
if d.Val() == "{" {
|
||||
d.cursor--
|
||||
break
|
||||
}
|
||||
args = append(args, d.Val())
|
||||
}
|
||||
|
||||
return args
|
||||
}
|
||||
|
||||
// ArgErr returns an argument error, meaning that another
|
||||
// argument was expected but not found. In other words,
|
||||
// a line break or open curly brace was encountered instead of
|
||||
// an argument.
|
||||
func (d *Dispenser) ArgErr() error {
|
||||
if d.Val() == "{" {
|
||||
return d.Err("Unexpected token '{', expecting argument")
|
||||
}
|
||||
return d.Errf("Wrong argument count or unexpected line ending after '%s'", d.Val())
|
||||
}
|
||||
|
||||
// SyntaxErr creates a generic syntax error which explains what was
|
||||
// found and what was expected.
|
||||
func (d *Dispenser) SyntaxErr(expected string) error {
|
||||
msg := fmt.Sprintf("%s:%d - Syntax error: Unexpected token '%s', expecting '%s'", d.File(), d.Line(), d.Val(), expected)
|
||||
return errors.New(msg)
|
||||
}
|
||||
|
||||
// EOFErr returns an error indicating that the dispenser reached
|
||||
// the end of the input when searching for the next token.
|
||||
func (d *Dispenser) EOFErr() error {
|
||||
return d.Errf("Unexpected EOF")
|
||||
}
|
||||
|
||||
// Err generates a custom parse error with a message of msg.
|
||||
func (d *Dispenser) Err(msg string) error {
|
||||
msg = fmt.Sprintf("%s:%d - Parse error: %s", d.File(), d.Line(), msg)
|
||||
return errors.New(msg)
|
||||
}
|
||||
|
||||
// Errf is like Err, but for formatted error messages
|
||||
func (d *Dispenser) Errf(format string, args ...interface{}) error {
|
||||
return d.Err(fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// numLineBreaks counts how many line breaks are in the token
|
||||
// value given by the token index tknIdx. It returns 0 if the
|
||||
// token does not exist or there are no line breaks.
|
||||
func (d *Dispenser) numLineBreaks(tknIdx int) int {
|
||||
if tknIdx < 0 || tknIdx >= len(d.tokens) {
|
||||
return 0
|
||||
}
|
||||
return strings.Count(d.tokens[tknIdx].Text, "\n")
|
||||
}
|
||||
|
||||
// isNewLine determines whether the current token is on a different
|
||||
// line (higher line number) than the previous token. It handles imported
|
||||
// tokens correctly. If there isn't a previous token, it returns true.
|
||||
func (d *Dispenser) isNewLine() bool {
|
||||
if d.cursor < 1 {
|
||||
return true
|
||||
}
|
||||
if d.cursor > len(d.tokens)-1 {
|
||||
return false
|
||||
}
|
||||
return d.tokens[d.cursor-1].File != d.tokens[d.cursor].File ||
|
||||
d.tokens[d.cursor-1].Line+d.numLineBreaks(d.cursor-1) < d.tokens[d.cursor].Line
|
||||
}
|
||||
Executable → Regular
+8
-32
@@ -1,22 +1,6 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -27,7 +11,7 @@ func TestDispenser_Val_Next(t *testing.T) {
|
||||
dir1 arg1
|
||||
dir2 arg2 arg3
|
||||
dir3`
|
||||
d := newTestDispenser(input)
|
||||
d := NewDispenser("Testfile", strings.NewReader(input))
|
||||
|
||||
if val := d.Val(); val != "" {
|
||||
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
|
||||
@@ -65,7 +49,7 @@ func TestDispenser_NextArg(t *testing.T) {
|
||||
input := `dir1 arg1
|
||||
dir2 arg2 arg3
|
||||
dir3`
|
||||
d := newTestDispenser(input)
|
||||
d := NewDispenser("Testfile", strings.NewReader(input))
|
||||
|
||||
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
|
||||
if d.Next() != shouldLoad {
|
||||
@@ -112,7 +96,7 @@ func TestDispenser_NextLine(t *testing.T) {
|
||||
input := `host:port
|
||||
dir1 arg1
|
||||
dir2 arg2 arg3`
|
||||
d := newTestDispenser(input)
|
||||
d := NewDispenser("Testfile", strings.NewReader(input))
|
||||
|
||||
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
|
||||
if d.NextLine() != shouldLoad {
|
||||
@@ -145,10 +129,10 @@ func TestDispenser_NextBlock(t *testing.T) {
|
||||
}
|
||||
foobar2 {
|
||||
}`
|
||||
d := newTestDispenser(input)
|
||||
d := NewDispenser("Testfile", strings.NewReader(input))
|
||||
|
||||
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
|
||||
if loaded := d.NextBlock(0); loaded != shouldLoad {
|
||||
if loaded := d.NextBlock(); loaded != shouldLoad {
|
||||
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
|
||||
}
|
||||
if d.cursor != expectedCursor {
|
||||
@@ -175,7 +159,7 @@ func TestDispenser_Args(t *testing.T) {
|
||||
dir2 arg4 arg5
|
||||
dir3 arg6 arg7
|
||||
dir4`
|
||||
d := newTestDispenser(input)
|
||||
d := NewDispenser("Testfile", strings.NewReader(input))
|
||||
|
||||
d.Next() // dir1
|
||||
|
||||
@@ -242,7 +226,7 @@ func TestDispenser_RemainingArgs(t *testing.T) {
|
||||
dir2 arg4 arg5
|
||||
dir3 arg6 { arg7
|
||||
dir4`
|
||||
d := newTestDispenser(input)
|
||||
d := NewDispenser("Testfile", strings.NewReader(input))
|
||||
|
||||
d.Next() // dir1
|
||||
|
||||
@@ -279,7 +263,7 @@ func TestDispenser_ArgErr_Err(t *testing.T) {
|
||||
input := `dir1 {
|
||||
}
|
||||
dir2 arg1 arg2`
|
||||
d := newTestDispenser(input)
|
||||
d := NewDispenser("Testfile", strings.NewReader(input))
|
||||
|
||||
d.cursor = 1 // {
|
||||
|
||||
@@ -306,11 +290,3 @@ func TestDispenser_ArgErr_Err(t *testing.T) {
|
||||
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestDispenser(input string) *Dispenser {
|
||||
tokens, err := allTokens("Testfile", strings.NewReader(input))
|
||||
if err != nil && err != io.EOF {
|
||||
log.Fatalf("getting all tokens from input: %v", err)
|
||||
}
|
||||
return NewDispenser(tokens)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const filename = "Caddyfile"
|
||||
|
||||
// ToJSON converts caddyfile to its JSON representation.
|
||||
func ToJSON(caddyfile []byte) ([]byte, error) {
|
||||
var j EncodedCaddyfile
|
||||
|
||||
serverBlocks, err := Parse(filename, bytes.NewReader(caddyfile), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, sb := range serverBlocks {
|
||||
block := EncodedServerBlock{
|
||||
Keys: sb.Keys,
|
||||
Body: [][]interface{}{},
|
||||
}
|
||||
|
||||
// Extract directives deterministically by sorting them
|
||||
var directives = make([]string, len(sb.Tokens))
|
||||
for dir := range sb.Tokens {
|
||||
directives = append(directives, dir)
|
||||
}
|
||||
sort.Strings(directives)
|
||||
|
||||
// Convert each directive's tokens into our JSON structure
|
||||
for _, dir := range directives {
|
||||
disp := NewDispenserTokens(filename, sb.Tokens[dir])
|
||||
for disp.Next() {
|
||||
block.Body = append(block.Body, constructLine(&disp))
|
||||
}
|
||||
}
|
||||
|
||||
// tack this block onto the end of the list
|
||||
j = append(j, block)
|
||||
}
|
||||
|
||||
result, err := json.Marshal(j)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// constructLine transforms tokens into a JSON-encodable structure;
|
||||
// but only one line at a time, to be used at the top-level of
|
||||
// a server block only (where the first token on each line is a
|
||||
// directive) - not to be used at any other nesting level.
|
||||
func constructLine(d *Dispenser) []interface{} {
|
||||
var args []interface{}
|
||||
|
||||
args = append(args, d.Val())
|
||||
|
||||
for d.NextArg() {
|
||||
if d.Val() == "{" {
|
||||
args = append(args, constructBlock(d))
|
||||
continue
|
||||
}
|
||||
args = append(args, d.Val())
|
||||
}
|
||||
|
||||
return args
|
||||
}
|
||||
|
||||
// constructBlock recursively processes tokens into a
|
||||
// JSON-encodable structure. To be used in a directive's
|
||||
// block. Goes to end of block.
|
||||
func constructBlock(d *Dispenser) [][]interface{} {
|
||||
block := [][]interface{}{}
|
||||
|
||||
for d.Next() {
|
||||
if d.Val() == "}" {
|
||||
break
|
||||
}
|
||||
block = append(block, constructLine(d))
|
||||
}
|
||||
|
||||
return block
|
||||
}
|
||||
|
||||
// FromJSON converts JSON-encoded jsonBytes to Caddyfile text
|
||||
func FromJSON(jsonBytes []byte) ([]byte, error) {
|
||||
var j EncodedCaddyfile
|
||||
var result string
|
||||
|
||||
err := json.Unmarshal(jsonBytes, &j)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for sbPos, sb := range j {
|
||||
if sbPos > 0 {
|
||||
result += "\n\n"
|
||||
}
|
||||
for i, key := range sb.Keys {
|
||||
if i > 0 {
|
||||
result += ", "
|
||||
}
|
||||
//result += standardizeScheme(key)
|
||||
result += key
|
||||
}
|
||||
result += jsonToText(sb.Body, 1)
|
||||
}
|
||||
|
||||
return []byte(result), nil
|
||||
}
|
||||
|
||||
// jsonToText recursively transforms a scope of JSON into plain
|
||||
// Caddyfile text.
|
||||
func jsonToText(scope interface{}, depth int) string {
|
||||
var result string
|
||||
|
||||
switch val := scope.(type) {
|
||||
case string:
|
||||
if strings.ContainsAny(val, "\" \n\t\r") {
|
||||
result += `"` + strings.Replace(val, "\"", "\\\"", -1) + `"`
|
||||
} else {
|
||||
result += val
|
||||
}
|
||||
case int:
|
||||
result += strconv.Itoa(val)
|
||||
case float64:
|
||||
result += fmt.Sprintf("%v", val)
|
||||
case bool:
|
||||
result += fmt.Sprintf("%t", val)
|
||||
case [][]interface{}:
|
||||
result += " {\n"
|
||||
for _, arg := range val {
|
||||
result += strings.Repeat("\t", depth) + jsonToText(arg, depth+1) + "\n"
|
||||
}
|
||||
result += strings.Repeat("\t", depth-1) + "}"
|
||||
case []interface{}:
|
||||
for i, v := range val {
|
||||
if block, ok := v.([]interface{}); ok {
|
||||
result += "{\n"
|
||||
for _, arg := range block {
|
||||
result += strings.Repeat("\t", depth) + jsonToText(arg, depth+1) + "\n"
|
||||
}
|
||||
result += strings.Repeat("\t", depth-1) + "}"
|
||||
continue
|
||||
}
|
||||
result += jsonToText(v, depth)
|
||||
if i < len(val)-1 {
|
||||
result += " "
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// TODO: Will this function come in handy somewhere else?
|
||||
/*
|
||||
// standardizeScheme turns an address like host:https into https://host,
|
||||
// or "host:" into "host".
|
||||
func standardizeScheme(addr string) string {
|
||||
if hostname, port, err := net.SplitHostPort(addr); err == nil {
|
||||
if port == "http" || port == "https" {
|
||||
addr = port + "://" + hostname
|
||||
}
|
||||
}
|
||||
return strings.TrimSuffix(addr, ":")
|
||||
}
|
||||
*/
|
||||
|
||||
// EncodedCaddyfile encapsulates a slice of EncodedServerBlocks.
|
||||
type EncodedCaddyfile []EncodedServerBlock
|
||||
|
||||
// EncodedServerBlock represents a server block ripe for encoding.
|
||||
type EncodedServerBlock struct {
|
||||
Keys []string `json:"keys"`
|
||||
Body [][]interface{} `json:"body"`
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package caddyfile
|
||||
|
||||
import "testing"
|
||||
|
||||
var tests = []struct {
|
||||
caddyfile, json string
|
||||
}{
|
||||
{ // 0
|
||||
caddyfile: `foo {
|
||||
root /bar
|
||||
}`,
|
||||
json: `[{"keys":["foo"],"body":[["root","/bar"]]}]`,
|
||||
},
|
||||
{ // 1
|
||||
caddyfile: `host1, host2 {
|
||||
dir {
|
||||
def
|
||||
}
|
||||
}`,
|
||||
json: `[{"keys":["host1","host2"],"body":[["dir",[["def"]]]]}]`,
|
||||
},
|
||||
{ // 2
|
||||
caddyfile: `host1, host2 {
|
||||
dir abc {
|
||||
def ghi
|
||||
jkl
|
||||
}
|
||||
}`,
|
||||
json: `[{"keys":["host1","host2"],"body":[["dir","abc",[["def","ghi"],["jkl"]]]]}]`,
|
||||
},
|
||||
{ // 3
|
||||
caddyfile: `host1:1234, host2:5678 {
|
||||
dir abc {
|
||||
}
|
||||
}`,
|
||||
json: `[{"keys":["host1:1234","host2:5678"],"body":[["dir","abc",[]]]}]`,
|
||||
},
|
||||
{ // 4
|
||||
caddyfile: `host {
|
||||
foo "bar baz"
|
||||
}`,
|
||||
json: `[{"keys":["host"],"body":[["foo","bar baz"]]}]`,
|
||||
},
|
||||
{ // 5
|
||||
caddyfile: `host, host:80 {
|
||||
foo "bar \"baz\""
|
||||
}`,
|
||||
json: `[{"keys":["host","host:80"],"body":[["foo","bar \"baz\""]]}]`,
|
||||
},
|
||||
{ // 6
|
||||
caddyfile: `host {
|
||||
foo "bar
|
||||
baz"
|
||||
}`,
|
||||
json: `[{"keys":["host"],"body":[["foo","bar\nbaz"]]}]`,
|
||||
},
|
||||
{ // 7
|
||||
caddyfile: `host {
|
||||
dir 123 4.56 true
|
||||
}`,
|
||||
json: `[{"keys":["host"],"body":[["dir","123","4.56","true"]]}]`, // NOTE: I guess we assume numbers and booleans should be encoded as strings...?
|
||||
},
|
||||
{ // 8
|
||||
caddyfile: `http://host, https://host {
|
||||
}`,
|
||||
json: `[{"keys":["http://host","https://host"],"body":[]}]`, // hosts in JSON are always host:port format (if port is specified), for consistency
|
||||
},
|
||||
{ // 9
|
||||
caddyfile: `host {
|
||||
dir1 a b
|
||||
dir2 c d
|
||||
}`,
|
||||
json: `[{"keys":["host"],"body":[["dir1","a","b"],["dir2","c","d"]]}]`,
|
||||
},
|
||||
{ // 10
|
||||
caddyfile: `host {
|
||||
dir a b
|
||||
dir c d
|
||||
}`,
|
||||
json: `[{"keys":["host"],"body":[["dir","a","b"],["dir","c","d"]]}]`,
|
||||
},
|
||||
{ // 11
|
||||
caddyfile: `host {
|
||||
dir1 a b
|
||||
dir2 {
|
||||
c
|
||||
d
|
||||
}
|
||||
}`,
|
||||
json: `[{"keys":["host"],"body":[["dir1","a","b"],["dir2",[["c"],["d"]]]]}]`,
|
||||
},
|
||||
{ // 12
|
||||
caddyfile: `host1 {
|
||||
dir1
|
||||
}
|
||||
|
||||
host2 {
|
||||
dir2
|
||||
}`,
|
||||
json: `[{"keys":["host1"],"body":[["dir1"]]},{"keys":["host2"],"body":[["dir2"]]}]`,
|
||||
},
|
||||
}
|
||||
|
||||
func TestToJSON(t *testing.T) {
|
||||
for i, test := range tests {
|
||||
output, err := ToJSON([]byte(test.caddyfile))
|
||||
if err != nil {
|
||||
t.Errorf("Test %d: %v", i, err)
|
||||
}
|
||||
if string(output) != test.json {
|
||||
t.Errorf("Test %d\nExpected:\n'%s'\nActual:\n'%s'", i, test.json, string(output))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromJSON(t *testing.T) {
|
||||
for i, test := range tests {
|
||||
output, err := FromJSON([]byte(test.json))
|
||||
if err != nil {
|
||||
t.Errorf("Test %d: %v", i, err)
|
||||
}
|
||||
if string(output) != test.caddyfile {
|
||||
t.Errorf("Test %d\nExpected:\n'%s'\nActual:\n'%s'", i, test.caddyfile, string(output))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Will these tests come in handy somewhere else?
|
||||
/*
|
||||
func TestStandardizeAddress(t *testing.T) {
|
||||
// host:https should be converted to https://host
|
||||
output, err := ToJSON([]byte(`host:https`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if expected, actual := `[{"keys":["https://host"],"body":[]}]`, string(output); expected != actual {
|
||||
t.Errorf("Expected:\n'%s'\nActual:\n'%s'", expected, actual)
|
||||
}
|
||||
|
||||
output, err = FromJSON([]byte(`[{"keys":["https://host"],"body":[]}]`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if expected, actual := "https://host {\n}", string(output); expected != actual {
|
||||
t.Errorf("Expected:\n'%s'\nActual:\n'%s'", expected, actual)
|
||||
}
|
||||
|
||||
// host: should be converted to just host
|
||||
output, err = ToJSON([]byte(`host:`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if expected, actual := `[{"keys":["host"],"body":[]}]`, string(output); expected != actual {
|
||||
t.Errorf("Expected:\n'%s'\nActual:\n'%s'", expected, actual)
|
||||
}
|
||||
output, err = FromJSON([]byte(`[{"keys":["host:"],"body":[]}]`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if expected, actual := "host {\n}", string(output); expected != actual {
|
||||
t.Errorf("Expected:\n'%s'\nActual:\n'%s'", expected, actual)
|
||||
}
|
||||
}
|
||||
*/
|
||||
Executable → Regular
+2
-16
@@ -1,17 +1,3 @@
|
||||
// Copyright 2015 Light Code Labs, LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
@@ -105,8 +91,8 @@ func (l *lexer) next() bool {
|
||||
l.line++
|
||||
}
|
||||
if escaped {
|
||||
// only escape quotes and newlines
|
||||
if ch != '"' && ch != '\n' {
|
||||
// only escape quotes
|
||||
if ch != '"' {
|
||||
val = append(val, '\\')
|
||||
}
|
||||
}
|
||||
Executable → Regular
+1
-26
@@ -1,21 +1,6 @@
|
||||
// Copyright 2015 Light Code Labs, LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -95,14 +80,6 @@ func TestLexer(t *testing.T) {
|
||||
{Line: 1, Text: "B"},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "A \"newline \\\ninside\" quotes",
|
||||
expected: []Token{
|
||||
{Line: 1, Text: "A"},
|
||||
{Line: 1, Text: "newline \ninside"},
|
||||
{Line: 2, Text: "quotes"},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: `"don't\escape"`,
|
||||
expected: []Token{
|
||||
@@ -167,9 +144,7 @@ func TestLexer(t *testing.T) {
|
||||
|
||||
func tokenize(input string) (tokens []Token) {
|
||||
l := lexer{}
|
||||
if err := l.load(strings.NewReader(input)); err != nil {
|
||||
log.Printf("[ERROR] load failed: %v", err)
|
||||
}
|
||||
l.load(strings.NewReader(input))
|
||||
for l.next() {
|
||||
tokens = append(tokens, l.token)
|
||||
}
|
||||
Executable → Regular
+102
-202
@@ -1,17 +1,3 @@
|
||||
// Copyright 2015 Light Code Labs, LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
@@ -28,19 +14,15 @@ import (
|
||||
// Directives that do not appear in validDirectives will cause
|
||||
// an error. If you do not want to check for valid directives,
|
||||
// pass in nil instead.
|
||||
func Parse(filename string, input io.Reader) ([]ServerBlock, error) {
|
||||
tokens, err := allTokens(filename, input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := parser{Dispenser: NewDispenser(tokens)}
|
||||
func Parse(filename string, input io.Reader, validDirectives []string) ([]ServerBlock, error) {
|
||||
p := parser{Dispenser: NewDispenser(filename, input), validDirectives: validDirectives}
|
||||
return p.parseAll()
|
||||
}
|
||||
|
||||
// allTokens lexes the entire input, but does not parse it.
|
||||
// It returns all the tokens from the input, unstructured
|
||||
// and in order.
|
||||
func allTokens(filename string, input io.Reader) ([]Token, error) {
|
||||
func allTokens(input io.Reader) ([]Token, error) {
|
||||
l := new(lexer)
|
||||
err := l.load(input)
|
||||
if err != nil {
|
||||
@@ -48,18 +30,16 @@ func allTokens(filename string, input io.Reader) ([]Token, error) {
|
||||
}
|
||||
var tokens []Token
|
||||
for l.next() {
|
||||
l.token.File = filename
|
||||
tokens = append(tokens, l.token)
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
type parser struct {
|
||||
*Dispenser
|
||||
Dispenser
|
||||
block ServerBlock // current server block being parsed
|
||||
validDirectives []string // a directive must be valid or it's an error
|
||||
eof bool // if we encounter a valid EOF in a hard place
|
||||
definedSnippets map[string][]Token
|
||||
nesting int
|
||||
}
|
||||
|
||||
func (p *parser) parseAll() ([]ServerBlock, error) {
|
||||
@@ -70,19 +50,17 @@ func (p *parser) parseAll() ([]ServerBlock, error) {
|
||||
if err != nil {
|
||||
return blocks, err
|
||||
}
|
||||
if len(p.block.Keys) > 0 || len(p.block.Segments) > 0 {
|
||||
if len(p.block.Keys) > 0 {
|
||||
blocks = append(blocks, p.block)
|
||||
}
|
||||
if p.nesting > 0 {
|
||||
return blocks, p.EOFErr()
|
||||
}
|
||||
}
|
||||
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
func (p *parser) parseOne() error {
|
||||
p.block = ServerBlock{}
|
||||
p.block = ServerBlock{Tokens: make(map[string][]Token)}
|
||||
|
||||
return p.begin()
|
||||
}
|
||||
|
||||
@@ -103,24 +81,6 @@ func (p *parser) begin() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
if ok, name := p.isSnippet(); ok {
|
||||
if p.definedSnippets == nil {
|
||||
p.definedSnippets = map[string][]Token{}
|
||||
}
|
||||
if _, found := p.definedSnippets[name]; found {
|
||||
return p.Errf("redeclaration of previously declared snippet %s", name)
|
||||
}
|
||||
// consume all tokens til matched close brace
|
||||
tokens, err := p.snippetTokens()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.definedSnippets[name] = tokens
|
||||
// empty block keys so we don't save this block as a real server.
|
||||
p.block.Keys = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
return p.blockContents()
|
||||
}
|
||||
|
||||
@@ -189,7 +149,7 @@ func (p *parser) blockContents() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// only look for close curly brace if there was an opening
|
||||
// Only look for close curly brace if there was an opening
|
||||
if errOpenCurlyBrace == nil {
|
||||
err = p.closeCurlyBrace()
|
||||
if err != nil {
|
||||
@@ -208,7 +168,6 @@ func (p *parser) directives() error {
|
||||
for p.Next() {
|
||||
// end of server block
|
||||
if p.Val() == "}" {
|
||||
// p.nesting has already been decremented
|
||||
break
|
||||
}
|
||||
|
||||
@@ -222,15 +181,11 @@ func (p *parser) directives() error {
|
||||
continue
|
||||
}
|
||||
|
||||
// normal case: parse a directive as a new segment
|
||||
// (a "segment" is a line which starts with a directive
|
||||
// and which ends at the end of the line or at the end of
|
||||
// the block that is opened at the end of the line)
|
||||
// normal case: parse a directive on this line
|
||||
if err := p.directive(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -252,57 +207,69 @@ func (p *parser) doImport() error {
|
||||
if p.NextArg() {
|
||||
return p.Err("Import takes only one argument (glob pattern or file)")
|
||||
}
|
||||
|
||||
// make path relative to Caddyfile rather than current working directory (issue #867)
|
||||
// and then use glob to get list of matching filenames
|
||||
absFile, err := filepath.Abs(p.Dispenser.filename)
|
||||
if err != nil {
|
||||
return p.Errf("Failed to get absolute path of file: %s", p.Dispenser.filename)
|
||||
}
|
||||
|
||||
var matches []string
|
||||
var globPattern string
|
||||
if !filepath.IsAbs(importPattern) {
|
||||
globPattern = filepath.Join(filepath.Dir(absFile), importPattern)
|
||||
} else {
|
||||
globPattern = importPattern
|
||||
}
|
||||
matches, err = filepath.Glob(globPattern)
|
||||
|
||||
if err != nil {
|
||||
return p.Errf("Failed to use import pattern %s: %v", importPattern, err)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
if strings.Contains(globPattern, "*") {
|
||||
log.Printf("[WARNING] No files matching import pattern: %s", importPattern)
|
||||
} else {
|
||||
return p.Errf("File to import not found: %s", importPattern)
|
||||
}
|
||||
}
|
||||
|
||||
// splice out the import directive and its argument (2 tokens total)
|
||||
tokensBefore := p.tokens[:p.cursor-1]
|
||||
tokensAfter := p.tokens[p.cursor+1:]
|
||||
|
||||
// collect all the imported tokens
|
||||
var importedTokens []Token
|
||||
|
||||
// first check snippets. That is a simple, non-recursive replacement
|
||||
if p.definedSnippets != nil && p.definedSnippets[importPattern] != nil {
|
||||
importedTokens = p.definedSnippets[importPattern]
|
||||
} else {
|
||||
// make path relative to the file of the _token_ being processed rather
|
||||
// than current working directory (issue #867) and then use glob to get
|
||||
// list of matching filenames
|
||||
absFile, err := filepath.Abs(p.Dispenser.File())
|
||||
for _, importFile := range matches {
|
||||
newTokens, err := p.doSingleImport(importFile)
|
||||
if err != nil {
|
||||
return p.Errf("Failed to get absolute path of file: %s: %v", p.Dispenser.File(), err)
|
||||
return err
|
||||
}
|
||||
|
||||
var matches []string
|
||||
var globPattern string
|
||||
if !filepath.IsAbs(importPattern) {
|
||||
globPattern = filepath.Join(filepath.Dir(absFile), importPattern)
|
||||
} else {
|
||||
globPattern = importPattern
|
||||
}
|
||||
if strings.Count(globPattern, "*") > 1 || strings.Count(globPattern, "?") > 1 ||
|
||||
(strings.Contains(globPattern, "[") && strings.Contains(globPattern, "]")) {
|
||||
// See issue #2096 - a pattern with many glob expansions can hang for too long
|
||||
return p.Errf("Glob pattern may only contain one wildcard (*), but has others: %s", globPattern)
|
||||
}
|
||||
matches, err = filepath.Glob(globPattern)
|
||||
|
||||
if err != nil {
|
||||
return p.Errf("Failed to use import pattern %s: %v", importPattern, err)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
if strings.ContainsAny(globPattern, "*?[]") {
|
||||
log.Printf("[WARNING] No files matching import glob pattern: %s", importPattern)
|
||||
} else {
|
||||
return p.Errf("File to import not found: %s", importPattern)
|
||||
var importLine int
|
||||
importDir := filepath.Dir(importFile)
|
||||
for i, token := range newTokens {
|
||||
if token.Text == "import" {
|
||||
importLine = token.Line
|
||||
continue
|
||||
}
|
||||
if token.Line == importLine {
|
||||
var abs string
|
||||
if filepath.IsAbs(token.Text) {
|
||||
abs = token.Text
|
||||
} else if !filepath.IsAbs(importFile) {
|
||||
abs = filepath.Join(filepath.Dir(absFile), token.Text)
|
||||
} else {
|
||||
abs = filepath.Join(importDir, token.Text)
|
||||
}
|
||||
newTokens[i] = Token{
|
||||
Text: abs,
|
||||
Line: token.Line,
|
||||
File: token.File,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// collect all the imported tokens
|
||||
|
||||
for _, importFile := range matches {
|
||||
newTokens, err := p.doSingleImport(importFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
importedTokens = append(importedTokens, newTokens...)
|
||||
}
|
||||
importedTokens = append(importedTokens, newTokens...)
|
||||
}
|
||||
|
||||
// splice the imported tokens in the place of the import statement
|
||||
@@ -328,17 +295,13 @@ func (p *parser) doSingleImport(importFile string) ([]Token, error) {
|
||||
return nil, p.Errf("Could not import %s: is a directory", importFile)
|
||||
}
|
||||
|
||||
importedTokens, err := allTokens(importFile, file)
|
||||
importedTokens, err := allTokens(file)
|
||||
if err != nil {
|
||||
return nil, p.Errf("Could not read tokens while importing %s: %v", importFile, err)
|
||||
}
|
||||
|
||||
// Tack the file path onto these tokens so errors show the imported file's name
|
||||
// (we use full, absolute path to avoid bugs: issue #1892)
|
||||
filename, err := filepath.Abs(importFile)
|
||||
if err != nil {
|
||||
return nil, p.Errf("Failed to get absolute path of file: %s: %v", importFile, err)
|
||||
}
|
||||
// Tack the filename onto these tokens so errors show the imported file's name
|
||||
filename := filepath.Base(importFile)
|
||||
for i := 0; i < len(importedTokens); i++ {
|
||||
importedTokens[i].File = filename
|
||||
}
|
||||
@@ -353,42 +316,35 @@ func (p *parser) doSingleImport(importFile string) ([]Token, error) {
|
||||
// are loaded into the current server block for later use
|
||||
// by directive setup functions.
|
||||
func (p *parser) directive() error {
|
||||
// evaluate any env vars in directive token
|
||||
p.tokens[p.cursor].Text = replaceEnvVars(p.tokens[p.cursor].Text)
|
||||
dir := p.Val()
|
||||
nesting := 0
|
||||
|
||||
// a segment is a list of tokens associated with this directive
|
||||
var segment Segment
|
||||
// TODO: More helpful error message ("did you mean..." or "maybe you need to install its server type")
|
||||
if !p.validDirective(dir) {
|
||||
return p.Errf("Unknown directive '%s'", dir)
|
||||
}
|
||||
|
||||
// the directive itself is appended as a relevant token
|
||||
segment = append(segment, p.Token())
|
||||
// The directive itself is appended as a relevant token
|
||||
p.block.Tokens[dir] = append(p.block.Tokens[dir], p.tokens[p.cursor])
|
||||
|
||||
for p.Next() {
|
||||
if p.Val() == "{" {
|
||||
p.nesting++
|
||||
} else if p.isNewLine() && p.nesting == 0 {
|
||||
nesting++
|
||||
} else if p.isNewLine() && nesting == 0 {
|
||||
p.cursor-- // read too far
|
||||
break
|
||||
} else if p.Val() == "}" && p.nesting > 0 {
|
||||
p.nesting--
|
||||
} else if p.Val() == "}" && p.nesting == 0 {
|
||||
} else if p.Val() == "}" && nesting > 0 {
|
||||
nesting--
|
||||
} else if p.Val() == "}" && nesting == 0 {
|
||||
return p.Err("Unexpected '}' because no matching opening brace")
|
||||
} else if p.Val() == "import" && p.isNewLine() {
|
||||
if err := p.doImport(); err != nil {
|
||||
return err
|
||||
}
|
||||
p.cursor-- // cursor is advanced when we continue, so roll back one more
|
||||
continue
|
||||
}
|
||||
p.tokens[p.cursor].Text = replaceEnvVars(p.tokens[p.cursor].Text)
|
||||
segment = append(segment, p.Token())
|
||||
p.block.Tokens[dir] = append(p.block.Tokens[dir], p.tokens[p.cursor])
|
||||
}
|
||||
|
||||
p.block.Segments = append(p.block.Segments, segment)
|
||||
|
||||
if p.nesting > 0 {
|
||||
if nesting > 0 {
|
||||
return p.EOFErr()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -414,6 +370,19 @@ func (p *parser) closeCurlyBrace() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// validDirective returns true if dir is in p.validDirectives.
|
||||
func (p *parser) validDirective(dir string) bool {
|
||||
if p.validDirectives == nil {
|
||||
return true
|
||||
}
|
||||
for _, d := range p.validDirectives {
|
||||
if d == dir {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// replaceEnvVars replaces environment variables that appear in the token
|
||||
// and understands both the $UNIX and %WINDOWS% syntaxes.
|
||||
func replaceEnvVars(s string) string {
|
||||
@@ -427,13 +396,8 @@ func replaceEnvVars(s string) string {
|
||||
func replaceEnvReferences(s, refStart, refEnd string) string {
|
||||
index := strings.Index(s, refStart)
|
||||
for index != -1 {
|
||||
endIndex := strings.Index(s[index:], refEnd)
|
||||
if endIndex == -1 {
|
||||
break
|
||||
}
|
||||
|
||||
endIndex += index
|
||||
if endIndex > index+len(refStart) {
|
||||
endIndex := strings.Index(s, refEnd)
|
||||
if endIndex != -1 {
|
||||
ref := s[index : endIndex+len(refEnd)]
|
||||
s = strings.Replace(s, ref, os.Getenv(ref[len(refStart):len(ref)-len(refEnd)]), -1)
|
||||
} else {
|
||||
@@ -444,73 +408,9 @@ func replaceEnvReferences(s, refStart, refEnd string) string {
|
||||
return s
|
||||
}
|
||||
|
||||
func (p *parser) isSnippet() (bool, string) {
|
||||
keys := p.block.Keys
|
||||
// A snippet block is a single key with parens. Nothing else qualifies.
|
||||
if len(keys) == 1 && strings.HasPrefix(keys[0], "(") && strings.HasSuffix(keys[0], ")") {
|
||||
return true, strings.TrimSuffix(keys[0][1:], ")")
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// read and store everything in a block for later replay.
|
||||
func (p *parser) snippetTokens() ([]Token, error) {
|
||||
// snippet must have curlies.
|
||||
err := p.openCurlyBrace()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nesting := 1 // count our own nesting in snippets
|
||||
tokens := []Token{}
|
||||
for p.Next() {
|
||||
if p.Val() == "}" {
|
||||
nesting--
|
||||
if nesting == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if p.Val() == "{" {
|
||||
nesting++
|
||||
}
|
||||
tokens = append(tokens, p.tokens[p.cursor])
|
||||
}
|
||||
// make sure we're matched up
|
||||
if nesting != 0 {
|
||||
return nil, p.SyntaxErr("}")
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
// ServerBlock associates any number of keys from the
|
||||
// head of the server block with tokens, which are
|
||||
// grouped by segments.
|
||||
// ServerBlock associates any number of keys (usually addresses
|
||||
// of some sort) with tokens (grouped by directive name).
|
||||
type ServerBlock struct {
|
||||
Keys []string
|
||||
Segments []Segment
|
||||
}
|
||||
|
||||
// DispenseDirective returns a dispenser that contains
|
||||
// all the tokens in the server block.
|
||||
func (sb ServerBlock) DispenseDirective(dir string) *Dispenser {
|
||||
var tokens []Token
|
||||
for _, seg := range sb.Segments {
|
||||
if len(seg) > 0 && seg[0].Text == dir {
|
||||
tokens = append(tokens, seg...)
|
||||
}
|
||||
}
|
||||
return NewDispenser(tokens)
|
||||
}
|
||||
|
||||
// Segment is a list of tokens which begins with a directive
|
||||
// and ends at the end of the directive (either at the end of
|
||||
// the line, or at the end of a block it opens).
|
||||
type Segment []Token
|
||||
|
||||
// Directive returns the directive name for the segment.
|
||||
// The directive name is the text of the first token.
|
||||
func (s Segment) Directive() string {
|
||||
if len(s) > 0 {
|
||||
return s[0].Text
|
||||
}
|
||||
return ""
|
||||
Keys []string
|
||||
Tokens map[string][]Token
|
||||
}
|
||||
Executable → Regular
+84
-261
@@ -1,17 +1,3 @@
|
||||
// Copyright 2015 Light Code Labs, LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
@@ -25,7 +11,7 @@ import (
|
||||
func TestAllTokens(t *testing.T) {
|
||||
input := strings.NewReader("a b c\nd e")
|
||||
expected := []string{"a", "b", "c", "d", "e"}
|
||||
tokens, err := allTokens("TestAllTokens", input)
|
||||
tokens, err := allTokens(input)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Expected no error, got %v", err)
|
||||
@@ -53,67 +39,84 @@ func TestParseOneAndImport(t *testing.T) {
|
||||
input string
|
||||
shouldErr bool
|
||||
keys []string
|
||||
numTokens []int // number of tokens to expect in each segment
|
||||
tokens map[string]int // map of directive name to number of tokens expected
|
||||
}{
|
||||
{`localhost`, false, []string{
|
||||
"localhost",
|
||||
}, []int{}},
|
||||
}, map[string]int{}},
|
||||
|
||||
{`localhost
|
||||
dir1`, false, []string{
|
||||
"localhost",
|
||||
}, []int{1}},
|
||||
}, map[string]int{
|
||||
"dir1": 1,
|
||||
}},
|
||||
|
||||
{`localhost:1234
|
||||
dir1 foo bar`, false, []string{
|
||||
"localhost:1234",
|
||||
}, []int{3},
|
||||
},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
}},
|
||||
|
||||
{`localhost {
|
||||
dir1
|
||||
}`, false, []string{
|
||||
"localhost",
|
||||
}, []int{1}},
|
||||
}, map[string]int{
|
||||
"dir1": 1,
|
||||
}},
|
||||
|
||||
{`localhost:1234 {
|
||||
dir1 foo bar
|
||||
dir2
|
||||
}`, false, []string{
|
||||
"localhost:1234",
|
||||
}, []int{3, 1}},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
"dir2": 1,
|
||||
}},
|
||||
|
||||
{`http://localhost https://localhost
|
||||
dir1 foo bar`, false, []string{
|
||||
"http://localhost",
|
||||
"https://localhost",
|
||||
}, []int{3}},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
}},
|
||||
|
||||
{`http://localhost https://localhost {
|
||||
dir1 foo bar
|
||||
}`, false, []string{
|
||||
"http://localhost",
|
||||
"https://localhost",
|
||||
}, []int{3}},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
}},
|
||||
|
||||
{`http://localhost, https://localhost {
|
||||
dir1 foo bar
|
||||
}`, false, []string{
|
||||
"http://localhost",
|
||||
"https://localhost",
|
||||
}, []int{3}},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
}},
|
||||
|
||||
{`http://localhost, {
|
||||
}`, true, []string{
|
||||
"http://localhost",
|
||||
}, []int{}},
|
||||
}, map[string]int{}},
|
||||
|
||||
{`host1:80, http://host2.com
|
||||
dir1 foo bar
|
||||
dir2 baz`, false, []string{
|
||||
"host1:80",
|
||||
"http://host2.com",
|
||||
}, []int{3, 2}},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
"dir2": 2,
|
||||
}},
|
||||
|
||||
{`http://host1.com,
|
||||
http://host2.com,
|
||||
@@ -121,7 +124,7 @@ func TestParseOneAndImport(t *testing.T) {
|
||||
"http://host1.com",
|
||||
"http://host2.com",
|
||||
"https://host3.com",
|
||||
}, []int{}},
|
||||
}, map[string]int{}},
|
||||
|
||||
{`http://host1.com:1234, https://host2.com
|
||||
dir1 foo {
|
||||
@@ -130,7 +133,10 @@ func TestParseOneAndImport(t *testing.T) {
|
||||
dir2`, false, []string{
|
||||
"http://host1.com:1234",
|
||||
"https://host2.com",
|
||||
}, []int{6, 1}},
|
||||
}, map[string]int{
|
||||
"dir1": 6,
|
||||
"dir2": 1,
|
||||
}},
|
||||
|
||||
{`127.0.0.1
|
||||
dir1 {
|
||||
@@ -140,25 +146,34 @@ func TestParseOneAndImport(t *testing.T) {
|
||||
foo bar
|
||||
}`, false, []string{
|
||||
"127.0.0.1",
|
||||
}, []int{5, 5}},
|
||||
}, map[string]int{
|
||||
"dir1": 5,
|
||||
"dir2": 5,
|
||||
}},
|
||||
|
||||
{`localhost
|
||||
dir1 {
|
||||
foo`, true, []string{
|
||||
"localhost",
|
||||
}, []int{3}},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
}},
|
||||
|
||||
{`localhost
|
||||
dir1 {
|
||||
}`, false, []string{
|
||||
"localhost",
|
||||
}, []int{3}},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
}},
|
||||
|
||||
{`localhost
|
||||
dir1 {
|
||||
} }`, true, []string{
|
||||
"localhost",
|
||||
}, []int{}},
|
||||
}, map[string]int{
|
||||
"dir1": 3,
|
||||
}},
|
||||
|
||||
{`localhost
|
||||
dir1 {
|
||||
@@ -168,38 +183,37 @@ func TestParseOneAndImport(t *testing.T) {
|
||||
}
|
||||
dir2 foo bar`, false, []string{
|
||||
"localhost",
|
||||
}, []int{7, 3}},
|
||||
}, map[string]int{
|
||||
"dir1": 7,
|
||||
"dir2": 3,
|
||||
}},
|
||||
|
||||
{``, false, []string{}, []int{}},
|
||||
{``, false, []string{}, map[string]int{}},
|
||||
|
||||
{`localhost
|
||||
dir1 arg1
|
||||
import testdata/import_test1.txt`, false, []string{
|
||||
"localhost",
|
||||
}, []int{2, 3, 1}},
|
||||
}, map[string]int{
|
||||
"dir1": 2,
|
||||
"dir2": 3,
|
||||
"dir3": 1,
|
||||
}},
|
||||
|
||||
{`import testdata/import_test2.txt`, false, []string{
|
||||
"host1",
|
||||
}, []int{1, 2}},
|
||||
}, map[string]int{
|
||||
"dir1": 1,
|
||||
"dir2": 2,
|
||||
}},
|
||||
|
||||
{`import testdata/import_test1.txt testdata/import_test2.txt`, true, []string{}, []int{}},
|
||||
{`import testdata/import_test1.txt testdata/import_test2.txt`, true, []string{}, map[string]int{}},
|
||||
|
||||
{`import testdata/not_found.txt`, true, []string{}, []int{}},
|
||||
{`import testdata/not_found.txt`, true, []string{}, map[string]int{}},
|
||||
|
||||
{`""`, false, []string{}, []int{}},
|
||||
{`""`, false, []string{}, map[string]int{}},
|
||||
|
||||
{``, false, []string{}, []int{}},
|
||||
|
||||
// test cases found by fuzzing!
|
||||
{`import }{$"`, true, []string{}, []int{}},
|
||||
{`import /*/*.txt`, true, []string{}, []int{}},
|
||||
{`import /???/?*?o`, true, []string{}, []int{}},
|
||||
{`import /??`, true, []string{}, []int{}},
|
||||
{`import /[a-z]`, true, []string{}, []int{}},
|
||||
{`import {$}`, true, []string{}, []int{}},
|
||||
{`import {%}`, true, []string{}, []int{}},
|
||||
{`import {$$}`, true, []string{}, []int{}},
|
||||
{`import {%%}`, true, []string{}, []int{}},
|
||||
{``, false, []string{}, map[string]int{}},
|
||||
} {
|
||||
result, err := testParseOne(test.input)
|
||||
|
||||
@@ -222,16 +236,15 @@ func TestParseOneAndImport(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
if len(result.Segments) != len(test.numTokens) {
|
||||
t.Errorf("Test %d: Expected %d segments, had %d",
|
||||
i, len(test.numTokens), len(result.Segments))
|
||||
if len(result.Tokens) != len(test.tokens) {
|
||||
t.Errorf("Test %d: Expected %d directives, had %d",
|
||||
i, len(test.tokens), len(result.Tokens))
|
||||
continue
|
||||
}
|
||||
|
||||
for j, seg := range result.Segments {
|
||||
if len(seg) != test.numTokens[j] {
|
||||
t.Errorf("Test %d, segment %d: Expected %d tokens, counted %d",
|
||||
i, j, test.numTokens[j], len(seg))
|
||||
for directive, tokens := range result.Tokens {
|
||||
if len(tokens) != test.tokens[directive] {
|
||||
t.Errorf("Test %d, directive '%s': Expected %d tokens, counted %d",
|
||||
i, directive, test.tokens[directive], len(tokens))
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -251,12 +264,12 @@ func TestRecursiveImport(t *testing.T) {
|
||||
t.Errorf("got keys unexpected: expect localhost, got %v", got.Keys)
|
||||
return false
|
||||
}
|
||||
if len(got.Segments) != 2 {
|
||||
t.Errorf("got wrong number of segments: expect 2, got %d", len(got.Segments))
|
||||
if len(got.Tokens) != 2 {
|
||||
t.Errorf("got wrong number of tokens: expect 2, got %d", len(got.Tokens))
|
||||
return false
|
||||
}
|
||||
if len(got.Segments[0]) != 1 || len(got.Segments[1]) != 2 {
|
||||
t.Errorf("got unexpect tokens: %v", got.Segments)
|
||||
if len(got.Tokens["dir1"]) != 1 || len(got.Tokens["dir2"]) != 2 {
|
||||
t.Errorf("got unexpect tokens: %v", got.Tokens)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -333,68 +346,6 @@ func TestRecursiveImport(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectiveImport(t *testing.T) {
|
||||
testParseOne := func(input string) (ServerBlock, error) {
|
||||
p := testParser(input)
|
||||
p.Next() // parseOne doesn't call Next() to start, so we must
|
||||
err := p.parseOne()
|
||||
return p.block, err
|
||||
}
|
||||
|
||||
isExpected := func(got ServerBlock) bool {
|
||||
if len(got.Keys) != 1 || got.Keys[0] != "localhost" {
|
||||
t.Errorf("got keys unexpected: expect localhost, got %v", got.Keys)
|
||||
return false
|
||||
}
|
||||
if len(got.Segments) != 2 {
|
||||
t.Errorf("got wrong number of segments: expect 2, got %d", len(got.Segments))
|
||||
return false
|
||||
}
|
||||
if len(got.Segments[0]) != 1 || len(got.Segments[1]) != 8 {
|
||||
t.Errorf("got unexpect tokens: %v", got.Segments)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
directiveFile, err := filepath.Abs("testdata/directive_import_test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = ioutil.WriteFile(directiveFile, []byte(`prop1 1
|
||||
prop2 2`), 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(directiveFile)
|
||||
|
||||
// import from existing file
|
||||
result, err := testParseOne(`localhost
|
||||
dir1
|
||||
proxy {
|
||||
import testdata/directive_import_test
|
||||
transparent
|
||||
}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !isExpected(result) {
|
||||
t.Error("directive import failed")
|
||||
}
|
||||
|
||||
// import from nonexistent file
|
||||
_, err = testParseOne(`localhost
|
||||
dir1
|
||||
proxy {
|
||||
import testdata/nonexistent_file
|
||||
transparent
|
||||
}`)
|
||||
if err == nil {
|
||||
t.Fatal("expected error when importing a nonexistent file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAll(t *testing.T) {
|
||||
for i, test := range []struct {
|
||||
input string
|
||||
@@ -476,7 +427,6 @@ func TestEnvironmentReplacement(t *testing.T) {
|
||||
os.Setenv("PORT", "8080")
|
||||
os.Setenv("ADDRESS", "servername.com")
|
||||
os.Setenv("FOOBAR", "foobar")
|
||||
os.Setenv("PARTIAL_DIR", "r1")
|
||||
|
||||
// basic test; unix-style env vars
|
||||
p := testParser(`{$ADDRESS}`)
|
||||
@@ -485,13 +435,6 @@ func TestEnvironmentReplacement(t *testing.T) {
|
||||
t.Errorf("Expected key to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
|
||||
// basic test; unix-style env vars
|
||||
p = testParser(`di{$PARTIAL_DIR}`)
|
||||
blocks, _ = p.parseAll()
|
||||
if actual, expected := blocks[0].Keys[0], "dir1"; expected != actual {
|
||||
t.Errorf("Expected key to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
|
||||
// multiple vars per token
|
||||
p = testParser(`{$ADDRESS}:{$PORT}`)
|
||||
blocks, _ = p.parseAll()
|
||||
@@ -519,21 +462,21 @@ func TestEnvironmentReplacement(t *testing.T) {
|
||||
if actual, expected := blocks[0].Keys[0], ":8080"; expected != actual {
|
||||
t.Errorf("Expected key to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
if actual, expected := blocks[0].Segments[0][1].Text, "foobar"; expected != actual {
|
||||
if actual, expected := blocks[0].Tokens["dir1"][1].Text, "foobar"; expected != actual {
|
||||
t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
|
||||
// combined windows env vars in argument
|
||||
p = testParser(":{%PORT%}\ndir1 {%ADDRESS%}/{%FOOBAR%}")
|
||||
blocks, _ = p.parseAll()
|
||||
if actual, expected := blocks[0].Segments[0][1].Text, "servername.com/foobar"; expected != actual {
|
||||
if actual, expected := blocks[0].Tokens["dir1"][1].Text, "servername.com/foobar"; expected != actual {
|
||||
t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
|
||||
// malformed env var (windows)
|
||||
p = testParser(":1234\ndir1 {%ADDRESS}")
|
||||
blocks, _ = p.parseAll()
|
||||
if actual, expected := blocks[0].Segments[0][1].Text, "{%ADDRESS}"; expected != actual {
|
||||
if actual, expected := blocks[0].Tokens["dir1"][1].Text, "{%ADDRESS}"; expected != actual {
|
||||
t.Errorf("Expected host to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
|
||||
@@ -547,133 +490,13 @@ func TestEnvironmentReplacement(t *testing.T) {
|
||||
// in quoted field
|
||||
p = testParser(":1234\ndir1 \"Test {$FOOBAR} test\"")
|
||||
blocks, _ = p.parseAll()
|
||||
if actual, expected := blocks[0].Segments[0][1].Text, "Test foobar test"; expected != actual {
|
||||
t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
|
||||
// after end token
|
||||
p = testParser(":1234\nanswer \"{{ .Name }} {$FOOBAR}\"")
|
||||
blocks, _ = p.parseAll()
|
||||
if actual, expected := blocks[0].Segments[0][1].Text, "{{ .Name }} foobar"; expected != actual {
|
||||
t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnippets(t *testing.T) {
|
||||
p := testParser(`
|
||||
(common) {
|
||||
gzip foo
|
||||
errors stderr
|
||||
}
|
||||
http://example.com {
|
||||
import common
|
||||
}
|
||||
`)
|
||||
blocks, err := p.parseAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range blocks {
|
||||
t.Log(b.Keys)
|
||||
t.Log(b.Segments)
|
||||
}
|
||||
if len(blocks) != 1 {
|
||||
t.Fatalf("Expect exactly one server block. Got %d.", len(blocks))
|
||||
}
|
||||
if actual, expected := blocks[0].Keys[0], "http://example.com"; expected != actual {
|
||||
t.Errorf("Expected server name to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
if len(blocks[0].Segments) != 2 {
|
||||
t.Fatalf("Server block should have tokens from import, got: %+v", blocks[0])
|
||||
}
|
||||
if actual, expected := blocks[0].Segments[0][0].Text, "gzip"; expected != actual {
|
||||
t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
if actual, expected := blocks[0].Segments[1][1].Text, "stderr"; expected != actual {
|
||||
t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func writeStringToTempFileOrDie(t *testing.T, str string) (pathToFile string) {
|
||||
file, err := ioutil.TempFile("", t.Name())
|
||||
if err != nil {
|
||||
panic(err) // get a stack trace so we know where this was called from.
|
||||
}
|
||||
if _, err := file.WriteString(str); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return file.Name()
|
||||
}
|
||||
|
||||
func TestImportedFilesIgnoreNonDirectiveImportTokens(t *testing.T) {
|
||||
fileName := writeStringToTempFileOrDie(t, `
|
||||
http://example.com {
|
||||
# This isn't an import directive, it's just an arg with value 'import'
|
||||
basicauth / import password
|
||||
}
|
||||
`)
|
||||
// Parse the root file that imports the other one.
|
||||
p := testParser(`import ` + fileName)
|
||||
blocks, err := p.parseAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range blocks {
|
||||
t.Log(b.Keys)
|
||||
t.Log(b.Segments)
|
||||
}
|
||||
auth := blocks[0].Segments[0]
|
||||
line := auth[0].Text + " " + auth[1].Text + " " + auth[2].Text + " " + auth[3].Text
|
||||
if line != "basicauth / import password" {
|
||||
// Previously, it would be changed to:
|
||||
// basicauth / import /path/to/test/dir/password
|
||||
// referencing a file that (probably) doesn't exist and changing the
|
||||
// password!
|
||||
t.Errorf("Expected basicauth tokens to be 'basicauth / import password' but got %#q", line)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnippetAcrossMultipleFiles(t *testing.T) {
|
||||
// Make the derived Caddyfile that expects (common) to be defined.
|
||||
fileName := writeStringToTempFileOrDie(t, `
|
||||
http://example.com {
|
||||
import common
|
||||
}
|
||||
`)
|
||||
|
||||
// Parse the root file that defines (common) and then imports the other one.
|
||||
p := testParser(`
|
||||
(common) {
|
||||
gzip foo
|
||||
}
|
||||
import ` + fileName + `
|
||||
`)
|
||||
|
||||
blocks, err := p.parseAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, b := range blocks {
|
||||
t.Log(b.Keys)
|
||||
t.Log(b.Segments)
|
||||
}
|
||||
if len(blocks) != 1 {
|
||||
t.Fatalf("Expect exactly one server block. Got %d.", len(blocks))
|
||||
}
|
||||
if actual, expected := blocks[0].Keys[0], "http://example.com"; expected != actual {
|
||||
t.Errorf("Expected server name to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
if len(blocks[0].Segments) != 1 {
|
||||
t.Fatalf("Server block should have tokens from import")
|
||||
}
|
||||
if actual, expected := blocks[0].Segments[0][0].Text, "gzip"; expected != actual {
|
||||
if actual, expected := blocks[0].Tokens["dir1"][1].Text, "Test foobar test"; expected != actual {
|
||||
t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func testParser(input string) parser {
|
||||
return parser{Dispenser: newTestDispenser(input)}
|
||||
buf := strings.NewReader(input)
|
||||
p := parser{Dispenser: NewDispenser("Caddyfile", buf)}
|
||||
return p
|
||||
}
|
||||
Vendored
Executable → Regular
Vendored
Executable → Regular
Vendored
Executable → Regular
Vendored
Executable → Regular
Vendored
Executable → Regular
@@ -0,0 +1,159 @@
|
||||
// Package basicauth implements HTTP Basic Authentication for Caddy.
|
||||
//
|
||||
// This is useful for simple protections on a website, like requiring
|
||||
// a password to access an admin interface. This package assumes a
|
||||
// fairly small threat model.
|
||||
package basicauth
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha1"
|
||||
"crypto/subtle"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/jimstudt/http-authentication/basic"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// BasicAuth is middleware to protect resources with a username and password.
|
||||
// Note that HTTP Basic Authentication is not secure by itself and should
|
||||
// not be used to protect important assets without HTTPS. Even then, the
|
||||
// security of HTTP Basic Auth is disputed. Use discretion when deciding
|
||||
// what to protect with BasicAuth.
|
||||
type BasicAuth struct {
|
||||
Next httpserver.Handler
|
||||
SiteRoot string
|
||||
Rules []Rule
|
||||
}
|
||||
|
||||
// ServeHTTP implements the httpserver.Handler interface.
|
||||
func (a BasicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
var hasAuth bool
|
||||
var isAuthenticated bool
|
||||
|
||||
for _, rule := range a.Rules {
|
||||
for _, res := range rule.Resources {
|
||||
if !httpserver.Path(r.URL.Path).Matches(res) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Path matches; parse auth header
|
||||
username, password, ok := r.BasicAuth()
|
||||
hasAuth = true
|
||||
|
||||
// Check credentials
|
||||
if !ok ||
|
||||
username != rule.Username ||
|
||||
!rule.Password(password) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Flag set only on successful authentication
|
||||
isAuthenticated = true
|
||||
}
|
||||
}
|
||||
|
||||
if hasAuth {
|
||||
if !isAuthenticated {
|
||||
w.Header().Set("WWW-Authenticate", "Basic realm=\"Restricted\"")
|
||||
return http.StatusUnauthorized, nil
|
||||
}
|
||||
// "It's an older code, sir, but it checks out. I was about to clear them."
|
||||
return a.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Pass-through when no paths match
|
||||
return a.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Rule represents a BasicAuth rule. A username and password
|
||||
// combination protect the associated resources, which are
|
||||
// file or directory paths.
|
||||
type Rule struct {
|
||||
Username string
|
||||
Password func(string) bool
|
||||
Resources []string
|
||||
}
|
||||
|
||||
// PasswordMatcher determines whether a password matches a rule.
|
||||
type PasswordMatcher func(pw string) bool
|
||||
|
||||
var (
|
||||
htpasswords map[string]map[string]PasswordMatcher
|
||||
htpasswordsMu sync.Mutex
|
||||
)
|
||||
|
||||
// GetHtpasswdMatcher matches password rules.
|
||||
func GetHtpasswdMatcher(filename, username, siteRoot string) (PasswordMatcher, error) {
|
||||
filename = filepath.Join(siteRoot, filename)
|
||||
htpasswordsMu.Lock()
|
||||
if htpasswords == nil {
|
||||
htpasswords = make(map[string]map[string]PasswordMatcher)
|
||||
}
|
||||
pm := htpasswords[filename]
|
||||
if pm == nil {
|
||||
fh, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %q: %v", filename, err)
|
||||
}
|
||||
defer fh.Close()
|
||||
pm = make(map[string]PasswordMatcher)
|
||||
if err = parseHtpasswd(pm, fh); err != nil {
|
||||
return nil, fmt.Errorf("parsing htpasswd %q: %v", fh.Name(), err)
|
||||
}
|
||||
htpasswords[filename] = pm
|
||||
}
|
||||
htpasswordsMu.Unlock()
|
||||
if pm[username] == nil {
|
||||
return nil, fmt.Errorf("username %q not found in %q", username, filename)
|
||||
}
|
||||
return pm[username], nil
|
||||
}
|
||||
|
||||
func parseHtpasswd(pm map[string]PasswordMatcher, r io.Reader) error {
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" || strings.IndexByte(line, '#') == 0 {
|
||||
continue
|
||||
}
|
||||
i := strings.IndexByte(line, ':')
|
||||
if i <= 0 {
|
||||
return fmt.Errorf("malformed line, no color: %q", line)
|
||||
}
|
||||
user, encoded := line[:i], line[i+1:]
|
||||
for _, p := range basic.DefaultSystems {
|
||||
matcher, err := p(encoded)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if matcher != nil {
|
||||
pm[user] = matcher.MatchesPassword
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return scanner.Err()
|
||||
}
|
||||
|
||||
// PlainMatcher returns a PasswordMatcher that does a constant-time
|
||||
// byte comparison against the password passw.
|
||||
func PlainMatcher(passw string) PasswordMatcher {
|
||||
// compare hashes of equal length instead of actual password
|
||||
// to avoid leaking password length
|
||||
passwHash := sha1.New()
|
||||
passwHash.Write([]byte(passw))
|
||||
passwSum := passwHash.Sum(nil)
|
||||
return func(pw string) bool {
|
||||
pwHash := sha1.New()
|
||||
pwHash.Write([]byte(pw))
|
||||
pwSum := pwHash.Sum(nil)
|
||||
return subtle.ConstantTimeCompare([]byte(pwSum), []byte(passwSum)) == 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package basicauth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestBasicAuth(t *testing.T) {
|
||||
rw := BasicAuth{
|
||||
Next: httpserver.HandlerFunc(contentHandler),
|
||||
Rules: []Rule{
|
||||
{Username: "test", Password: PlainMatcher("ttest"), Resources: []string{"/testing"}},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
from string
|
||||
result int
|
||||
cred string
|
||||
}{
|
||||
{"/testing", http.StatusUnauthorized, "ttest:test"},
|
||||
{"/testing", http.StatusOK, "test:ttest"},
|
||||
{"/testing", http.StatusUnauthorized, ""},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
|
||||
req, err := http.NewRequest("GET", test.from, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Could not create HTTP request %v", i, err)
|
||||
}
|
||||
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(test.cred))
|
||||
req.Header.Set("Authorization", auth)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
result, err := rw.ServeHTTP(rec, req)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Could not ServeHTTP %v", i, err)
|
||||
}
|
||||
if result != test.result {
|
||||
t.Errorf("Test %d: Expected Header '%d' but was '%d'",
|
||||
i, test.result, result)
|
||||
}
|
||||
if result == http.StatusUnauthorized {
|
||||
headers := rec.Header()
|
||||
if val, ok := headers["Www-Authenticate"]; ok {
|
||||
if val[0] != "Basic realm=\"Restricted\"" {
|
||||
t.Errorf("Test %d, Www-Authenticate should be %s provided %s", i, "Basic", val[0])
|
||||
}
|
||||
} else {
|
||||
t.Errorf("Test %d, should provide a header Www-Authenticate", i)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestMultipleOverlappingRules(t *testing.T) {
|
||||
rw := BasicAuth{
|
||||
Next: httpserver.HandlerFunc(contentHandler),
|
||||
Rules: []Rule{
|
||||
{Username: "t", Password: PlainMatcher("p1"), Resources: []string{"/t"}},
|
||||
{Username: "t1", Password: PlainMatcher("p2"), Resources: []string{"/t/t"}},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
from string
|
||||
result int
|
||||
cred string
|
||||
}{
|
||||
{"/t", http.StatusOK, "t:p1"},
|
||||
{"/t/t", http.StatusOK, "t:p1"},
|
||||
{"/t/t", http.StatusOK, "t1:p2"},
|
||||
{"/a", http.StatusOK, "t1:p2"},
|
||||
{"/t/t", http.StatusUnauthorized, "t1:p3"},
|
||||
{"/t", http.StatusUnauthorized, "t1:p2"},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
|
||||
req, err := http.NewRequest("GET", test.from, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Could not create HTTP request %v", i, err)
|
||||
}
|
||||
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(test.cred))
|
||||
req.Header.Set("Authorization", auth)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
result, err := rw.ServeHTTP(rec, req)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Could not ServeHTTP %v", i, err)
|
||||
}
|
||||
if result != test.result {
|
||||
t.Errorf("Test %d: Expected Header '%d' but was '%d'",
|
||||
i, test.result, result)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func contentHandler(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
fmt.Fprintf(w, r.URL.String())
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
func TestHtpasswd(t *testing.T) {
|
||||
htpasswdPasswd := "IedFOuGmTpT8"
|
||||
htpasswdFile := `sha1:{SHA}dcAUljwz99qFjYR0YLTXx0RqLww=
|
||||
md5:$apr1$l42y8rex$pOA2VJ0x/0TwaFeAF9nX61`
|
||||
|
||||
htfh, err := ioutil.TempFile("", "basicauth-")
|
||||
if err != nil {
|
||||
t.Skipf("Error creating temp file (%v), will skip htpassword test")
|
||||
return
|
||||
}
|
||||
defer os.Remove(htfh.Name())
|
||||
if _, err = htfh.Write([]byte(htpasswdFile)); err != nil {
|
||||
t.Fatalf("write htpasswd file %q: %v", htfh.Name(), err)
|
||||
}
|
||||
htfh.Close()
|
||||
|
||||
for i, username := range []string{"sha1", "md5"} {
|
||||
rule := Rule{Username: username, Resources: []string{"/testing"}}
|
||||
|
||||
siteRoot := filepath.Dir(htfh.Name())
|
||||
filename := filepath.Base(htfh.Name())
|
||||
if rule.Password, err = GetHtpasswdMatcher(filename, rule.Username, siteRoot); err != nil {
|
||||
t.Fatalf("GetHtpasswdMatcher(%q, %q): %v", htfh.Name(), rule.Username, err)
|
||||
}
|
||||
t.Logf("%d. username=%q", i, rule.Username)
|
||||
if !rule.Password(htpasswdPasswd) || rule.Password(htpasswdPasswd+"!") {
|
||||
t.Errorf("%d (%s) password does not match.", i, rule.Username)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package basicauth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("basicauth", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
// setup configures a new BasicAuth middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
cfg := httpserver.GetConfig(c)
|
||||
root := cfg.Root
|
||||
|
||||
rules, err := basicAuthParse(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
basic := BasicAuth{Rules: rules}
|
||||
|
||||
cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
basic.Next = next
|
||||
basic.SiteRoot = root
|
||||
return basic
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func basicAuthParse(c *caddy.Controller) ([]Rule, error) {
|
||||
var rules []Rule
|
||||
cfg := httpserver.GetConfig(c)
|
||||
|
||||
var err error
|
||||
for c.Next() {
|
||||
var rule Rule
|
||||
|
||||
args := c.RemainingArgs()
|
||||
|
||||
switch len(args) {
|
||||
case 2:
|
||||
rule.Username = args[0]
|
||||
if rule.Password, err = passwordMatcher(rule.Username, args[1], cfg.Root); err != nil {
|
||||
return rules, c.Errf("Get password matcher from %s: %v", c.Val(), err)
|
||||
}
|
||||
|
||||
for c.NextBlock() {
|
||||
rule.Resources = append(rule.Resources, c.Val())
|
||||
if c.NextArg() {
|
||||
return rules, c.Errf("Expecting only one resource per line (extra '%s')", c.Val())
|
||||
}
|
||||
}
|
||||
case 3:
|
||||
rule.Resources = append(rule.Resources, args[0])
|
||||
rule.Username = args[1]
|
||||
if rule.Password, err = passwordMatcher(rule.Username, args[2], cfg.Root); err != nil {
|
||||
return rules, c.Errf("Get password matcher from %s: %v", c.Val(), err)
|
||||
}
|
||||
default:
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
|
||||
rules = append(rules, rule)
|
||||
}
|
||||
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
func passwordMatcher(username, passw, siteRoot string) (PasswordMatcher, error) {
|
||||
if !strings.HasPrefix(passw, "htpasswd=") {
|
||||
return PlainMatcher(passw), nil
|
||||
}
|
||||
return GetHtpasswdMatcher(passw[9:], username, siteRoot)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package basicauth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `basicauth user pwd`)
|
||||
err := setup(c)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no errors, but got: %v", err)
|
||||
}
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
if len(mids) == 0 {
|
||||
t.Fatal("Expected middleware, got 0 instead")
|
||||
}
|
||||
|
||||
handler := mids[0](httpserver.EmptyNext)
|
||||
myHandler, ok := handler.(BasicAuth)
|
||||
if !ok {
|
||||
t.Fatalf("Expected handler to be type BasicAuth, got: %#v", handler)
|
||||
}
|
||||
|
||||
if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
|
||||
t.Error("'Next' field of handler was not set properly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicAuthParse(t *testing.T) {
|
||||
htpasswdPasswd := "IedFOuGmTpT8"
|
||||
htpasswdFile := `sha1:{SHA}dcAUljwz99qFjYR0YLTXx0RqLww=
|
||||
md5:$apr1$l42y8rex$pOA2VJ0x/0TwaFeAF9nX61`
|
||||
|
||||
var skipHtpassword bool
|
||||
htfh, err := ioutil.TempFile(".", "basicauth-")
|
||||
if err != nil {
|
||||
t.Logf("Error creating temp file (%v), will skip htpassword test", err)
|
||||
skipHtpassword = true
|
||||
} else {
|
||||
if _, err = htfh.Write([]byte(htpasswdFile)); err != nil {
|
||||
t.Fatalf("write htpasswd file %q: %v", htfh.Name(), err)
|
||||
}
|
||||
htfh.Close()
|
||||
defer os.Remove(htfh.Name())
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
input string
|
||||
shouldErr bool
|
||||
password string
|
||||
expected []Rule
|
||||
}{
|
||||
{`basicauth user pwd`, false, "pwd", []Rule{
|
||||
{Username: "user"},
|
||||
}},
|
||||
{`basicauth user pwd {
|
||||
}`, false, "pwd", []Rule{
|
||||
{Username: "user"},
|
||||
}},
|
||||
{`basicauth user pwd {
|
||||
/resource1
|
||||
/resource2
|
||||
}`, false, "pwd", []Rule{
|
||||
{Username: "user", Resources: []string{"/resource1", "/resource2"}},
|
||||
}},
|
||||
{`basicauth /resource user pwd`, false, "pwd", []Rule{
|
||||
{Username: "user", Resources: []string{"/resource"}},
|
||||
}},
|
||||
{`basicauth /res1 user1 pwd1
|
||||
basicauth /res2 user2 pwd2`, false, "pwd", []Rule{
|
||||
{Username: "user1", Resources: []string{"/res1"}},
|
||||
{Username: "user2", Resources: []string{"/res2"}},
|
||||
}},
|
||||
{`basicauth user`, true, "", []Rule{}},
|
||||
{`basicauth`, true, "", []Rule{}},
|
||||
{`basicauth /resource user pwd asdf`, true, "", []Rule{}},
|
||||
|
||||
{`basicauth sha1 htpasswd=` + htfh.Name(), false, htpasswdPasswd, []Rule{
|
||||
{Username: "sha1"},
|
||||
}},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
actual, err := basicAuthParse(caddy.NewTestController("http", test.input))
|
||||
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d didn't error, but it should have", i)
|
||||
} else if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
|
||||
}
|
||||
|
||||
if len(actual) != len(test.expected) {
|
||||
t.Fatalf("Test %d expected %d rules, but got %d",
|
||||
i, len(test.expected), len(actual))
|
||||
}
|
||||
|
||||
for j, expectedRule := range test.expected {
|
||||
actualRule := actual[j]
|
||||
|
||||
if actualRule.Username != expectedRule.Username {
|
||||
t.Errorf("Test %d, rule %d: Expected username '%s', got '%s'",
|
||||
i, j, expectedRule.Username, actualRule.Username)
|
||||
}
|
||||
|
||||
if strings.Contains(test.input, "htpasswd=") && skipHtpassword {
|
||||
continue
|
||||
}
|
||||
pwd := test.password
|
||||
if len(actual) > 1 {
|
||||
pwd = fmt.Sprintf("%s%d", pwd, j+1)
|
||||
}
|
||||
if !actualRule.Password(pwd) || actualRule.Password(test.password+"!") {
|
||||
t.Errorf("Test %d, rule %d: Expected password '%v', got '%v'",
|
||||
i, j, test.password, actualRule.Password(""))
|
||||
}
|
||||
|
||||
expectedRes := fmt.Sprintf("%v", expectedRule.Resources)
|
||||
actualRes := fmt.Sprintf("%v", actualRule.Resources)
|
||||
if actualRes != expectedRes {
|
||||
t.Errorf("Test %d, rule %d: Expected resource list %s, but got %s",
|
||||
i, j, expectedRes, actualRes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package bind
|
||||
|
||||
import (
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("bind", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setupBind,
|
||||
})
|
||||
}
|
||||
|
||||
func setupBind(c *caddy.Controller) error {
|
||||
config := httpserver.GetConfig(c)
|
||||
for c.Next() {
|
||||
if !c.Args(&config.ListenHost) {
|
||||
return c.ArgErr()
|
||||
}
|
||||
config.TLS.ListenHost = config.ListenHost // necessary for ACME challenges, see issue #309
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package bind
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetupBind(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `bind 1.2.3.4`)
|
||||
err := setupBind(c)
|
||||
if err != nil {
|
||||
t.Fatalf("Expected no errors, but got: %v", err)
|
||||
}
|
||||
|
||||
cfg := httpserver.GetConfig(c)
|
||||
if got, want := cfg.ListenHost, "1.2.3.4"; got != want {
|
||||
t.Errorf("Expected the config's ListenHost to be %s, was %s", want, got)
|
||||
}
|
||||
if got, want := cfg.TLS.ListenHost, "1.2.3.4"; got != want {
|
||||
t.Errorf("Expected the TLS config's ListenHost to be %s, was %s", want, got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
// Package browse provides middleware for listing files in a directory
|
||||
// when directory path is requested instead of a specific file.
|
||||
package browse
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
"github.com/mholt/caddy/caddyhttp/staticfiles"
|
||||
)
|
||||
|
||||
const (
|
||||
sortByName = "name"
|
||||
sortBySize = "size"
|
||||
sortByTime = "time"
|
||||
)
|
||||
|
||||
// Browse is an http.Handler that can show a file listing when
|
||||
// directories in the given paths are specified.
|
||||
type Browse struct {
|
||||
Next httpserver.Handler
|
||||
Configs []Config
|
||||
IgnoreIndexes bool
|
||||
}
|
||||
|
||||
// Config is a configuration for browsing in a particular path.
|
||||
type Config struct {
|
||||
PathScope string
|
||||
Fs staticfiles.FileServer
|
||||
Variables interface{}
|
||||
Template *template.Template
|
||||
}
|
||||
|
||||
// A Listing is the context used to fill out a template.
|
||||
type Listing struct {
|
||||
// The name of the directory (the last element of the path)
|
||||
Name string
|
||||
|
||||
// The full path of the request
|
||||
Path string
|
||||
|
||||
// Whether the parent directory is browsable
|
||||
CanGoUp bool
|
||||
|
||||
// The items (files and folders) in the path
|
||||
Items []FileInfo
|
||||
|
||||
// The number of directories in the listing
|
||||
NumDirs int
|
||||
|
||||
// The number of files (items that aren't directories) in the listing
|
||||
NumFiles int
|
||||
|
||||
// Which sorting order is used
|
||||
Sort string
|
||||
|
||||
// And which order
|
||||
Order string
|
||||
|
||||
// If ≠0 then Items have been limited to that many elements
|
||||
ItemsLimitedTo int
|
||||
|
||||
// Optional custom variables for use in browse templates
|
||||
User interface{}
|
||||
|
||||
httpserver.Context
|
||||
}
|
||||
|
||||
// BreadcrumbMap returns l.Path where every element is a map
|
||||
// of URLs and path segment names.
|
||||
func (l Listing) BreadcrumbMap() map[string]string {
|
||||
result := map[string]string{}
|
||||
|
||||
if len(l.Path) == 0 {
|
||||
return result
|
||||
}
|
||||
|
||||
// skip trailing slash
|
||||
lpath := l.Path
|
||||
if lpath[len(lpath)-1] == '/' {
|
||||
lpath = lpath[:len(lpath)-1]
|
||||
}
|
||||
|
||||
parts := strings.Split(lpath, "/")
|
||||
for i, part := range parts {
|
||||
if i == 0 && part == "" {
|
||||
// Leading slash (root)
|
||||
result["/"] = "/"
|
||||
continue
|
||||
}
|
||||
result[strings.Join(parts[:i+1], "/")] = part
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// FileInfo is the info about a particular file or directory
|
||||
type FileInfo struct {
|
||||
Name string
|
||||
Size int64
|
||||
URL string
|
||||
ModTime time.Time
|
||||
Mode os.FileMode
|
||||
IsDir bool
|
||||
}
|
||||
|
||||
// HumanSize returns the size of the file as a human-readable string
|
||||
// in IEC format (i.e. power of 2 or base 1024).
|
||||
func (fi FileInfo) HumanSize() string {
|
||||
return humanize.IBytes(uint64(fi.Size))
|
||||
}
|
||||
|
||||
// HumanModTime returns the modified time of the file as a human-readable string.
|
||||
func (fi FileInfo) HumanModTime(format string) string {
|
||||
return fi.ModTime.Format(format)
|
||||
}
|
||||
|
||||
// Implement sorting for Listing
|
||||
type byName Listing
|
||||
type bySize Listing
|
||||
type byTime Listing
|
||||
|
||||
// By Name
|
||||
func (l byName) Len() int { return len(l.Items) }
|
||||
func (l byName) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
|
||||
|
||||
// Treat upper and lower case equally
|
||||
func (l byName) Less(i, j int) bool {
|
||||
return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name)
|
||||
}
|
||||
|
||||
// By Size
|
||||
func (l bySize) Len() int { return len(l.Items) }
|
||||
func (l bySize) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
|
||||
|
||||
const directoryOffset = -1 << 31 // = math.MinInt32
|
||||
func (l bySize) Less(i, j int) bool {
|
||||
iSize, jSize := l.Items[i].Size, l.Items[j].Size
|
||||
if l.Items[i].IsDir {
|
||||
iSize = directoryOffset + iSize
|
||||
}
|
||||
if l.Items[j].IsDir {
|
||||
jSize = directoryOffset + jSize
|
||||
}
|
||||
return iSize < jSize
|
||||
}
|
||||
|
||||
// By Time
|
||||
func (l byTime) Len() int { return len(l.Items) }
|
||||
func (l byTime) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }
|
||||
func (l byTime) Less(i, j int) bool { return l.Items[i].ModTime.Before(l.Items[j].ModTime) }
|
||||
|
||||
// Add sorting method to "Listing"
|
||||
// it will apply what's in ".Sort" and ".Order"
|
||||
func (l Listing) applySort() {
|
||||
// Check '.Order' to know how to sort
|
||||
if l.Order == "desc" {
|
||||
switch l.Sort {
|
||||
case sortByName:
|
||||
sort.Sort(sort.Reverse(byName(l)))
|
||||
case sortBySize:
|
||||
sort.Sort(sort.Reverse(bySize(l)))
|
||||
case sortByTime:
|
||||
sort.Sort(sort.Reverse(byTime(l)))
|
||||
default:
|
||||
// If not one of the above, do nothing
|
||||
return
|
||||
}
|
||||
} else { // If we had more Orderings we could add them here
|
||||
switch l.Sort {
|
||||
case sortByName:
|
||||
sort.Sort(byName(l))
|
||||
case sortBySize:
|
||||
sort.Sort(bySize(l))
|
||||
case sortByTime:
|
||||
sort.Sort(byTime(l))
|
||||
default:
|
||||
// If not one of the above, do nothing
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func directoryListing(files []os.FileInfo, canGoUp bool, urlPath string, config *Config) (Listing, bool) {
|
||||
var (
|
||||
fileinfos []FileInfo
|
||||
dirCount, fileCount int
|
||||
hasIndexFile bool
|
||||
)
|
||||
|
||||
for _, f := range files {
|
||||
name := f.Name()
|
||||
|
||||
for _, indexName := range staticfiles.IndexPages {
|
||||
if name == indexName {
|
||||
hasIndexFile = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if f.IsDir() {
|
||||
name += "/"
|
||||
dirCount++
|
||||
} else {
|
||||
fileCount++
|
||||
}
|
||||
|
||||
url := url.URL{Path: "./" + name} // prepend with "./" to fix paths with ':' in the name
|
||||
|
||||
if config.Fs.IsHidden(f) {
|
||||
continue
|
||||
}
|
||||
|
||||
fileinfos = append(fileinfos, FileInfo{
|
||||
IsDir: f.IsDir(),
|
||||
Name: f.Name(),
|
||||
Size: f.Size(),
|
||||
URL: url.String(),
|
||||
ModTime: f.ModTime().UTC(),
|
||||
Mode: f.Mode(),
|
||||
})
|
||||
}
|
||||
|
||||
return Listing{
|
||||
Name: path.Base(urlPath),
|
||||
Path: urlPath,
|
||||
CanGoUp: canGoUp,
|
||||
Items: fileinfos,
|
||||
NumDirs: dirCount,
|
||||
NumFiles: fileCount,
|
||||
}, hasIndexFile
|
||||
}
|
||||
|
||||
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
|
||||
// If so, control is handed over to ServeListing.
|
||||
func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
var bc *Config
|
||||
// See if there's a browse configuration to match the path
|
||||
for i := range b.Configs {
|
||||
if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) {
|
||||
bc = &b.Configs[i]
|
||||
goto inScope
|
||||
}
|
||||
}
|
||||
return b.Next.ServeHTTP(w, r)
|
||||
inScope:
|
||||
|
||||
// Browse works on existing directories; delegate everything else
|
||||
requestedFilepath, err := bc.Fs.Root.Open(r.URL.Path)
|
||||
if err != nil {
|
||||
switch {
|
||||
case os.IsPermission(err):
|
||||
return http.StatusForbidden, err
|
||||
case os.IsExist(err):
|
||||
return http.StatusNotFound, err
|
||||
default:
|
||||
return b.Next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
defer requestedFilepath.Close()
|
||||
|
||||
info, err := requestedFilepath.Stat()
|
||||
if err != nil {
|
||||
switch {
|
||||
case os.IsPermission(err):
|
||||
return http.StatusForbidden, err
|
||||
case os.IsExist(err):
|
||||
return http.StatusGone, err
|
||||
default:
|
||||
return b.Next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return b.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Do not reply to anything else because it might be nonsensical
|
||||
switch r.Method {
|
||||
case http.MethodGet, http.MethodHead:
|
||||
// proceed, noop
|
||||
case "PROPFIND", http.MethodOptions:
|
||||
return http.StatusNotImplemented, nil
|
||||
default:
|
||||
return b.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Browsing navigation gets messed up if browsing a directory
|
||||
// that doesn't end in "/" (which it should, anyway)
|
||||
if !strings.HasSuffix(r.URL.Path, "/") {
|
||||
staticfiles.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return b.ServeListing(w, r, requestedFilepath, bc)
|
||||
}
|
||||
|
||||
func (b Browse) loadDirectoryContents(requestedFilepath http.File, urlPath string, config *Config) (*Listing, bool, error) {
|
||||
files, err := requestedFilepath.Readdir(-1)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
// Determine if user can browse up another folder
|
||||
var canGoUp bool
|
||||
curPathDir := path.Dir(strings.TrimSuffix(urlPath, "/"))
|
||||
for _, other := range b.Configs {
|
||||
if strings.HasPrefix(curPathDir, other.PathScope) {
|
||||
canGoUp = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Assemble listing of directory contents
|
||||
listing, hasIndex := directoryListing(files, canGoUp, urlPath, config)
|
||||
|
||||
return &listing, hasIndex, nil
|
||||
}
|
||||
|
||||
// handleSortOrder gets and stores for a Listing the 'sort' and 'order',
|
||||
// and reads 'limit' if given. The latter is 0 if not given.
|
||||
//
|
||||
// This sets Cookies.
|
||||
func (b Browse) handleSortOrder(w http.ResponseWriter, r *http.Request, scope string) (sort string, order string, limit int, err error) {
|
||||
sort, order, limitQuery := r.URL.Query().Get("sort"), r.URL.Query().Get("order"), r.URL.Query().Get("limit")
|
||||
|
||||
// If the query 'sort' or 'order' is empty, use defaults or any values previously saved in Cookies
|
||||
switch sort {
|
||||
case "":
|
||||
sort = sortByName
|
||||
if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil {
|
||||
sort = sortCookie.Value
|
||||
}
|
||||
case sortByName, sortBySize, sortByTime:
|
||||
http.SetCookie(w, &http.Cookie{Name: "sort", Value: sort, Path: scope, Secure: r.TLS != nil})
|
||||
}
|
||||
|
||||
switch order {
|
||||
case "":
|
||||
order = "asc"
|
||||
if orderCookie, orderErr := r.Cookie("order"); orderErr == nil {
|
||||
order = orderCookie.Value
|
||||
}
|
||||
case "asc", "desc":
|
||||
http.SetCookie(w, &http.Cookie{Name: "order", Value: order, Path: scope, Secure: r.TLS != nil})
|
||||
}
|
||||
|
||||
if limitQuery != "" {
|
||||
limit, err = strconv.Atoi(limitQuery)
|
||||
if err != nil { // if the 'limit' query can't be interpreted as a number, return err
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ServeListing returns a formatted view of 'requestedFilepath' contents'.
|
||||
func (b Browse) ServeListing(w http.ResponseWriter, r *http.Request, requestedFilepath http.File, bc *Config) (int, error) {
|
||||
listing, containsIndex, err := b.loadDirectoryContents(requestedFilepath, r.URL.Path, bc)
|
||||
if err != nil {
|
||||
switch {
|
||||
case os.IsPermission(err):
|
||||
return http.StatusForbidden, err
|
||||
case os.IsExist(err):
|
||||
return http.StatusGone, err
|
||||
default:
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
}
|
||||
if containsIndex && !b.IgnoreIndexes { // directory isn't browsable
|
||||
return b.Next.ServeHTTP(w, r)
|
||||
}
|
||||
listing.Context = httpserver.Context{
|
||||
Root: bc.Fs.Root,
|
||||
Req: r,
|
||||
URL: r.URL,
|
||||
}
|
||||
listing.User = bc.Variables
|
||||
|
||||
// Copy the query values into the Listing struct
|
||||
var limit int
|
||||
listing.Sort, listing.Order, limit, err = b.handleSortOrder(w, r, bc.PathScope)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
listing.applySort()
|
||||
|
||||
if limit > 0 && limit <= len(listing.Items) {
|
||||
listing.Items = listing.Items[:limit]
|
||||
listing.ItemsLimitedTo = limit
|
||||
}
|
||||
|
||||
var buf *bytes.Buffer
|
||||
acceptHeader := strings.ToLower(strings.Join(r.Header["Accept"], ","))
|
||||
switch {
|
||||
case strings.Contains(acceptHeader, "application/json"):
|
||||
if buf, err = b.formatAsJSON(listing, bc); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
|
||||
default: // There's no 'application/json' in the 'Accept' header; browse normally
|
||||
if buf, err = b.formatAsHTML(listing, bc); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
|
||||
}
|
||||
|
||||
buf.WriteTo(w)
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
func (b Browse) formatAsJSON(listing *Listing, bc *Config) (*bytes.Buffer, error) {
|
||||
marsh, err := json.Marshal(listing.Items)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
_, err = buf.Write(marsh)
|
||||
return buf, err
|
||||
}
|
||||
|
||||
func (b Browse) formatAsHTML(listing *Listing, bc *Config) (*bytes.Buffer, error) {
|
||||
buf := new(bytes.Buffer)
|
||||
err := bc.Template.Execute(buf, listing)
|
||||
return buf, err
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package browse
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"testing"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
"github.com/mholt/caddy/caddyhttp/staticfiles"
|
||||
)
|
||||
|
||||
func TestSort(t *testing.T) {
|
||||
// making up []fileInfo with bogus values;
|
||||
// to be used to make up our "listing"
|
||||
fileInfos := []FileInfo{
|
||||
{
|
||||
Name: "fizz",
|
||||
Size: 4,
|
||||
ModTime: time.Now().AddDate(-1, 1, 0),
|
||||
},
|
||||
{
|
||||
Name: "buzz",
|
||||
Size: 2,
|
||||
ModTime: time.Now().AddDate(0, -3, 3),
|
||||
},
|
||||
{
|
||||
Name: "bazz",
|
||||
Size: 1,
|
||||
ModTime: time.Now().AddDate(0, -2, -23),
|
||||
},
|
||||
{
|
||||
Name: "jazz",
|
||||
Size: 3,
|
||||
ModTime: time.Now(),
|
||||
},
|
||||
}
|
||||
listing := Listing{
|
||||
Name: "foobar",
|
||||
Path: "/fizz/buzz",
|
||||
CanGoUp: false,
|
||||
Items: fileInfos,
|
||||
}
|
||||
|
||||
// sort by name
|
||||
listing.Sort = "name"
|
||||
listing.applySort()
|
||||
if !sort.IsSorted(byName(listing)) {
|
||||
t.Errorf("The listing isn't name sorted: %v", listing.Items)
|
||||
}
|
||||
|
||||
// sort by size
|
||||
listing.Sort = "size"
|
||||
listing.applySort()
|
||||
if !sort.IsSorted(bySize(listing)) {
|
||||
t.Errorf("The listing isn't size sorted: %v", listing.Items)
|
||||
}
|
||||
|
||||
// sort by Time
|
||||
listing.Sort = "time"
|
||||
listing.applySort()
|
||||
if !sort.IsSorted(byTime(listing)) {
|
||||
t.Errorf("The listing isn't time sorted: %v", listing.Items)
|
||||
}
|
||||
|
||||
// reverse by name
|
||||
listing.Sort = "name"
|
||||
listing.Order = "desc"
|
||||
listing.applySort()
|
||||
if !isReversed(byName(listing)) {
|
||||
t.Errorf("The listing isn't reversed by name: %v", listing.Items)
|
||||
}
|
||||
|
||||
// reverse by size
|
||||
listing.Sort = "size"
|
||||
listing.Order = "desc"
|
||||
listing.applySort()
|
||||
if !isReversed(bySize(listing)) {
|
||||
t.Errorf("The listing isn't reversed by size: %v", listing.Items)
|
||||
}
|
||||
|
||||
// reverse by time
|
||||
listing.Sort = "time"
|
||||
listing.Order = "desc"
|
||||
listing.applySort()
|
||||
if !isReversed(byTime(listing)) {
|
||||
t.Errorf("The listing isn't reversed by time: %v", listing.Items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrowseHTTPMethods(t *testing.T) {
|
||||
tmpl, err := template.ParseFiles("testdata/photos.tpl")
|
||||
if err != nil {
|
||||
t.Fatalf("An error occurred while parsing the template: %v", err)
|
||||
}
|
||||
|
||||
b := Browse{
|
||||
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
return http.StatusTeapot, nil // not t.Fatalf, or we will not see what other methods yield
|
||||
}),
|
||||
Configs: []Config{
|
||||
{
|
||||
PathScope: "/photos",
|
||||
Fs: staticfiles.FileServer{
|
||||
Root: http.Dir("./testdata"),
|
||||
},
|
||||
Template: tmpl,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
for method, expected := range map[string]int{
|
||||
http.MethodGet: http.StatusOK,
|
||||
http.MethodHead: http.StatusOK,
|
||||
http.MethodOptions: http.StatusNotImplemented,
|
||||
"PROPFIND": http.StatusNotImplemented,
|
||||
} {
|
||||
req, err := http.NewRequest(method, "/photos/", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test: Could not create HTTP request: %v", err)
|
||||
}
|
||||
|
||||
code, _ := b.ServeHTTP(rec, req)
|
||||
if code != expected {
|
||||
t.Errorf("Wrong status with HTTP Method %s: expected %d, got %d", method, expected, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrowseTemplate(t *testing.T) {
|
||||
tmpl, err := template.ParseFiles("testdata/photos.tpl")
|
||||
if err != nil {
|
||||
t.Fatalf("An error occurred while parsing the template: %v", err)
|
||||
}
|
||||
|
||||
b := Browse{
|
||||
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
t.Fatalf("Next shouldn't be called")
|
||||
return 0, nil
|
||||
}),
|
||||
Configs: []Config{
|
||||
{
|
||||
PathScope: "/photos",
|
||||
Fs: staticfiles.FileServer{
|
||||
Root: http.Dir("./testdata"),
|
||||
Hide: []string{"photos/hidden.html"},
|
||||
},
|
||||
Template: tmpl,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", "/photos/", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test: Could not create HTTP request: %v", err)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
code, _ := b.ServeHTTP(rec, req)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("Wrong status, expected %d, got %d", http.StatusOK, code)
|
||||
}
|
||||
|
||||
respBody := rec.Body.String()
|
||||
expectedBody := `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Template</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Header</h1>
|
||||
|
||||
<h1>/photos/</h1>
|
||||
|
||||
<a href="./test.html">test.html</a><br>
|
||||
|
||||
<a href="./test2.html">test2.html</a><br>
|
||||
|
||||
<a href="./test3.html">test3.html</a><br>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
if respBody != expectedBody {
|
||||
t.Fatalf("Expected body: %v got: %v", expectedBody, respBody)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBrowseJson(t *testing.T) {
|
||||
b := Browse{
|
||||
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
t.Fatalf("Next shouldn't be called")
|
||||
return 0, nil
|
||||
}),
|
||||
Configs: []Config{
|
||||
{
|
||||
PathScope: "/photos/",
|
||||
Fs: staticfiles.FileServer{
|
||||
Root: http.Dir("./testdata"),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
//Getting the listing from the ./testdata/photos, the listing returned will be used to validate test results
|
||||
testDataPath := filepath.Join("./testdata", "photos")
|
||||
file, err := os.Open(testDataPath)
|
||||
if err != nil {
|
||||
if os.IsPermission(err) {
|
||||
t.Fatalf("Os Permission Error")
|
||||
}
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
files, err := file.Readdir(-1)
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to Read Contents of the directory")
|
||||
}
|
||||
var fileinfos []FileInfo
|
||||
|
||||
for i, f := range files {
|
||||
name := f.Name()
|
||||
|
||||
// Tests fail in CI environment because all file mod times are the same for
|
||||
// some reason, making the sorting unpredictable. To hack around this,
|
||||
// we ensure here that each file has a different mod time.
|
||||
chTime := f.ModTime().UTC().Add(-(time.Duration(i) * time.Second))
|
||||
if err := os.Chtimes(filepath.Join(testDataPath, name), chTime, chTime); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if f.IsDir() {
|
||||
name += "/"
|
||||
}
|
||||
|
||||
url := url.URL{Path: "./" + name}
|
||||
|
||||
fileinfos = append(fileinfos, FileInfo{
|
||||
IsDir: f.IsDir(),
|
||||
Name: f.Name(),
|
||||
Size: f.Size(),
|
||||
URL: url.String(),
|
||||
ModTime: chTime,
|
||||
Mode: f.Mode(),
|
||||
})
|
||||
}
|
||||
listing := Listing{Items: fileinfos} // this listing will be used for validation inside the tests
|
||||
|
||||
tests := []struct {
|
||||
QueryURL string
|
||||
SortBy string
|
||||
OrderBy string
|
||||
Limit int
|
||||
shouldErr bool
|
||||
expectedResult []FileInfo
|
||||
}{
|
||||
//test case 1: testing for default sort and order and without the limit parameter, default sort is by name and the default order is ascending
|
||||
//without the limit query entire listing will be produced
|
||||
{"/", "", "", -1, false, listing.Items},
|
||||
//test case 2: limit is set to 1, orderBy and sortBy is default
|
||||
{"/?limit=1", "", "", 1, false, listing.Items[:1]},
|
||||
//test case 3 : if the listing request is bigger than total size of listing then it should return everything
|
||||
{"/?limit=100000000", "", "", 100000000, false, listing.Items},
|
||||
//test case 4 : testing for negative limit
|
||||
{"/?limit=-1", "", "", -1, false, listing.Items},
|
||||
//test case 5 : testing with limit set to -1 and order set to descending
|
||||
{"/?limit=-1&order=desc", "", "desc", -1, false, listing.Items},
|
||||
//test case 6 : testing with limit set to 2 and order set to descending
|
||||
{"/?limit=2&order=desc", "", "desc", 2, false, listing.Items},
|
||||
//test case 7 : testing with limit set to 3 and order set to descending
|
||||
{"/?limit=3&order=desc", "", "desc", 3, false, listing.Items},
|
||||
//test case 8 : testing with limit set to 3 and order set to ascending
|
||||
{"/?limit=3&order=asc", "", "asc", 3, false, listing.Items},
|
||||
//test case 9 : testing with limit set to 1111111 and order set to ascending
|
||||
{"/?limit=1111111&order=asc", "", "asc", 1111111, false, listing.Items},
|
||||
//test case 10 : testing with limit set to default and order set to ascending and sorting by size
|
||||
{"/?order=asc&sort=size", "size", "asc", -1, false, listing.Items},
|
||||
//test case 11 : testing with limit set to default and order set to ascending and sorting by last modified
|
||||
{"/?order=asc&sort=time", "time", "asc", -1, false, listing.Items},
|
||||
//test case 12 : testing with limit set to 1 and order set to ascending and sorting by last modified
|
||||
{"/?order=asc&sort=time&limit=1", "time", "asc", 1, false, listing.Items},
|
||||
//test case 13 : testing with limit set to -100 and order set to ascending and sorting by last modified
|
||||
{"/?order=asc&sort=time&limit=-100", "time", "asc", -100, false, listing.Items},
|
||||
//test case 14 : testing with limit set to -100 and order set to ascending and sorting by size
|
||||
{"/?order=asc&sort=size&limit=-100", "size", "asc", -100, false, listing.Items},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
var marsh []byte
|
||||
req, err := http.NewRequest("GET", "/photos"+test.QueryURL, nil)
|
||||
if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored when making request, but it shouldn't have; got '%v'", i, err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
code, err := b.ServeHTTP(rec, req)
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d didn't error, but it should have", i)
|
||||
} else if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
|
||||
}
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("In test %d: Wrong status, expected %d, got %d", i, http.StatusOK, code)
|
||||
}
|
||||
if rec.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {
|
||||
t.Fatalf("Expected Content type to be application/json; charset=utf-8, but got %s ", rec.HeaderMap.Get("Content-Type"))
|
||||
}
|
||||
|
||||
actualJSONResponse := rec.Body.String()
|
||||
copyOflisting := listing
|
||||
if test.SortBy == "" {
|
||||
copyOflisting.Sort = "name"
|
||||
} else {
|
||||
copyOflisting.Sort = test.SortBy
|
||||
}
|
||||
if test.OrderBy == "" {
|
||||
copyOflisting.Order = "asc"
|
||||
} else {
|
||||
copyOflisting.Order = test.OrderBy
|
||||
}
|
||||
|
||||
copyOflisting.applySort()
|
||||
|
||||
limit := test.Limit
|
||||
if limit <= len(copyOflisting.Items) && limit > 0 {
|
||||
marsh, err = json.Marshal(copyOflisting.Items[:limit])
|
||||
} else { // if the 'limit' query is empty, or has the wrong value, list everything
|
||||
marsh, err = json.Marshal(copyOflisting.Items)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to Marshal the listing ")
|
||||
}
|
||||
expectedJSON := string(marsh)
|
||||
|
||||
if actualJSONResponse != expectedJSON {
|
||||
t.Errorf("JSON response doesn't match the expected for test number %d with sort=%s, order=%s\nExpected response %s\nActual response = %s\n",
|
||||
i+1, test.SortBy, test.OrderBy, expectedJSON, actualJSONResponse)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// "sort" package has "IsSorted" function, but no "IsReversed";
|
||||
func isReversed(data sort.Interface) bool {
|
||||
n := data.Len()
|
||||
for i := n - 1; i > 0; i-- {
|
||||
if !data.Less(i, i-1) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package browse
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"text/template"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
"github.com/mholt/caddy/caddyhttp/staticfiles"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("browse", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
// setup configures a new Browse middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
configs, err := browseParse(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := Browse{
|
||||
Configs: configs,
|
||||
IgnoreIndexes: false,
|
||||
}
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
b.Next = next
|
||||
return b
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func browseParse(c *caddy.Controller) ([]Config, error) {
|
||||
var configs []Config
|
||||
|
||||
cfg := httpserver.GetConfig(c)
|
||||
|
||||
appendCfg := func(bc Config) error {
|
||||
for _, c := range configs {
|
||||
if c.PathScope == bc.PathScope {
|
||||
return fmt.Errorf("duplicate browsing config for %s", c.PathScope)
|
||||
}
|
||||
}
|
||||
configs = append(configs, bc)
|
||||
return nil
|
||||
}
|
||||
|
||||
for c.Next() {
|
||||
var bc Config
|
||||
|
||||
// First argument is directory to allow browsing; default is site root
|
||||
if c.NextArg() {
|
||||
bc.PathScope = c.Val()
|
||||
} else {
|
||||
bc.PathScope = "/"
|
||||
}
|
||||
|
||||
bc.Fs = staticfiles.FileServer{
|
||||
Root: http.Dir(cfg.Root),
|
||||
Hide: httpserver.GetConfig(c).HiddenFiles,
|
||||
}
|
||||
|
||||
// Second argument would be the template file to use
|
||||
var tplText string
|
||||
if c.NextArg() {
|
||||
tplBytes, err := ioutil.ReadFile(c.Val())
|
||||
if err != nil {
|
||||
return configs, err
|
||||
}
|
||||
tplText = string(tplBytes)
|
||||
} else {
|
||||
tplText = defaultTemplate
|
||||
}
|
||||
|
||||
// Build the template
|
||||
tpl, err := template.New("listing").Parse(tplText)
|
||||
if err != nil {
|
||||
return configs, err
|
||||
}
|
||||
bc.Template = tpl
|
||||
|
||||
// Save configuration
|
||||
err = appendCfg(bc)
|
||||
if err != nil {
|
||||
return configs, err
|
||||
}
|
||||
}
|
||||
|
||||
return configs, nil
|
||||
}
|
||||
|
||||
// The default template to use when serving up directory listings
|
||||
const defaultTemplate = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{{.Name}}</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
* { padding: 0; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
text-rendering: optimizespeed;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #006ed3;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover,
|
||||
h1 a:hover {
|
||||
color: #319cff;
|
||||
}
|
||||
|
||||
header,
|
||||
#summary {
|
||||
padding-left: 5%;
|
||||
padding-right: 5%;
|
||||
}
|
||||
|
||||
th:first-child,
|
||||
td:first-child {
|
||||
padding-left: 5%;
|
||||
}
|
||||
|
||||
th:last-child,
|
||||
td:last-child {
|
||||
padding-right: 5%;
|
||||
}
|
||||
|
||||
header {
|
||||
padding-top: 25px;
|
||||
padding-bottom: 15px;
|
||||
background-color: #f2f2f2;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 20px;
|
||||
font-weight: normal;
|
||||
white-space: nowrap;
|
||||
overflow-x: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
h1 a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
h1 a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
main {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.meta {
|
||||
font-size: 12px;
|
||||
font-family: Verdana, sans-serif;
|
||||
border-bottom: 1px solid #9C9C9C;
|
||||
padding-top: 15px;
|
||||
padding-bottom: 15px;
|
||||
}
|
||||
|
||||
.meta-item {
|
||||
margin-right: 1em;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
tr {
|
||||
border-bottom: 1px dashed #dadada;
|
||||
}
|
||||
|
||||
tbody tr:hover {
|
||||
background-color: #ffffec;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
text-align: left;
|
||||
padding: 10px 0;
|
||||
}
|
||||
|
||||
th {
|
||||
padding-top: 15px;
|
||||
padding-bottom: 15px;
|
||||
font-size: 16px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
th a {
|
||||
color: black;
|
||||
}
|
||||
|
||||
th svg {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
td {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
td:first-child {
|
||||
width: 50%;
|
||||
}
|
||||
|
||||
th:last-child,
|
||||
td:last-child {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
td:first-child svg {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
td .name,
|
||||
td .goup {
|
||||
margin-left: 1.75em;
|
||||
word-break: break-all;
|
||||
overflow-wrap: break-word;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
footer {
|
||||
padding: 40px 20px;
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.hideable {
|
||||
display: none;
|
||||
}
|
||||
|
||||
td:first-child {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
th:nth-child(2),
|
||||
td:nth-child(2) {
|
||||
padding-right: 5%;
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="0" width="0" style="position: absolute;">
|
||||
<defs>
|
||||
<!-- Folder -->
|
||||
<linearGradient id="f" y2="640" gradientUnits="userSpaceOnUse" x2="244.84" gradientTransform="matrix(.97319 0 0 1.0135 -.50695 -13.679)" y1="415.75" x1="244.84">
|
||||
<stop stop-color="#b3ddfd" offset="0"/>
|
||||
<stop stop-color="#69c" offset="1"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="e" y2="571.06" gradientUnits="userSpaceOnUse" x2="238.03" gradientTransform="translate(0,2)" y1="346.05" x1="236.26">
|
||||
<stop stop-color="#ace" offset="0"/>
|
||||
<stop stop-color="#369" offset="1"/>
|
||||
</linearGradient>
|
||||
<g id="folder" transform="translate(-266.06 -193.36)">
|
||||
<g transform="matrix(.066019 0 0 .066019 264.2 170.93)">
|
||||
<g transform="matrix(1.4738 0 0 1.4738 -52.053 -166.93)">
|
||||
<path fill="#69c" d="m98.424 343.78c-11.08 0-20 8.92-20 20v48.5 33.719 105.06c0 11.08 8.92 20 20 20h279.22c11.08 0 20-8.92 20-20v-138.78c0-11.08-8.92-20-20-20h-117.12c-7.5478-1.1844-9.7958-6.8483-10.375-11.312v-5.625-11.562c0-11.08-8.92-20-20-20h-131.72z"/>
|
||||
<rect rx="12.885" ry="12.199" height="227.28" width="366.69" y="409.69" x="54.428" fill="#369"/>
|
||||
<path fill="url(#e)" d="m98.424 345.78c-11.08 0-20 8.92-20 20v48.5 33.719 105.06c0 11.08 8.92 20 20 20h279.22c11.08 0 20-8.92 20-20v-138.78c0-11.08-8.92-20-20-20h-117.12c-7.5478-1.1844-9.7958-6.8483-10.375-11.312v-5.625-11.562c0-11.08-8.92-20-20-20h-131.72z"/>
|
||||
<rect rx="12.885" ry="12.199" height="227.28" width="366.69" y="407.69" x="54.428" fill="url(#f)"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- File -->
|
||||
<linearGradient id="a">
|
||||
<stop stop-color="#cbcbcb" offset="0"/>
|
||||
<stop stop-color="#f0f0f0" offset=".34923"/>
|
||||
<stop stop-color="#e2e2e2" offset="1"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="d" y2="686.15" xlink:href="#a" gradientUnits="userSpaceOnUse" y1="207.83" gradientTransform="matrix(.28346 0 0 .31053 -608.52 485.11)" x2="380.1" x1="749.25"/>
|
||||
<linearGradient id="c" y2="287.74" xlink:href="#a" gradientUnits="userSpaceOnUse" y1="169.44" gradientTransform="matrix(.28342 0 0 .31057 -608.52 485.11)" x2="622.33" x1="741.64"/>
|
||||
<linearGradient id="b" y2="418.54" gradientUnits="userSpaceOnUse" y1="236.13" gradientTransform="matrix(.29343 0 0 .29999 -608.52 485.11)" x2="330.88" x1="687.96">
|
||||
<stop stop-color="#fff" offset="0"/>
|
||||
<stop stop-color="#fff" stop-opacity="0" offset="1"/>
|
||||
</linearGradient>
|
||||
<g id="file" transform="translate(-278.15 -216.59)">
|
||||
<g fill-rule="evenodd" transform="matrix(.19775 0 0 .19775 381.05 112.68)">
|
||||
<path d="m-520.17 525.5v36.739 36.739 36.739 36.739h33.528 33.528 33.528 33.528v-36.739-36.739-36.739l-33.528-36.739h-33.528-33.528-33.528z" stroke-opacity=".36478" stroke-width=".42649" fill="#fff"/>
|
||||
<g>
|
||||
<path d="m-520.11 525.68v36.739 36.739 36.739 36.739h33.528 33.528 33.528 33.528v-36.739-36.739-36.739l-33.528-36.739h-33.528-33.528-33.528z" stroke-opacity=".36478" stroke="#000" stroke-width=".42649" fill="url(#d)"/>
|
||||
<path d="m-386 562.42c-10.108-2.9925-23.206-2.5682-33.101-0.86253 1.7084-10.962 1.922-24.701-0.4271-35.877l33.528 36.739z" stroke-width=".95407pt" fill="url(#c)"/>
|
||||
<path d="m-519.13 537-0.60402 134.7h131.68l0.0755-33.296c-2.9446 1.1325-32.692-40.998-70.141-39.186-37.483 1.8137-27.785-56.777-61.006-62.214z" stroke-width="1pt" fill="url(#b)"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- Up arrow -->
|
||||
<g id="up-arrow" transform="translate(-279.22 -208.12)">
|
||||
<path transform="matrix(.22413 0 0 .12089 335.67 164.35)" stroke-width="0" d="m-194.17 412.01h-28.827-28.827l14.414-24.965 14.414-24.965 14.414 24.965z"/>
|
||||
</g>
|
||||
|
||||
<!-- Down arrow -->
|
||||
<g id="down-arrow" transform="translate(-279.22 -208.12)">
|
||||
<path transform="matrix(.22413 0 0 -.12089 335.67 257.93)" stroke-width="0" d="m-194.17 412.01h-28.827-28.827l14.414-24.965 14.414-24.965 14.414 24.965z"/>
|
||||
</g>
|
||||
</defs>
|
||||
</svg>
|
||||
|
||||
<header>
|
||||
<h1>
|
||||
{{range $url, $name := .BreadcrumbMap}}<a href="{{$url}}">{{$name}}</a>{{if ne $url "/"}}/{{end}}{{end}}
|
||||
</h1>
|
||||
</header>
|
||||
<main>
|
||||
<div class="meta">
|
||||
<div id="summary">
|
||||
<span class="meta-item"><b>{{.NumDirs}}</b> director{{if eq 1 .NumDirs}}y{{else}}ies{{end}}</span>
|
||||
<span class="meta-item"><b>{{.NumFiles}}</b> file{{if ne 1 .NumFiles}}s{{end}}</span>
|
||||
{{- if ne 0 .ItemsLimitedTo}}
|
||||
<span class="meta-item">(of which only <b>{{.ItemsLimitedTo}}</b> are displayed)</span>
|
||||
{{- end}}
|
||||
</div>
|
||||
</div>
|
||||
<div class="listing">
|
||||
<table aria-describedby="summary">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
{{- if and (eq .Sort "name") (ne .Order "desc")}}
|
||||
<a href="?sort=name&order=desc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Name <svg width="1em" height=".4em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#up-arrow"></use></svg></a>
|
||||
{{- else if and (eq .Sort "name") (ne .Order "asc")}}
|
||||
<a href="?sort=name&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Name <svg width="1em" height=".4em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#down-arrow"></use></svg></a>
|
||||
{{- else}}
|
||||
<a href="?sort=name&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Name</a>
|
||||
{{- end}}
|
||||
</th>
|
||||
<th>
|
||||
{{- if and (eq .Sort "size") (ne .Order "desc")}}
|
||||
<a href="?sort=size&order=desc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Size <svg width="1em" height=".4em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#up-arrow"></use></svg></a>
|
||||
{{- else if and (eq .Sort "size") (ne .Order "asc")}}
|
||||
<a href="?sort=size&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Size <svg width="1em" height=".4em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#down-arrow"></use></svg></a>
|
||||
{{- else}}
|
||||
<a href="?sort=size&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Size</a>
|
||||
{{- end}}
|
||||
</th>
|
||||
<th class="hideable">
|
||||
{{- if and (eq .Sort "time") (ne .Order "desc")}}
|
||||
<a href="?sort=time&order=desc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Modified <svg width="1em" height=".4em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#up-arrow"></use></svg></a>
|
||||
{{- else if and (eq .Sort "time") (ne .Order "asc")}}
|
||||
<a href="?sort=time&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Modified <svg width="1em" height=".4em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#down-arrow"></use></svg></a>
|
||||
{{- else}}
|
||||
<a href="?sort=time&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Modified</a>
|
||||
{{- end}}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{- if .CanGoUp}}
|
||||
<tr>
|
||||
<td>
|
||||
<a href="..">
|
||||
<span class="goup">Go up</span>
|
||||
</a>
|
||||
</td>
|
||||
<td>—</td>
|
||||
<td class="hideable">—</td>
|
||||
</tr>
|
||||
{{- end}}
|
||||
{{- range .Items}}
|
||||
<tr>
|
||||
<td>
|
||||
<a href="{{.URL}}">
|
||||
{{- if .IsDir}}
|
||||
<svg width="1.5em" height="1em" version="1.1" viewBox="0 0 35.678803 28.527945"><use xlink:href="#folder"></use></svg>
|
||||
{{- else}}
|
||||
<svg width="1.5em" height="1em" version="1.1" viewBox="0 0 26.604381 29.144726"><use xlink:href="#file"></use></svg>
|
||||
{{- end}}
|
||||
<span class="name">{{.Name}}</span>
|
||||
</a>
|
||||
</td>
|
||||
{{- if .IsDir}}
|
||||
<td data-order="-1">—</td>
|
||||
{{- else}}
|
||||
<td data-order="{{.Size}}">{{.HumanSize}}</td>
|
||||
{{- end}}
|
||||
<td class="hideable"><time datetime="{{.HumanModTime "2006-01-02T15:04:05Z"}}">{{.HumanModTime "01/02/2006 03:04:05 PM -07:00"}}</time></td>
|
||||
</tr>
|
||||
{{- end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</main>
|
||||
<footer>
|
||||
Served with <a rel="noopener noreferrer" href="https://caddyserver.com">Caddy</a>.
|
||||
</footer>
|
||||
<script type="text/javascript">
|
||||
function localizeDatetime(e, index, ar) {
|
||||
if (e.textContent === undefined) {
|
||||
return;
|
||||
}
|
||||
var d = new Date(e.getAttribute('datetime'));
|
||||
if (isNaN(d)) {
|
||||
d = new Date(e.textContent);
|
||||
if (isNaN(d)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
e.textContent = d.toLocaleString();
|
||||
}
|
||||
var timeList = Array.prototype.slice.call(document.getElementsByTagName("time"));
|
||||
timeList.forEach(localizeDatetime);
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
@@ -0,0 +1,81 @@
|
||||
package browse
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
tempDirPath := os.TempDir()
|
||||
_, err := os.Stat(tempDirPath)
|
||||
if err != nil {
|
||||
t.Fatalf("BeforeTest: Failed to find an existing directory for testing! Error was: %v", err)
|
||||
}
|
||||
nonExistentDirPath := filepath.Join(tempDirPath, strconv.Itoa(int(time.Now().UnixNano())))
|
||||
|
||||
tempTemplate, err := ioutil.TempFile(".", "tempTemplate")
|
||||
if err != nil {
|
||||
t.Fatalf("BeforeTest: Failed to create a temporary file in the working directory! Error was: %v", err)
|
||||
}
|
||||
defer os.Remove(tempTemplate.Name())
|
||||
|
||||
tempTemplatePath := filepath.Join(".", tempTemplate.Name())
|
||||
|
||||
for i, test := range []struct {
|
||||
input string
|
||||
expectedPathScope []string
|
||||
shouldErr bool
|
||||
}{
|
||||
// test case #0 tests handling of multiple pathscopes
|
||||
{"browse " + tempDirPath + "\n browse .", []string{tempDirPath, "."}, false},
|
||||
|
||||
// test case #1 tests instantiation of Config with default values
|
||||
{"browse /", []string{"/"}, false},
|
||||
|
||||
// test case #2 tests detectaction of custom template
|
||||
{"browse . " + tempTemplatePath, []string{"."}, false},
|
||||
|
||||
// test case #3 tests detection of non-existent template
|
||||
{"browse . " + nonExistentDirPath, nil, true},
|
||||
|
||||
// test case #4 tests detection of duplicate pathscopes
|
||||
{"browse " + tempDirPath + "\n browse " + tempDirPath, nil, true},
|
||||
} {
|
||||
|
||||
c := caddy.NewTestController("http", test.input)
|
||||
err := setup(c)
|
||||
if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test case #%d received an error of %v", i, err)
|
||||
}
|
||||
if test.expectedPathScope == nil {
|
||||
continue
|
||||
}
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
mid := mids[len(mids)-1]
|
||||
receivedConfigs := mid(nil).(Browse).Configs
|
||||
for j, config := range receivedConfigs {
|
||||
if config.PathScope != test.expectedPathScope[j] {
|
||||
t.Errorf("Test case #%d expected a pathscope of %v, but got %v", i, test.expectedPathScope, config.PathScope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// test case #6 tests startup with missing root directory in combination with default browse settings
|
||||
controller := caddy.NewTestController("http", "browse")
|
||||
cfg := httpserver.GetConfig(controller)
|
||||
|
||||
// Make sure non-existent root path doesn't return error
|
||||
cfg.Root = nonExistentDirPath
|
||||
err = setup(controller)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Test for non-existent browse path received an error, but shouldn't have: %v", err)
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
<h1>Header</h1>
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Template</title>
|
||||
</head>
|
||||
<body>
|
||||
{{.Include "header.html"}}
|
||||
<h1>{{.Path}}</h1>
|
||||
{{range .Items}}
|
||||
<a href="{{.URL}}">{{.Name}}</a><br>
|
||||
{{end}}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
Should be hidden
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test</title>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test 2</title>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
package caddyhttp
|
||||
|
||||
import (
|
||||
// plug in the server
|
||||
_ "github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
|
||||
// plug in the standard directives
|
||||
_ "github.com/mholt/caddy/caddyhttp/basicauth"
|
||||
_ "github.com/mholt/caddy/caddyhttp/bind"
|
||||
_ "github.com/mholt/caddy/caddyhttp/browse"
|
||||
_ "github.com/mholt/caddy/caddyhttp/errors"
|
||||
_ "github.com/mholt/caddy/caddyhttp/expvar"
|
||||
_ "github.com/mholt/caddy/caddyhttp/extensions"
|
||||
_ "github.com/mholt/caddy/caddyhttp/fastcgi"
|
||||
_ "github.com/mholt/caddy/caddyhttp/gzip"
|
||||
_ "github.com/mholt/caddy/caddyhttp/header"
|
||||
_ "github.com/mholt/caddy/caddyhttp/internalsrv"
|
||||
_ "github.com/mholt/caddy/caddyhttp/log"
|
||||
_ "github.com/mholt/caddy/caddyhttp/markdown"
|
||||
_ "github.com/mholt/caddy/caddyhttp/maxrequestbody"
|
||||
_ "github.com/mholt/caddy/caddyhttp/mime"
|
||||
_ "github.com/mholt/caddy/caddyhttp/pprof"
|
||||
_ "github.com/mholt/caddy/caddyhttp/proxy"
|
||||
_ "github.com/mholt/caddy/caddyhttp/redirect"
|
||||
_ "github.com/mholt/caddy/caddyhttp/rewrite"
|
||||
_ "github.com/mholt/caddy/caddyhttp/root"
|
||||
_ "github.com/mholt/caddy/caddyhttp/status"
|
||||
_ "github.com/mholt/caddy/caddyhttp/templates"
|
||||
_ "github.com/mholt/caddy/caddyhttp/websocket"
|
||||
_ "github.com/mholt/caddy/startupshutdown"
|
||||
)
|
||||
@@ -0,0 +1,19 @@
|
||||
package caddyhttp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
)
|
||||
|
||||
// TODO: this test could be improved; the purpose is to
|
||||
// ensure that the standard plugins are in fact plugged in
|
||||
// and registered properly; this is a quick/naive way to do it.
|
||||
func TestStandardPlugins(t *testing.T) {
|
||||
numStandardPlugins := 28 // importing caddyhttp plugs in this many plugins
|
||||
s := caddy.DescribePlugins()
|
||||
if got, want := strings.Count(s, "\n"), numStandardPlugins+5; got != want {
|
||||
t.Errorf("Expected all standard plugins to be plugged in, got:\n%s", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// Package errors implements an HTTP error handling middleware.
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("errors", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
// ErrorHandler handles HTTP errors (and errors from other middleware).
|
||||
type ErrorHandler struct {
|
||||
Next httpserver.Handler
|
||||
GenericErrorPage string // default error page filename
|
||||
ErrorPages map[int]string // map of status code to filename
|
||||
LogFile string
|
||||
Log *log.Logger
|
||||
LogRoller *httpserver.LogRoller
|
||||
Debug bool // if true, errors are written out to client rather than to a log
|
||||
file *os.File // a log file to close when done
|
||||
}
|
||||
|
||||
func (h ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
defer h.recovery(w, r)
|
||||
|
||||
status, err := h.Next.ServeHTTP(w, r)
|
||||
|
||||
if err != nil {
|
||||
errMsg := fmt.Sprintf("%s [ERROR %d %s] %v", time.Now().Format(timeFormat), status, r.URL.Path, err)
|
||||
if h.Debug {
|
||||
// Write error to response instead of to log
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
fmt.Fprintln(w, errMsg)
|
||||
return 0, err // returning 0 signals that a response has been written
|
||||
}
|
||||
h.Log.Println(errMsg)
|
||||
}
|
||||
|
||||
if status >= 400 {
|
||||
h.errorPage(w, r, status)
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return status, err
|
||||
}
|
||||
|
||||
// errorPage serves a static error page to w according to the status
|
||||
// code. If there is an error serving the error page, a plaintext error
|
||||
// message is written instead, and the extra error is logged.
|
||||
func (h ErrorHandler) errorPage(w http.ResponseWriter, r *http.Request, code int) {
|
||||
// See if an error page for this status code was specified
|
||||
if pagePath, ok := h.findErrorPage(code); ok {
|
||||
// Try to open it
|
||||
errorPage, err := os.Open(pagePath)
|
||||
if err != nil {
|
||||
// An additional error handling an error... <insert grumpy cat here>
|
||||
h.Log.Printf("%s [NOTICE %d %s] could not load error page: %v",
|
||||
time.Now().Format(timeFormat), code, r.URL.String(), err)
|
||||
httpserver.DefaultErrorFunc(w, r, code)
|
||||
return
|
||||
}
|
||||
defer errorPage.Close()
|
||||
|
||||
// Copy the page body into the response
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(code)
|
||||
_, err = io.Copy(w, errorPage)
|
||||
|
||||
if err != nil {
|
||||
// Epic fail... sigh.
|
||||
h.Log.Printf("%s [NOTICE %d %s] could not respond with %s: %v",
|
||||
time.Now().Format(timeFormat), code, r.URL.String(), pagePath, err)
|
||||
httpserver.DefaultErrorFunc(w, r, code)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Default error response
|
||||
httpserver.DefaultErrorFunc(w, r, code)
|
||||
}
|
||||
|
||||
func (h ErrorHandler) findErrorPage(code int) (string, bool) {
|
||||
if pagePath, ok := h.ErrorPages[code]; ok {
|
||||
return pagePath, true
|
||||
}
|
||||
|
||||
if h.GenericErrorPage != "" {
|
||||
return h.GenericErrorPage, true
|
||||
}
|
||||
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (h ErrorHandler) recovery(w http.ResponseWriter, r *http.Request) {
|
||||
rec := recover()
|
||||
if rec == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Obtain source of panic
|
||||
// From: https://gist.github.com/swdunlop/9629168
|
||||
var name, file string // function name, file name
|
||||
var line int
|
||||
var pc [16]uintptr
|
||||
n := runtime.Callers(3, pc[:])
|
||||
for _, pc := range pc[:n] {
|
||||
fn := runtime.FuncForPC(pc)
|
||||
if fn == nil {
|
||||
continue
|
||||
}
|
||||
file, line = fn.FileLine(pc)
|
||||
name = fn.Name()
|
||||
if !strings.HasPrefix(name, "runtime.") {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Trim file path
|
||||
delim := "/caddy/"
|
||||
pkgPathPos := strings.Index(file, delim)
|
||||
if pkgPathPos > -1 && len(file) > pkgPathPos+len(delim) {
|
||||
file = file[pkgPathPos+len(delim):]
|
||||
}
|
||||
|
||||
panicMsg := fmt.Sprintf("%s [PANIC %s] %s:%d - %v", time.Now().Format(timeFormat), r.URL.String(), file, line, rec)
|
||||
if h.Debug {
|
||||
// Write error and stack trace to the response rather than to a log
|
||||
var stackBuf [4096]byte
|
||||
stack := stackBuf[:runtime.Stack(stackBuf[:], false)]
|
||||
httpserver.WriteTextResponse(w, http.StatusInternalServerError, fmt.Sprintf("%s\n\n%s", panicMsg, stack))
|
||||
} else {
|
||||
// Currently we don't use the function name, since file:line is more conventional
|
||||
h.Log.Printf(panicMsg)
|
||||
h.errorPage(w, r, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
const timeFormat = "02/Jan/2006:15:04:05 -0700"
|
||||
@@ -0,0 +1,259 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestErrors(t *testing.T) {
|
||||
// create a temporary page
|
||||
const content = "This is a error page"
|
||||
|
||||
path, err := createErrorPageFile("errors_test.html", content)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(path)
|
||||
|
||||
buf := bytes.Buffer{}
|
||||
em := ErrorHandler{
|
||||
ErrorPages: map[int]string{
|
||||
http.StatusNotFound: path,
|
||||
http.StatusForbidden: "not_exist_file",
|
||||
},
|
||||
Log: log.New(&buf, "", 0),
|
||||
}
|
||||
_, notExistErr := os.Open("not_exist_file")
|
||||
|
||||
testErr := errors.New("test error")
|
||||
tests := []struct {
|
||||
next httpserver.Handler
|
||||
expectedCode int
|
||||
expectedBody string
|
||||
expectedLog string
|
||||
expectedErr error
|
||||
}{
|
||||
{
|
||||
next: genErrorHandler(http.StatusOK, nil, "normal"),
|
||||
expectedCode: http.StatusOK,
|
||||
expectedBody: "normal",
|
||||
expectedLog: "",
|
||||
expectedErr: nil,
|
||||
},
|
||||
{
|
||||
next: genErrorHandler(http.StatusMovedPermanently, testErr, ""),
|
||||
expectedCode: http.StatusMovedPermanently,
|
||||
expectedBody: "",
|
||||
expectedLog: fmt.Sprintf("[ERROR %d %s] %v\n", http.StatusMovedPermanently, "/", testErr),
|
||||
expectedErr: testErr,
|
||||
},
|
||||
{
|
||||
next: genErrorHandler(http.StatusBadRequest, nil, ""),
|
||||
expectedCode: 0,
|
||||
expectedBody: fmt.Sprintf("%d %s\n", http.StatusBadRequest,
|
||||
http.StatusText(http.StatusBadRequest)),
|
||||
expectedLog: "",
|
||||
expectedErr: nil,
|
||||
},
|
||||
{
|
||||
next: genErrorHandler(http.StatusNotFound, nil, ""),
|
||||
expectedCode: 0,
|
||||
expectedBody: content,
|
||||
expectedLog: "",
|
||||
expectedErr: nil,
|
||||
},
|
||||
{
|
||||
next: genErrorHandler(http.StatusForbidden, nil, ""),
|
||||
expectedCode: 0,
|
||||
expectedBody: fmt.Sprintf("%d %s\n", http.StatusForbidden,
|
||||
http.StatusText(http.StatusForbidden)),
|
||||
expectedLog: fmt.Sprintf("[NOTICE %d /] could not load error page: %v\n",
|
||||
http.StatusForbidden, notExistErr),
|
||||
expectedErr: nil,
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", "/", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, test := range tests {
|
||||
em.Next = test.next
|
||||
buf.Reset()
|
||||
rec := httptest.NewRecorder()
|
||||
code, err := em.ServeHTTP(rec, req)
|
||||
|
||||
if err != test.expectedErr {
|
||||
t.Errorf("Test %d: Expected error %v, but got %v",
|
||||
i, test.expectedErr, err)
|
||||
}
|
||||
if code != test.expectedCode {
|
||||
t.Errorf("Test %d: Expected status code %d, but got %d",
|
||||
i, test.expectedCode, code)
|
||||
}
|
||||
if body := rec.Body.String(); body != test.expectedBody {
|
||||
t.Errorf("Test %d: Expected body %q, but got %q",
|
||||
i, test.expectedBody, body)
|
||||
}
|
||||
if log := buf.String(); !strings.Contains(log, test.expectedLog) {
|
||||
t.Errorf("Test %d: Expected log %q, but got %q",
|
||||
i, test.expectedLog, log)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibleErrorWithPanic(t *testing.T) {
|
||||
const panicMsg = "I'm a panic"
|
||||
eh := ErrorHandler{
|
||||
ErrorPages: make(map[int]string),
|
||||
Debug: true,
|
||||
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
panic(panicMsg)
|
||||
}),
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", "/", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
code, err := eh.ServeHTTP(rec, req)
|
||||
|
||||
if code != 0 {
|
||||
t.Errorf("Expected error handler to return 0 (it should write to response), got status %d", code)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Expected error handler to return nil error (it should panic!), but got '%v'", err)
|
||||
}
|
||||
|
||||
body := rec.Body.String()
|
||||
|
||||
if !strings.Contains(body, "[PANIC /] caddyhttp/errors/errors_test.go") {
|
||||
t.Errorf("Expected response body to contain error log line, but it didn't:\n%s", body)
|
||||
}
|
||||
if !strings.Contains(body, panicMsg) {
|
||||
t.Errorf("Expected response body to contain panic message, but it didn't:\n%s", body)
|
||||
}
|
||||
if len(body) < 500 {
|
||||
t.Errorf("Expected response body to contain stack trace, but it was too short: len=%d", len(body))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericErrorPage(t *testing.T) {
|
||||
// create temporary generic error page
|
||||
const genericErrorContent = "This is a generic error page"
|
||||
|
||||
genericErrorPagePath, err := createErrorPageFile("generic_error_test.html", genericErrorContent)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(genericErrorPagePath)
|
||||
|
||||
// create temporary error page
|
||||
const notFoundErrorContent = "This is a error page"
|
||||
|
||||
notFoundErrorPagePath, err := createErrorPageFile("not_found.html", notFoundErrorContent)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(notFoundErrorPagePath)
|
||||
|
||||
buf := bytes.Buffer{}
|
||||
em := ErrorHandler{
|
||||
GenericErrorPage: genericErrorPagePath,
|
||||
ErrorPages: map[int]string{
|
||||
http.StatusNotFound: notFoundErrorPagePath,
|
||||
},
|
||||
Log: log.New(&buf, "", 0),
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
next httpserver.Handler
|
||||
expectedCode int
|
||||
expectedBody string
|
||||
expectedLog string
|
||||
expectedErr error
|
||||
}{
|
||||
{
|
||||
next: genErrorHandler(http.StatusNotFound, nil, ""),
|
||||
expectedCode: 0,
|
||||
expectedBody: notFoundErrorContent,
|
||||
expectedLog: "",
|
||||
expectedErr: nil,
|
||||
},
|
||||
{
|
||||
next: genErrorHandler(http.StatusInternalServerError, nil, ""),
|
||||
expectedCode: 0,
|
||||
expectedBody: genericErrorContent,
|
||||
expectedLog: "",
|
||||
expectedErr: nil,
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", "/", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
em.Next = test.next
|
||||
buf.Reset()
|
||||
rec := httptest.NewRecorder()
|
||||
code, err := em.ServeHTTP(rec, req)
|
||||
|
||||
if err != test.expectedErr {
|
||||
t.Errorf("Test %d: Expected error %v, but got %v",
|
||||
i, test.expectedErr, err)
|
||||
}
|
||||
if code != test.expectedCode {
|
||||
t.Errorf("Test %d: Expected status code %d, but got %d",
|
||||
i, test.expectedCode, code)
|
||||
}
|
||||
if body := rec.Body.String(); body != test.expectedBody {
|
||||
t.Errorf("Test %d: Expected body %q, but got %q",
|
||||
i, test.expectedBody, body)
|
||||
}
|
||||
if log := buf.String(); !strings.Contains(log, test.expectedLog) {
|
||||
t.Errorf("Test %d: Expected log %q, but got %q",
|
||||
i, test.expectedLog, log)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func genErrorHandler(status int, err error, body string) httpserver.Handler {
|
||||
return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if len(body) > 0 {
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
|
||||
fmt.Fprint(w, body)
|
||||
}
|
||||
return status, err
|
||||
})
|
||||
}
|
||||
|
||||
func createErrorPageFile(name string, content string) (string, error) {
|
||||
errorPageFilePath := filepath.Join(os.TempDir(), name)
|
||||
f, err := os.Create(errorPageFilePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
_, err = f.WriteString(content)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
f.Close()
|
||||
|
||||
return errorPageFilePath, nil
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/hashicorp/go-syslog"
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// setup configures a new errors middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
handler, err := errorsParse(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Open the log file for writing when the server starts
|
||||
c.OnStartup(func() error {
|
||||
var err error
|
||||
var writer io.Writer
|
||||
|
||||
switch handler.LogFile {
|
||||
case "visible":
|
||||
handler.Debug = true
|
||||
case "stdout":
|
||||
writer = os.Stdout
|
||||
case "stderr":
|
||||
writer = os.Stderr
|
||||
case "syslog":
|
||||
writer, err = gsyslog.NewLogger(gsyslog.LOG_ERR, "LOCAL0", "caddy")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
if handler.LogFile == "" {
|
||||
writer = os.Stderr // default
|
||||
break
|
||||
}
|
||||
|
||||
var file *os.File
|
||||
file, err = os.OpenFile(handler.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if handler.LogRoller != nil {
|
||||
file.Close()
|
||||
handler.LogRoller.Filename = handler.LogFile
|
||||
writer = handler.LogRoller.GetLogWriter()
|
||||
} else {
|
||||
handler.file = file
|
||||
writer = file
|
||||
}
|
||||
}
|
||||
|
||||
handler.Log = log.New(writer, "", 0)
|
||||
return nil
|
||||
})
|
||||
|
||||
// When server stops, close any open log file
|
||||
c.OnShutdown(func() error {
|
||||
if handler.file != nil {
|
||||
handler.file.Close()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
handler.Next = next
|
||||
return handler
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func errorsParse(c *caddy.Controller) (*ErrorHandler, error) {
|
||||
// Very important that we make a pointer because the startup
|
||||
// function that opens the log file must have access to the
|
||||
// same instance of the handler, not a copy.
|
||||
handler := &ErrorHandler{ErrorPages: make(map[int]string)}
|
||||
|
||||
cfg := httpserver.GetConfig(c)
|
||||
|
||||
optionalBlock := func() (bool, error) {
|
||||
var hadBlock bool
|
||||
|
||||
for c.NextBlock() {
|
||||
hadBlock = true
|
||||
|
||||
what := c.Val()
|
||||
if !c.NextArg() {
|
||||
return hadBlock, c.ArgErr()
|
||||
}
|
||||
where := c.Val()
|
||||
|
||||
if what == "log" {
|
||||
if where == "visible" {
|
||||
handler.Debug = true
|
||||
} else {
|
||||
handler.LogFile = where
|
||||
if c.NextArg() {
|
||||
if c.Val() == "{" {
|
||||
c.IncrNest()
|
||||
logRoller, err := httpserver.ParseRoller(c)
|
||||
if err != nil {
|
||||
return hadBlock, err
|
||||
}
|
||||
handler.LogRoller = logRoller
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Error page; ensure it exists
|
||||
if !filepath.IsAbs(where) {
|
||||
where = filepath.Join(cfg.Root, where)
|
||||
}
|
||||
f, err := os.Open(where)
|
||||
if err != nil {
|
||||
log.Printf("[WARNING] Unable to open error page '%s': %v", where, err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
if what == "*" {
|
||||
if handler.GenericErrorPage != "" {
|
||||
return hadBlock, c.Errf("Duplicate status code entry: %s", what)
|
||||
}
|
||||
handler.GenericErrorPage = where
|
||||
} else {
|
||||
whatInt, err := strconv.Atoi(what)
|
||||
if err != nil {
|
||||
return hadBlock, c.Err("Expecting a numeric status code or '*', got '" + what + "'")
|
||||
}
|
||||
|
||||
if _, exists := handler.ErrorPages[whatInt]; exists {
|
||||
return hadBlock, c.Errf("Duplicate status code entry: %s", what)
|
||||
}
|
||||
|
||||
handler.ErrorPages[whatInt] = where
|
||||
}
|
||||
}
|
||||
}
|
||||
return hadBlock, nil
|
||||
}
|
||||
|
||||
for c.Next() {
|
||||
// weird hack to avoid having the handler values overwritten.
|
||||
if c.Val() == "}" {
|
||||
continue
|
||||
}
|
||||
// Configuration may be in a block
|
||||
hadBlock, err := optionalBlock()
|
||||
if err != nil {
|
||||
return handler, err
|
||||
}
|
||||
|
||||
// Otherwise, the only argument would be an error log file name or 'visible'
|
||||
if !hadBlock {
|
||||
if c.NextArg() {
|
||||
if c.Val() == "visible" {
|
||||
handler.Debug = true
|
||||
} else {
|
||||
handler.LogFile = c.Val()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return handler, nil
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `errors`)
|
||||
err := setup(c)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no errors, got: %v", err)
|
||||
}
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
if len(mids) == 0 {
|
||||
t.Fatal("Expected middlewares, was nil instead")
|
||||
}
|
||||
|
||||
handler := mids[0](httpserver.EmptyNext)
|
||||
myHandler, ok := handler.(*ErrorHandler)
|
||||
if !ok {
|
||||
t.Fatalf("Expected handler to be type ErrorHandler, got: %#v", handler)
|
||||
}
|
||||
|
||||
if myHandler.LogFile != "" {
|
||||
t.Errorf("Expected '%s' as the default LogFile", "")
|
||||
}
|
||||
if myHandler.LogRoller != nil {
|
||||
t.Errorf("Expected LogRoller to be nil, got: %v", *myHandler.LogRoller)
|
||||
}
|
||||
if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
|
||||
t.Error("'Next' field of handler was not set properly")
|
||||
}
|
||||
|
||||
// Test Startup function -- TODO
|
||||
// if len(c.Startup) == 0 {
|
||||
// t.Fatal("Expected 1 startup function, had 0")
|
||||
// }
|
||||
// c.Startup[0]()
|
||||
// if myHandler.Log == nil {
|
||||
// t.Error("Expected Log to be non-nil after startup because Debug is not enabled")
|
||||
// }
|
||||
}
|
||||
|
||||
func TestErrorsParse(t *testing.T) {
|
||||
testAbs, err := filepath.Abs("./404.html")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
tests := []struct {
|
||||
inputErrorsRules string
|
||||
shouldErr bool
|
||||
expectedErrorHandler ErrorHandler
|
||||
}{
|
||||
{`errors`, false, ErrorHandler{
|
||||
ErrorPages: map[int]string{},
|
||||
}},
|
||||
{`errors errors.txt`, false, ErrorHandler{
|
||||
ErrorPages: map[int]string{},
|
||||
LogFile: "errors.txt",
|
||||
}},
|
||||
{`errors visible`, false, ErrorHandler{
|
||||
ErrorPages: map[int]string{},
|
||||
Debug: true,
|
||||
}},
|
||||
{`errors { log visible }`, false, ErrorHandler{
|
||||
ErrorPages: map[int]string{},
|
||||
Debug: true,
|
||||
}},
|
||||
{`errors { log errors.txt
|
||||
404 404.html
|
||||
500 500.html
|
||||
}`, false, ErrorHandler{
|
||||
LogFile: "errors.txt",
|
||||
ErrorPages: map[int]string{
|
||||
404: "404.html",
|
||||
500: "500.html",
|
||||
},
|
||||
}},
|
||||
{`errors { log errors.txt { size 2 age 10 keep 3 } }`, false, ErrorHandler{
|
||||
LogFile: "errors.txt",
|
||||
LogRoller: &httpserver.LogRoller{
|
||||
MaxSize: 2,
|
||||
MaxAge: 10,
|
||||
MaxBackups: 3,
|
||||
LocalTime: true,
|
||||
},
|
||||
ErrorPages: map[int]string{},
|
||||
}},
|
||||
{`errors { log errors.txt {
|
||||
size 3
|
||||
age 11
|
||||
keep 5
|
||||
}
|
||||
404 404.html
|
||||
503 503.html
|
||||
}`, false, ErrorHandler{
|
||||
LogFile: "errors.txt",
|
||||
ErrorPages: map[int]string{
|
||||
404: "404.html",
|
||||
503: "503.html",
|
||||
},
|
||||
LogRoller: &httpserver.LogRoller{
|
||||
MaxSize: 3,
|
||||
MaxAge: 11,
|
||||
MaxBackups: 5,
|
||||
LocalTime: true,
|
||||
},
|
||||
}},
|
||||
{`errors { log errors.txt
|
||||
* generic_error.html
|
||||
404 404.html
|
||||
503 503.html
|
||||
}`, false, ErrorHandler{
|
||||
LogFile: "errors.txt",
|
||||
GenericErrorPage: "generic_error.html",
|
||||
ErrorPages: map[int]string{
|
||||
404: "404.html",
|
||||
503: "503.html",
|
||||
},
|
||||
}},
|
||||
// test absolute file path
|
||||
{`errors {
|
||||
404 ` + testAbs + `
|
||||
}`,
|
||||
false, ErrorHandler{
|
||||
ErrorPages: map[int]string{
|
||||
404: testAbs,
|
||||
},
|
||||
}},
|
||||
// Next two test cases is the detection of duplicate status codes
|
||||
{`errors {
|
||||
503 503.html
|
||||
503 503.html
|
||||
}`, true, ErrorHandler{ErrorPages: map[int]string{}}},
|
||||
{`errors {
|
||||
* generic_error.html
|
||||
* generic_error.html
|
||||
}`, true, ErrorHandler{ErrorPages: map[int]string{}}},
|
||||
}
|
||||
for i, test := range tests {
|
||||
actualErrorsRule, err := errorsParse(caddy.NewTestController("http", test.inputErrorsRules))
|
||||
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d didn't error, but it should have", i)
|
||||
} else if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
|
||||
} else if err != nil && test.shouldErr {
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(actualErrorsRule, &test.expectedErrorHandler) {
|
||||
t.Errorf("Test %d expect %v, but got %v", i,
|
||||
actualErrorsRule, test.expectedErrorHandler)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package expvar
|
||||
|
||||
import (
|
||||
"expvar"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// ExpVar is a simple struct to hold expvar's configuration
|
||||
type ExpVar struct {
|
||||
Next httpserver.Handler
|
||||
Resource Resource
|
||||
}
|
||||
|
||||
// ServeHTTP handles requests to expvar's configured entry point with
|
||||
// expvar, or passes all other requests up the chain.
|
||||
func (e ExpVar) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if httpserver.Path(r.URL.Path).Matches(string(e.Resource)) {
|
||||
expvarHandler(w, r)
|
||||
return 0, nil
|
||||
}
|
||||
return e.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// expvarHandler returns a JSON object will all the published variables.
|
||||
//
|
||||
// This is lifted straight from the expvar package.
|
||||
func expvarHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
fmt.Fprintf(w, "{\n")
|
||||
first := true
|
||||
expvar.Do(func(kv expvar.KeyValue) {
|
||||
if !first {
|
||||
fmt.Fprintf(w, ",\n")
|
||||
}
|
||||
first = false
|
||||
fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
|
||||
})
|
||||
fmt.Fprintf(w, "\n}\n")
|
||||
}
|
||||
|
||||
// Resource contains the path to the expvar entry point
|
||||
type Resource string
|
||||
@@ -0,0 +1,46 @@
|
||||
package expvar
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestExpVar(t *testing.T) {
|
||||
rw := ExpVar{
|
||||
Next: httpserver.HandlerFunc(contentHandler),
|
||||
Resource: "/d/v",
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
from string
|
||||
result int
|
||||
}{
|
||||
{"/d/v", 0},
|
||||
{"/x/y", http.StatusOK},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
req, err := http.NewRequest("GET", test.from, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Could not create HTTP request %v", i, err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
result, err := rw.ServeHTTP(rec, req)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Could not ServeHTTP %v", i, err)
|
||||
}
|
||||
if result != test.result {
|
||||
t.Errorf("Test %d: Expected Header '%d' but was '%d'",
|
||||
i, test.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func contentHandler(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
fmt.Fprintf(w, r.URL.String())
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package expvar
|
||||
|
||||
import (
|
||||
"expvar"
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("expvar", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
// setup configures a new ExpVar middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
resource, err := expVarParse(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// publish any extra information/metrics we may want to capture
|
||||
publishExtraVars()
|
||||
|
||||
ev := ExpVar{Resource: resource}
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
ev.Next = next
|
||||
return ev
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func expVarParse(c *caddy.Controller) (Resource, error) {
|
||||
var resource Resource
|
||||
var err error
|
||||
|
||||
for c.Next() {
|
||||
args := c.RemainingArgs()
|
||||
switch len(args) {
|
||||
case 0:
|
||||
resource = Resource(defaultExpvarPath)
|
||||
case 1:
|
||||
resource = Resource(args[0])
|
||||
default:
|
||||
return resource, c.ArgErr()
|
||||
}
|
||||
}
|
||||
|
||||
return resource, err
|
||||
}
|
||||
|
||||
func publishExtraVars() {
|
||||
// By using sync.Once instead of an init() function, we don't clutter
|
||||
// the app's expvar export unnecessarily, or risk colliding with it.
|
||||
publishOnce.Do(func() {
|
||||
expvar.Publish("Goroutines", expvar.Func(func() interface{} {
|
||||
return runtime.NumGoroutine()
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
var publishOnce sync.Once // publishing variables should only be done once
|
||||
var defaultExpvarPath = "/debug/vars"
|
||||
@@ -0,0 +1,42 @@
|
||||
package expvar
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `expvar`)
|
||||
err := setup(c)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no errors, got: %v", err)
|
||||
}
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
if len(mids) == 0 {
|
||||
t.Fatal("Expected middleware, got 0 instead")
|
||||
}
|
||||
|
||||
c = caddy.NewTestController("http", `expvar /d/v`)
|
||||
err = setup(c)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no errors, got: %v", err)
|
||||
}
|
||||
mids = httpserver.GetConfig(c).Middleware()
|
||||
if len(mids) == 0 {
|
||||
t.Fatal("Expected middleware, got 0 instead")
|
||||
}
|
||||
|
||||
handler := mids[0](httpserver.EmptyNext)
|
||||
myHandler, ok := handler.(ExpVar)
|
||||
if !ok {
|
||||
t.Fatalf("Expected handler to be type ExpVar, got: %#v", handler)
|
||||
}
|
||||
if myHandler.Resource != "/d/v" {
|
||||
t.Errorf("Expected /d/v as expvar resource")
|
||||
}
|
||||
if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
|
||||
t.Error("'Next' field of handler was not set properly")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Package extensions contains middleware for clean URLs.
|
||||
//
|
||||
// The root path of the site is passed in as well as possible extensions
|
||||
// to try internally for paths requested that don't match an existing
|
||||
// resource. The first path+ext combination that matches a valid file
|
||||
// will be used.
|
||||
package extensions
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// Ext can assume an extension from clean URLs.
|
||||
// It tries extensions in the order listed in Extensions.
|
||||
type Ext struct {
|
||||
// Next handler in the chain
|
||||
Next httpserver.Handler
|
||||
|
||||
// Path to site root
|
||||
Root string
|
||||
|
||||
// List of extensions to try
|
||||
Extensions []string
|
||||
}
|
||||
|
||||
// ServeHTTP implements the httpserver.Handler interface.
|
||||
func (e Ext) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
urlpath := strings.TrimSuffix(r.URL.Path, "/")
|
||||
if path.Ext(urlpath) == "" && len(r.URL.Path) > 0 && r.URL.Path[len(r.URL.Path)-1] != '/' {
|
||||
for _, ext := range e.Extensions {
|
||||
if resourceExists(e.Root, urlpath+ext) {
|
||||
r.URL.Path = urlpath + ext
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return e.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// resourceExists returns true if the file specified at
|
||||
// root + path exists; false otherwise.
|
||||
func resourceExists(root, path string) bool {
|
||||
_, err := os.Stat(root + path)
|
||||
// technically we should use os.IsNotExist(err)
|
||||
// but we don't handle any other kinds of errors anyway
|
||||
return err == nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package extensions
|
||||
|
||||
import (
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("ext", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
// setup configures a new instance of 'extensions' middleware for clean URLs.
|
||||
func setup(c *caddy.Controller) error {
|
||||
cfg := httpserver.GetConfig(c)
|
||||
root := cfg.Root
|
||||
|
||||
exts, err := extParse(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
return Ext{
|
||||
Next: next,
|
||||
Extensions: exts,
|
||||
Root: root,
|
||||
}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extParse sets up an instance of extension middleware
|
||||
// from a middleware controller and returns a list of extensions.
|
||||
func extParse(c *caddy.Controller) ([]string, error) {
|
||||
var exts []string
|
||||
|
||||
for c.Next() {
|
||||
// At least one extension is required
|
||||
if !c.NextArg() {
|
||||
return exts, c.ArgErr()
|
||||
}
|
||||
exts = append(exts, c.Val())
|
||||
|
||||
// Tack on any other extensions that may have been listed
|
||||
exts = append(exts, c.RemainingArgs()...)
|
||||
}
|
||||
|
||||
return exts, nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package extensions
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `ext .html .htm .php`)
|
||||
err := setup(c)
|
||||
if err != nil {
|
||||
t.Fatalf("Expected no errors, got: %v", err)
|
||||
}
|
||||
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
if len(mids) == 0 {
|
||||
t.Fatal("Expected middleware, had 0 instead")
|
||||
}
|
||||
|
||||
handler := mids[0](httpserver.EmptyNext)
|
||||
myHandler, ok := handler.(Ext)
|
||||
|
||||
if !ok {
|
||||
t.Fatalf("Expected handler to be type Ext, got: %#v", handler)
|
||||
}
|
||||
|
||||
if myHandler.Extensions[0] != ".html" {
|
||||
t.Errorf("Expected .html in the list of Extensions")
|
||||
}
|
||||
if myHandler.Extensions[1] != ".htm" {
|
||||
t.Errorf("Expected .htm in the list of Extensions")
|
||||
}
|
||||
if myHandler.Extensions[2] != ".php" {
|
||||
t.Errorf("Expected .php in the list of Extensions")
|
||||
}
|
||||
if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
|
||||
t.Error("'Next' field of handler was not set properly")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestExtParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
inputExts string
|
||||
shouldErr bool
|
||||
expectedExts []string
|
||||
}{
|
||||
{`ext .html .htm .php`, false, []string{".html", ".htm", ".php"}},
|
||||
{`ext .php .html .xml`, false, []string{".php", ".html", ".xml"}},
|
||||
{`ext .txt .php .xml`, false, []string{".txt", ".php", ".xml"}},
|
||||
}
|
||||
for i, test := range tests {
|
||||
actualExts, err := extParse(caddy.NewTestController("http", test.inputExts))
|
||||
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d didn't error, but it should have", i)
|
||||
} else if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
|
||||
}
|
||||
|
||||
if len(actualExts) != len(test.expectedExts) {
|
||||
t.Fatalf("Test %d expected %d rules, but got %d",
|
||||
i, len(test.expectedExts), len(actualExts))
|
||||
}
|
||||
for j, actualExt := range actualExts {
|
||||
if actualExt != test.expectedExts[j] {
|
||||
t.Fatalf("Test %d expected %dth extension to be %s , but got %s",
|
||||
i, j, test.expectedExts[j], actualExt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package fastcgi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dialer interface {
|
||||
Dial() (Client, error)
|
||||
Close(Client) error
|
||||
}
|
||||
|
||||
// basicDialer is a basic dialer that wraps default fcgi functions.
|
||||
type basicDialer struct {
|
||||
network string
|
||||
address string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func (b basicDialer) Dial() (Client, error) {
|
||||
return DialTimeout(b.network, b.address, b.timeout)
|
||||
}
|
||||
|
||||
func (b basicDialer) Close(c Client) error { return c.Close() }
|
||||
|
||||
// persistentDialer keeps a pool of fcgi connections.
|
||||
// connections are not closed after use, rather added back to the pool for reuse.
|
||||
type persistentDialer struct {
|
||||
size int
|
||||
network string
|
||||
address string
|
||||
timeout time.Duration
|
||||
pool []Client
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (p *persistentDialer) Dial() (Client, error) {
|
||||
p.Lock()
|
||||
// connection is available, return first one.
|
||||
if len(p.pool) > 0 {
|
||||
client := p.pool[0]
|
||||
p.pool = p.pool[1:]
|
||||
p.Unlock()
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
p.Unlock()
|
||||
|
||||
// no connection available, create new one
|
||||
return DialTimeout(p.network, p.address, p.timeout)
|
||||
}
|
||||
|
||||
func (p *persistentDialer) Close(client Client) error {
|
||||
p.Lock()
|
||||
if len(p.pool) < p.size {
|
||||
// pool is not full yet, add connection for reuse
|
||||
p.pool = append(p.pool, client)
|
||||
p.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
p.Unlock()
|
||||
|
||||
// otherwise, close the connection.
|
||||
return client.Close()
|
||||
}
|
||||
|
||||
type loadBalancingDialer struct {
|
||||
dialers []dialer
|
||||
current int64
|
||||
}
|
||||
|
||||
func (m *loadBalancingDialer) Dial() (Client, error) {
|
||||
nextDialerIndex := atomic.AddInt64(&m.current, 1) % int64(len(m.dialers))
|
||||
currentDialer := m.dialers[nextDialerIndex]
|
||||
|
||||
client, err := currentDialer.Dial()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dialerAwareClient{Client: client, dialer: currentDialer}, nil
|
||||
}
|
||||
|
||||
func (m *loadBalancingDialer) Close(c Client) error {
|
||||
// Close the client according to dialer behaviour
|
||||
if da, ok := c.(*dialerAwareClient); ok {
|
||||
return da.dialer.Close(c)
|
||||
}
|
||||
|
||||
return errors.New("Cannot close client")
|
||||
}
|
||||
|
||||
type dialerAwareClient struct {
|
||||
Client
|
||||
dialer dialer
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package fastcgi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadbalancingDialer(t *testing.T) {
|
||||
// given
|
||||
runs := 100
|
||||
mockDialer1 := new(mockDialer)
|
||||
mockDialer2 := new(mockDialer)
|
||||
|
||||
dialer := &loadBalancingDialer{dialers: []dialer{mockDialer1, mockDialer2}}
|
||||
|
||||
// when
|
||||
for i := 0; i < runs; i++ {
|
||||
client, err := dialer.Dial()
|
||||
dialer.Close(client)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Expected error to be nil")
|
||||
}
|
||||
}
|
||||
|
||||
// then
|
||||
if mockDialer1.dialCalled != mockDialer2.dialCalled && mockDialer1.dialCalled != 50 {
|
||||
t.Errorf("Expected dialer to call Dial() on multiple backend dialers %d times [actual: %d, %d]", 50, mockDialer1.dialCalled, mockDialer2.dialCalled)
|
||||
}
|
||||
|
||||
if mockDialer1.closeCalled != mockDialer2.closeCalled && mockDialer1.closeCalled != 50 {
|
||||
t.Errorf("Expected dialer to call Close() on multiple backend dialers %d times [actual: %d, %d]", 50, mockDialer1.closeCalled, mockDialer2.closeCalled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBalancingDialerShouldReturnDialerAwareClient(t *testing.T) {
|
||||
// given
|
||||
mockDialer1 := new(mockDialer)
|
||||
dialer := &loadBalancingDialer{dialers: []dialer{mockDialer1}}
|
||||
|
||||
// when
|
||||
client, err := dialer.Dial()
|
||||
|
||||
// then
|
||||
if err != nil {
|
||||
t.Errorf("Expected error to be nil")
|
||||
}
|
||||
|
||||
if awareClient, ok := client.(*dialerAwareClient); !ok {
|
||||
t.Error("Expected dialer to wrap client")
|
||||
} else {
|
||||
if awareClient.dialer != mockDialer1 {
|
||||
t.Error("Expected wrapped client to have reference to dialer")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBalancingDialerShouldUnderlyingReturnDialerError(t *testing.T) {
|
||||
// given
|
||||
mockDialer1 := new(errorReturningDialer)
|
||||
dialer := &loadBalancingDialer{dialers: []dialer{mockDialer1}}
|
||||
|
||||
// when
|
||||
_, err := dialer.Dial()
|
||||
|
||||
// then
|
||||
if err.Error() != "Error during dial" {
|
||||
t.Errorf("Expected 'Error during dial', got: '%s'", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBalancingDialerShouldCloseClient(t *testing.T) {
|
||||
// given
|
||||
mockDialer1 := new(mockDialer)
|
||||
mockDialer2 := new(mockDialer)
|
||||
|
||||
dialer := &loadBalancingDialer{dialers: []dialer{mockDialer1, mockDialer2}}
|
||||
client, _ := dialer.Dial()
|
||||
|
||||
// when
|
||||
err := dialer.Close(client)
|
||||
|
||||
// then
|
||||
if err != nil {
|
||||
t.Error("Expected error not to occur")
|
||||
}
|
||||
|
||||
// load balancing starts from index 1
|
||||
if mockDialer2.client != client {
|
||||
t.Errorf("Expected Close() to be called on referenced dialer")
|
||||
}
|
||||
}
|
||||
|
||||
type mockDialer struct {
|
||||
dialCalled int
|
||||
closeCalled int
|
||||
client Client
|
||||
}
|
||||
|
||||
type mockClient struct {
|
||||
Client
|
||||
}
|
||||
|
||||
func (m *mockDialer) Dial() (Client, error) {
|
||||
m.dialCalled++
|
||||
return mockClient{Client: &FCGIClient{}}, nil
|
||||
}
|
||||
|
||||
func (m *mockDialer) Close(c Client) error {
|
||||
m.client = c
|
||||
m.closeCalled++
|
||||
return nil
|
||||
}
|
||||
|
||||
type errorReturningDialer struct {
|
||||
client Client
|
||||
}
|
||||
|
||||
func (m *errorReturningDialer) Dial() (Client, error) {
|
||||
return mockClient{Client: &FCGIClient{}}, errors.New("Error during dial")
|
||||
}
|
||||
|
||||
func (m *errorReturningDialer) Close(c Client) error {
|
||||
m.client = c
|
||||
return errors.New("Error during close")
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
// Package fastcgi has middleware that acts as a FastCGI client. Requests
|
||||
// that get forwarded to FastCGI stop the middleware execution chain.
|
||||
// The most common use for this package is to serve PHP websites via php-fpm.
|
||||
package fastcgi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// Handler is a middleware type that can handle requests as a FastCGI client.
|
||||
type Handler struct {
|
||||
Next httpserver.Handler
|
||||
Rules []Rule
|
||||
Root string
|
||||
AbsRoot string // same as root, but absolute path
|
||||
FileSys http.FileSystem
|
||||
|
||||
// These are sent to CGI scripts in env variables
|
||||
SoftwareName string
|
||||
SoftwareVersion string
|
||||
ServerName string
|
||||
ServerPort string
|
||||
}
|
||||
|
||||
// When a rewrite is performed, a header field of this name
|
||||
// is added to the request
|
||||
// It contains the original request URI before the rewrite.
|
||||
const internalRewriteFieldName = "Caddy-Rewrite-Original-URI"
|
||||
|
||||
// ServeHTTP satisfies the httpserver.Handler interface.
|
||||
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
for _, rule := range h.Rules {
|
||||
|
||||
// First requirement: Base path must match and the path must be allowed.
|
||||
if !httpserver.Path(r.URL.Path).Matches(rule.Path) || !rule.AllowedPath(r.URL.Path) {
|
||||
continue
|
||||
}
|
||||
|
||||
// In addition to matching the path, a request must meet some
|
||||
// other criteria before being proxied as FastCGI. For example,
|
||||
// we probably want to exclude static assets (CSS, JS, images...)
|
||||
// but we also want to be flexible for the script we proxy to.
|
||||
|
||||
fpath := r.URL.Path
|
||||
|
||||
if idx, ok := httpserver.IndexFile(h.FileSys, fpath, rule.IndexFiles); ok {
|
||||
fpath = idx
|
||||
// Index file present.
|
||||
// If request path cannot be split, return error.
|
||||
if !rule.canSplit(fpath) {
|
||||
return http.StatusInternalServerError, ErrIndexMissingSplit
|
||||
}
|
||||
} else {
|
||||
// No index file present.
|
||||
// If request path cannot be split, ignore request.
|
||||
if !rule.canSplit(fpath) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// These criteria work well in this order for PHP sites
|
||||
if !h.exists(fpath) || fpath[len(fpath)-1] == '/' || strings.HasSuffix(fpath, rule.Ext) {
|
||||
|
||||
// Create environment for CGI script
|
||||
env, err := h.buildEnv(r, rule, fpath)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// Connect to FastCGI gateway
|
||||
fcgiBackend, err := rule.dialer.Dial()
|
||||
if err != nil {
|
||||
if err, ok := err.(net.Error); ok && err.Timeout() {
|
||||
return http.StatusGatewayTimeout, err
|
||||
}
|
||||
return http.StatusBadGateway, err
|
||||
}
|
||||
defer fcgiBackend.Close()
|
||||
fcgiBackend.SetReadTimeout(rule.ReadTimeout)
|
||||
fcgiBackend.SetSendTimeout(rule.SendTimeout)
|
||||
|
||||
var resp *http.Response
|
||||
contentLength, _ := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
switch r.Method {
|
||||
case "HEAD":
|
||||
resp, err = fcgiBackend.Head(env)
|
||||
case "GET":
|
||||
resp, err = fcgiBackend.Get(env)
|
||||
case "OPTIONS":
|
||||
resp, err = fcgiBackend.Options(env)
|
||||
default:
|
||||
resp, err = fcgiBackend.Post(env, r.Method, r.Header.Get("Content-Type"), r.Body, contentLength)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if err, ok := err.(net.Error); ok && err.Timeout() {
|
||||
return http.StatusGatewayTimeout, err
|
||||
} else if err != io.EOF {
|
||||
return http.StatusBadGateway, err
|
||||
}
|
||||
}
|
||||
|
||||
// Write response header
|
||||
writeHeader(w, resp)
|
||||
|
||||
// Write the response body
|
||||
_, err = io.Copy(w, resp.Body)
|
||||
if err != nil {
|
||||
return http.StatusBadGateway, err
|
||||
}
|
||||
|
||||
// Log any stderr output from upstream
|
||||
if stderr := fcgiBackend.StdErr(); stderr.Len() != 0 {
|
||||
// Remove trailing newline, error logger already does this.
|
||||
err = LogError(strings.TrimSuffix(stderr.String(), "\n"))
|
||||
}
|
||||
|
||||
// Normally we would return the status code if it is an error status (>= 400),
|
||||
// however, upstream FastCGI apps don't know about our contract and have
|
||||
// probably already written an error page. So we just return 0, indicating
|
||||
// that the response body is already written. However, we do return any
|
||||
// error value so it can be logged.
|
||||
// Note that the proxy middleware works the same way, returning status=0.
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
return h.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// parseAddress returns the network and address of fcgiAddress.
|
||||
// The first string is the network, "tcp" or "unix", implied from the scheme and address.
|
||||
// The second string is fcgiAddress, with scheme prefixes removed.
|
||||
// The two returned strings can be used as parameters to the Dial() function.
|
||||
func parseAddress(fcgiAddress string) (string, string) {
|
||||
// check if address has tcp scheme explicitly set
|
||||
if strings.HasPrefix(fcgiAddress, "tcp://") {
|
||||
return "tcp", fcgiAddress[len("tcp://"):]
|
||||
}
|
||||
// check if address has fastcgi scheme explicitly set
|
||||
if strings.HasPrefix(fcgiAddress, "fastcgi://") {
|
||||
return "tcp", fcgiAddress[len("fastcgi://"):]
|
||||
}
|
||||
// check if unix socket
|
||||
if trim := strings.HasPrefix(fcgiAddress, "unix"); strings.HasPrefix(fcgiAddress, "/") || trim {
|
||||
if trim {
|
||||
return "unix", fcgiAddress[len("unix:"):]
|
||||
}
|
||||
return "unix", fcgiAddress
|
||||
}
|
||||
// default case, a plain tcp address with no scheme
|
||||
return "tcp", fcgiAddress
|
||||
}
|
||||
|
||||
func writeHeader(w http.ResponseWriter, r *http.Response) {
|
||||
for key, vals := range r.Header {
|
||||
for _, val := range vals {
|
||||
w.Header().Add(key, val)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(r.StatusCode)
|
||||
}
|
||||
|
||||
func (h Handler) exists(path string) bool {
|
||||
if _, err := os.Stat(h.Root + path); err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// buildEnv returns a set of CGI environment variables for the request.
|
||||
func (h Handler) buildEnv(r *http.Request, rule Rule, fpath string) (map[string]string, error) {
|
||||
var env map[string]string
|
||||
|
||||
// Get absolute path of requested resource
|
||||
absPath := filepath.Join(h.AbsRoot, fpath)
|
||||
|
||||
// Separate remote IP and port; more lenient than net.SplitHostPort
|
||||
var ip, port string
|
||||
if idx := strings.LastIndex(r.RemoteAddr, ":"); idx > -1 {
|
||||
ip = r.RemoteAddr[:idx]
|
||||
port = r.RemoteAddr[idx+1:]
|
||||
} else {
|
||||
ip = r.RemoteAddr
|
||||
}
|
||||
|
||||
// Remove [] from IPv6 addresses
|
||||
ip = strings.Replace(ip, "[", "", 1)
|
||||
ip = strings.Replace(ip, "]", "", 1)
|
||||
|
||||
// Split path in preparation for env variables.
|
||||
// Previous rule.canSplit checks ensure this can never be -1.
|
||||
splitPos := rule.splitPos(fpath)
|
||||
|
||||
// Request has the extension; path was split successfully
|
||||
docURI := fpath[:splitPos+len(rule.SplitPath)]
|
||||
pathInfo := fpath[splitPos+len(rule.SplitPath):]
|
||||
scriptName := fpath
|
||||
scriptFilename := absPath
|
||||
|
||||
// Strip PATH_INFO from SCRIPT_NAME
|
||||
scriptName = strings.TrimSuffix(scriptName, pathInfo)
|
||||
|
||||
// Get the request URI. The request URI might be as it came in over the wire,
|
||||
// or it might have been rewritten internally by the rewrite middleware (see issue #256).
|
||||
// If it was rewritten, there will be a header indicating the original URL,
|
||||
// which is needed to get the correct RequestURI value for PHP apps.
|
||||
reqURI := r.URL.RequestURI()
|
||||
if origURI := r.Header.Get(internalRewriteFieldName); origURI != "" {
|
||||
reqURI = origURI
|
||||
}
|
||||
|
||||
// Some variables are unused but cleared explicitly to prevent
|
||||
// the parent environment from interfering.
|
||||
env = map[string]string{
|
||||
|
||||
// Variables defined in CGI 1.1 spec
|
||||
"AUTH_TYPE": "", // Not used
|
||||
"CONTENT_LENGTH": r.Header.Get("Content-Length"),
|
||||
"CONTENT_TYPE": r.Header.Get("Content-Type"),
|
||||
"GATEWAY_INTERFACE": "CGI/1.1",
|
||||
"PATH_INFO": pathInfo,
|
||||
"QUERY_STRING": r.URL.RawQuery,
|
||||
"REMOTE_ADDR": ip,
|
||||
"REMOTE_HOST": ip, // For speed, remote host lookups disabled
|
||||
"REMOTE_PORT": port,
|
||||
"REMOTE_IDENT": "", // Not used
|
||||
"REMOTE_USER": "", // Not used
|
||||
"REQUEST_METHOD": r.Method,
|
||||
"SERVER_NAME": h.ServerName,
|
||||
"SERVER_PORT": h.ServerPort,
|
||||
"SERVER_PROTOCOL": r.Proto,
|
||||
"SERVER_SOFTWARE": h.SoftwareName + "/" + h.SoftwareVersion,
|
||||
|
||||
// Other variables
|
||||
"DOCUMENT_ROOT": h.AbsRoot,
|
||||
"DOCUMENT_URI": docURI,
|
||||
"HTTP_HOST": r.Host, // added here, since not always part of headers
|
||||
"REQUEST_URI": reqURI,
|
||||
"SCRIPT_FILENAME": scriptFilename,
|
||||
"SCRIPT_NAME": scriptName,
|
||||
}
|
||||
|
||||
// compliance with the CGI specification that PATH_TRANSLATED
|
||||
// should only exist if PATH_INFO is defined.
|
||||
// Info: https://www.ietf.org/rfc/rfc3875 Page 14
|
||||
if env["PATH_INFO"] != "" {
|
||||
env["PATH_TRANSLATED"] = filepath.Join(h.AbsRoot, pathInfo) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
|
||||
}
|
||||
|
||||
// Some web apps rely on knowing HTTPS or not
|
||||
if r.TLS != nil {
|
||||
env["HTTPS"] = "on"
|
||||
}
|
||||
|
||||
replacer := httpserver.NewReplacer(r, nil, "")
|
||||
// Add env variables from config
|
||||
for _, envVar := range rule.EnvVars {
|
||||
// replace request placeholders in environment variables
|
||||
env[envVar[0]] = replacer.Replace(envVar[1])
|
||||
}
|
||||
|
||||
// Add all HTTP headers (except Caddy-Rewrite-Original-URI ) to env variables
|
||||
for field, val := range r.Header {
|
||||
if strings.ToLower(field) == strings.ToLower(internalRewriteFieldName) {
|
||||
continue
|
||||
}
|
||||
header := strings.ToUpper(field)
|
||||
header = headerNameReplacer.Replace(header)
|
||||
env["HTTP_"+header] = strings.Join(val, ", ")
|
||||
}
|
||||
return env, nil
|
||||
}
|
||||
|
||||
// Rule represents a FastCGI handling rule.
|
||||
// It is parsed from the fastcgi directive in the Caddyfile, see setup.go.
|
||||
type Rule struct {
|
||||
// The base path to match. Required.
|
||||
Path string
|
||||
|
||||
// The address of the FastCGI server. Required.
|
||||
Address string
|
||||
|
||||
// Always process files with this extension with fastcgi.
|
||||
Ext string
|
||||
|
||||
// The path in the URL will be split into two, with the first piece ending
|
||||
// with the value of SplitPath. The first piece will be assumed as the
|
||||
// actual resource (CGI script) name, and the second piece will be set to
|
||||
// PATH_INFO for the CGI script to use.
|
||||
SplitPath string
|
||||
|
||||
// If the URL ends with '/' (which indicates a directory), these index
|
||||
// files will be tried instead.
|
||||
IndexFiles []string
|
||||
|
||||
// Environment Variables
|
||||
EnvVars [][2]string
|
||||
|
||||
// Ignored paths
|
||||
IgnoredSubPaths []string
|
||||
|
||||
// The duration used to set a deadline when reading from the FastCGI server.
|
||||
ReadTimeout time.Duration
|
||||
|
||||
// The duration used to set a deadline when sending to the FastCGI server.
|
||||
SendTimeout time.Duration
|
||||
|
||||
// FCGI dialer
|
||||
dialer dialer
|
||||
}
|
||||
|
||||
// canSplit checks if path can split into two based on rule.SplitPath.
|
||||
func (r Rule) canSplit(path string) bool {
|
||||
return r.splitPos(path) >= 0
|
||||
}
|
||||
|
||||
// splitPos returns the index where path should be split
|
||||
// based on rule.SplitPath.
|
||||
func (r Rule) splitPos(path string) int {
|
||||
if httpserver.CaseSensitivePath {
|
||||
return strings.Index(path, r.SplitPath)
|
||||
}
|
||||
return strings.Index(strings.ToLower(path), strings.ToLower(r.SplitPath))
|
||||
}
|
||||
|
||||
// AllowedPath checks if requestPath is not an ignored path.
|
||||
func (r Rule) AllowedPath(requestPath string) bool {
|
||||
for _, ignoredSubPath := range r.IgnoredSubPaths {
|
||||
if httpserver.Path(path.Clean(requestPath)).Matches(path.Join(r.Path, ignoredSubPath)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var (
|
||||
headerNameReplacer = strings.NewReplacer(" ", "_", "-", "_")
|
||||
// ErrIndexMissingSplit describes an index configuration error.
|
||||
ErrIndexMissingSplit = errors.New("configured index file(s) must include split value")
|
||||
)
|
||||
|
||||
// LogError is a non fatal error that allows requests to go through.
|
||||
type LogError string
|
||||
|
||||
// Error satisfies error interface.
|
||||
func (l LogError) Error() string {
|
||||
return string(l)
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
package fastcgi
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/fcgi"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestServeHTTP(t *testing.T) {
|
||||
body := "This is some test body content"
|
||||
|
||||
bodyLenStr := strconv.Itoa(len(body))
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to create listener for test: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
go fcgi.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", bodyLenStr)
|
||||
w.Write([]byte(body))
|
||||
}))
|
||||
|
||||
network, address := parseAddress(listener.Addr().String())
|
||||
handler := Handler{
|
||||
Next: nil,
|
||||
Rules: []Rule{
|
||||
{
|
||||
Path: "/",
|
||||
Address: listener.Addr().String(),
|
||||
dialer: basicDialer{network: network, address: address},
|
||||
},
|
||||
},
|
||||
}
|
||||
r, err := http.NewRequest("GET", "/", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to create request: %v", err)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
status, err := handler.ServeHTTP(w, r)
|
||||
|
||||
if got, want := status, 0; got != want {
|
||||
t.Errorf("Expected returned status code to be %d, got %d", want, got)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Expected nil error, got: %v", err)
|
||||
}
|
||||
if got, want := w.Header().Get("Content-Length"), bodyLenStr; got != want {
|
||||
t.Errorf("Expected Content-Length to be '%s', got: '%s'", want, got)
|
||||
}
|
||||
if got, want := w.Body.String(), body; got != want {
|
||||
t.Errorf("Expected response body to be '%s', got: '%s'", want, got)
|
||||
}
|
||||
}
|
||||
|
||||
// connectionCounter in fact is a listener with an added counter to keep track
|
||||
// of the number of accepted connections.
|
||||
type connectionCounter struct {
|
||||
net.Listener
|
||||
sync.Mutex
|
||||
counter int
|
||||
}
|
||||
|
||||
func (l *connectionCounter) Accept() (net.Conn, error) {
|
||||
l.Lock()
|
||||
l.counter++
|
||||
l.Unlock()
|
||||
return l.Listener.Accept()
|
||||
}
|
||||
|
||||
// TestPersistent ensures that persistent
|
||||
// as well as the non-persistent fastCGI servers
|
||||
// send the answers corresnponding to the correct request.
|
||||
// It also checks the number of tcp connections used.
|
||||
func TestPersistent(t *testing.T) {
|
||||
numberOfRequests := 32
|
||||
|
||||
for _, poolsize := range []int{0, 1, 5, numberOfRequests} {
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to create listener for test: %v", err)
|
||||
}
|
||||
|
||||
listener := &connectionCounter{l, *new(sync.Mutex), 0}
|
||||
|
||||
// this fcgi server replies with the request URL
|
||||
go fcgi.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body := "This answers a request to " + r.URL.Path
|
||||
bodyLenStr := strconv.Itoa(len(body))
|
||||
|
||||
w.Header().Set("Content-Length", bodyLenStr)
|
||||
w.Write([]byte(body))
|
||||
}))
|
||||
|
||||
network, address := parseAddress(listener.Addr().String())
|
||||
handler := Handler{
|
||||
Next: nil,
|
||||
Rules: []Rule{{Path: "/", Address: listener.Addr().String(), dialer: &persistentDialer{size: poolsize, network: network, address: address}}},
|
||||
}
|
||||
|
||||
var semaphore sync.WaitGroup
|
||||
serialMutex := new(sync.Mutex)
|
||||
|
||||
serialCounter := 0
|
||||
parallelCounter := 0
|
||||
// make some serial followed by some
|
||||
// parallel requests to challenge the handler
|
||||
for _, serialize := range []bool{true, false, false, false} {
|
||||
if serialize {
|
||||
serialCounter++
|
||||
} else {
|
||||
parallelCounter++
|
||||
}
|
||||
semaphore.Add(numberOfRequests)
|
||||
|
||||
for i := 0; i < numberOfRequests; i++ {
|
||||
go func(i int, serialize bool) {
|
||||
defer semaphore.Done()
|
||||
if serialize {
|
||||
serialMutex.Lock()
|
||||
defer serialMutex.Unlock()
|
||||
}
|
||||
r, err := http.NewRequest("GET", "/"+strconv.Itoa(i), nil)
|
||||
if err != nil {
|
||||
t.Errorf("Unable to create request: %v", err)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
status, err := handler.ServeHTTP(w, r)
|
||||
|
||||
if status != 0 {
|
||||
t.Errorf("Handler(pool: %v) return status %v", poolsize, status)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Handler(pool: %v) Error: %v", poolsize, err)
|
||||
}
|
||||
want := "This answers a request to /" + strconv.Itoa(i)
|
||||
if got := w.Body.String(); got != want {
|
||||
t.Errorf("Expected response from handler(pool: %v) to be '%s', got: '%s'", poolsize, want, got)
|
||||
}
|
||||
}(i, serialize)
|
||||
} //next request
|
||||
semaphore.Wait()
|
||||
} // next set of requests (serial/parallel)
|
||||
|
||||
listener.Close()
|
||||
t.Logf("The pool: %v test used %v tcp connections to answer %v * %v serial and %v * %v parallel requests.", poolsize, listener.counter, serialCounter, numberOfRequests, parallelCounter, numberOfRequests)
|
||||
} // next handler (persistent/non-persistent)
|
||||
}
|
||||
|
||||
func TestRuleParseAddress(t *testing.T) {
|
||||
getClientTestTable := []struct {
|
||||
rule *Rule
|
||||
expectednetwork string
|
||||
expectedaddress string
|
||||
}{
|
||||
{&Rule{Address: "tcp://172.17.0.1:9000"}, "tcp", "172.17.0.1:9000"},
|
||||
{&Rule{Address: "fastcgi://localhost:9000"}, "tcp", "localhost:9000"},
|
||||
{&Rule{Address: "172.17.0.15"}, "tcp", "172.17.0.15"},
|
||||
{&Rule{Address: "/my/unix/socket"}, "unix", "/my/unix/socket"},
|
||||
{&Rule{Address: "unix:/second/unix/socket"}, "unix", "/second/unix/socket"},
|
||||
}
|
||||
|
||||
for _, entry := range getClientTestTable {
|
||||
if actualnetwork, _ := parseAddress(entry.rule.Address); actualnetwork != entry.expectednetwork {
|
||||
t.Errorf("Unexpected network for address string %v. Got %v, expected %v", entry.rule.Address, actualnetwork, entry.expectednetwork)
|
||||
}
|
||||
if _, actualaddress := parseAddress(entry.rule.Address); actualaddress != entry.expectedaddress {
|
||||
t.Errorf("Unexpected parsed address for address string %v. Got %v, expected %v", entry.rule.Address, actualaddress, entry.expectedaddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuleIgnoredPath(t *testing.T) {
|
||||
rule := &Rule{
|
||||
Path: "/fastcgi",
|
||||
IgnoredSubPaths: []string{"/download", "/static"},
|
||||
}
|
||||
tests := []struct {
|
||||
url string
|
||||
expected bool
|
||||
}{
|
||||
{"/fastcgi", true},
|
||||
{"/fastcgi/dl", true},
|
||||
{"/fastcgi/download", false},
|
||||
{"/fastcgi/download/static", false},
|
||||
{"/fastcgi/static", false},
|
||||
{"/fastcgi/static/download", false},
|
||||
{"/fastcgi/something/download", true},
|
||||
{"/fastcgi/something/static", true},
|
||||
{"/fastcgi//static", false},
|
||||
{"/fastcgi//static//download", false},
|
||||
{"/fastcgi//download", false},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
allowed := rule.AllowedPath(test.url)
|
||||
if test.expected != allowed {
|
||||
t.Errorf("Test %d: expected %v found %v", i, test.expected, allowed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildEnv(t *testing.T) {
|
||||
testBuildEnv := func(r *http.Request, rule Rule, fpath string, envExpected map[string]string) {
|
||||
var h Handler
|
||||
env, err := h.buildEnv(r, rule, fpath)
|
||||
if err != nil {
|
||||
t.Error("Unexpected error:", err.Error())
|
||||
}
|
||||
for k, v := range envExpected {
|
||||
if env[k] != v {
|
||||
t.Errorf("Unexpected %v. Got %v, expected %v", k, env[k], v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rule := Rule{}
|
||||
url, err := url.Parse("http://localhost:2015/fgci_test.php?test=blabla")
|
||||
if err != nil {
|
||||
t.Error("Unexpected error:", err.Error())
|
||||
}
|
||||
|
||||
var newReq = func() *http.Request {
|
||||
return &http.Request{
|
||||
Method: "GET",
|
||||
URL: url,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Host: "localhost:2015",
|
||||
RemoteAddr: "[2b02:1810:4f2d:9400:70ab:f822:be8a:9093]:51688",
|
||||
RequestURI: "/fgci_test.php",
|
||||
Header: map[string][]string{
|
||||
"Foo": {"Bar", "two"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fpath := "/fgci_test.php"
|
||||
|
||||
var newEnv = func() map[string]string {
|
||||
return map[string]string{
|
||||
"REMOTE_ADDR": "2b02:1810:4f2d:9400:70ab:f822:be8a:9093",
|
||||
"REMOTE_PORT": "51688",
|
||||
"SERVER_PROTOCOL": "HTTP/1.1",
|
||||
"QUERY_STRING": "test=blabla",
|
||||
"REQUEST_METHOD": "GET",
|
||||
"HTTP_HOST": "localhost:2015",
|
||||
}
|
||||
}
|
||||
|
||||
// request
|
||||
var r *http.Request
|
||||
|
||||
// expected environment variables
|
||||
var envExpected map[string]string
|
||||
|
||||
// 1. Test for full canonical IPv6 address
|
||||
r = newReq()
|
||||
testBuildEnv(r, rule, fpath, envExpected)
|
||||
|
||||
// 2. Test for shorthand notation of IPv6 address
|
||||
r = newReq()
|
||||
r.RemoteAddr = "[::1]:51688"
|
||||
envExpected = newEnv()
|
||||
envExpected["REMOTE_ADDR"] = "::1"
|
||||
testBuildEnv(r, rule, fpath, envExpected)
|
||||
|
||||
// 3. Test for IPv4 address
|
||||
r = newReq()
|
||||
r.RemoteAddr = "192.168.0.10:51688"
|
||||
envExpected = newEnv()
|
||||
envExpected["REMOTE_ADDR"] = "192.168.0.10"
|
||||
testBuildEnv(r, rule, fpath, envExpected)
|
||||
|
||||
// 4. Test for environment variable
|
||||
r = newReq()
|
||||
rule.EnvVars = [][2]string{
|
||||
{"HTTP_HOST", "localhost:2016"},
|
||||
{"REQUEST_METHOD", "POST"},
|
||||
}
|
||||
envExpected = newEnv()
|
||||
envExpected["HTTP_HOST"] = "localhost:2016"
|
||||
envExpected["REQUEST_METHOD"] = "POST"
|
||||
testBuildEnv(r, rule, fpath, envExpected)
|
||||
|
||||
// 5. Test for environment variable placeholders
|
||||
r = newReq()
|
||||
rule.EnvVars = [][2]string{
|
||||
{"HTTP_HOST", "{host}"},
|
||||
{"CUSTOM_URI", "custom_uri{uri}"},
|
||||
{"CUSTOM_QUERY", "custom=true&{query}"},
|
||||
}
|
||||
envExpected = newEnv()
|
||||
envExpected["HTTP_HOST"] = "localhost:2015"
|
||||
envExpected["CUSTOM_URI"] = "custom_uri/fgci_test.php?test=blabla"
|
||||
envExpected["CUSTOM_QUERY"] = "custom=true&test=blabla"
|
||||
testBuildEnv(r, rule, fpath, envExpected)
|
||||
|
||||
// 6. Test Caddy-Rewrite-Original-URI header is not removed
|
||||
r = newReq()
|
||||
rule.EnvVars = [][2]string{
|
||||
{"HTTP_HOST", "{host}"},
|
||||
{"CUSTOM_URI", "custom_uri{uri}"},
|
||||
{"CUSTOM_QUERY", "custom=true&{query}"},
|
||||
}
|
||||
envExpected = newEnv()
|
||||
envExpected["HTTP_HOST"] = "localhost:2015"
|
||||
envExpected["CUSTOM_URI"] = "custom_uri/fgci_test.php?test=blabla"
|
||||
envExpected["CUSTOM_QUERY"] = "custom=true&test=blabla"
|
||||
httpFieldName := strings.ToUpper(internalRewriteFieldName)
|
||||
envExpected["HTTP_"+httpFieldName] = ""
|
||||
r.Header.Add(internalRewriteFieldName, "/apath/torewrite/index.php")
|
||||
testBuildEnv(r, rule, fpath, envExpected)
|
||||
if r.Header.Get(internalRewriteFieldName) == "" {
|
||||
t.Errorf("Error: Header Expected %v", internalRewriteFieldName)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestReadTimeout(t *testing.T) {
|
||||
tests := []struct {
|
||||
sleep time.Duration
|
||||
readTimeout time.Duration
|
||||
shouldErr bool
|
||||
}{
|
||||
{75 * time.Millisecond, 50 * time.Millisecond, true},
|
||||
{0, -1 * time.Second, true},
|
||||
{0, time.Minute, false},
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i, test := range tests {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Unable to create listener for test: %v", i, err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
network, address := parseAddress(listener.Addr().String())
|
||||
handler := Handler{
|
||||
Next: nil,
|
||||
Rules: []Rule{
|
||||
{
|
||||
Path: "/",
|
||||
Address: listener.Addr().String(),
|
||||
dialer: basicDialer{network: network, address: address},
|
||||
ReadTimeout: test.readTimeout,
|
||||
},
|
||||
},
|
||||
}
|
||||
r, err := http.NewRequest("GET", "/", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Unable to create request: %v", i, err)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
wg.Add(1)
|
||||
go fcgi.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(test.sleep)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
wg.Done()
|
||||
}))
|
||||
|
||||
got, err := handler.ServeHTTP(w, r)
|
||||
if test.shouldErr {
|
||||
if err == nil {
|
||||
t.Errorf("Test %d: Expected i/o timeout error but had none", i)
|
||||
} else if err, ok := err.(net.Error); !ok || !err.Timeout() {
|
||||
t.Errorf("Test %d: Expected i/o timeout error, got: '%s'", i, err.Error())
|
||||
}
|
||||
|
||||
want := http.StatusGatewayTimeout
|
||||
if got != want {
|
||||
t.Errorf("Test %d: Expected returned status code to be %d, got: %d",
|
||||
i, want, got)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Errorf("Test %d: Expected nil error, got: %v", i, err)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendTimeout(t *testing.T) {
|
||||
tests := []struct {
|
||||
sendTimeout time.Duration
|
||||
shouldErr bool
|
||||
}{
|
||||
{-1 * time.Second, true},
|
||||
{time.Minute, false},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Unable to create listener for test: %v", i, err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
network, address := parseAddress(listener.Addr().String())
|
||||
handler := Handler{
|
||||
Next: nil,
|
||||
Rules: []Rule{
|
||||
{
|
||||
Path: "/",
|
||||
Address: listener.Addr().String(),
|
||||
dialer: basicDialer{network: network, address: address},
|
||||
SendTimeout: test.sendTimeout,
|
||||
},
|
||||
},
|
||||
}
|
||||
r, err := http.NewRequest("GET", "/", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Unable to create request: %v", i, err)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
go fcgi.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
got, err := handler.ServeHTTP(w, r)
|
||||
if test.shouldErr {
|
||||
if err == nil {
|
||||
t.Errorf("Test %d: Expected i/o timeout error but had none", i)
|
||||
} else if err, ok := err.(net.Error); !ok || !err.Timeout() {
|
||||
t.Errorf("Test %d: Expected i/o timeout error, got: '%s'", i, err.Error())
|
||||
}
|
||||
|
||||
want := http.StatusGatewayTimeout
|
||||
if got != want {
|
||||
t.Errorf("Test %d: Expected returned status code to be %d, got: %d",
|
||||
i, want, got)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Errorf("Test %d: Expected nil error, got: %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
ini_set("display_errors",1);
|
||||
|
||||
echo "resp: start\n";//.print_r($GLOBALS,1)."\n".print_r($_SERVER,1)."\n";
|
||||
|
||||
//echo print_r($_SERVER,1)."\n";
|
||||
|
||||
$length = 0;
|
||||
$stat = "PASSED";
|
||||
|
||||
$ret = "[";
|
||||
|
||||
if (count($_POST) || count($_FILES)) {
|
||||
foreach($_POST as $key => $val) {
|
||||
$md5 = md5($val);
|
||||
|
||||
if ($key != $md5) {
|
||||
$stat = "FAILED";
|
||||
echo "server:err ".$md5." != ".$key."\n";
|
||||
}
|
||||
|
||||
$length += strlen($key) + strlen($val);
|
||||
|
||||
$ret .= $key."(".strlen($key).") ";
|
||||
}
|
||||
$ret .= "] [";
|
||||
foreach ($_FILES as $k0 => $val) {
|
||||
|
||||
$error = $val["error"];
|
||||
if ($error == UPLOAD_ERR_OK) {
|
||||
$tmp_name = $val["tmp_name"];
|
||||
$name = $val["name"];
|
||||
$datafile = "/tmp/test.go";
|
||||
move_uploaded_file($tmp_name, $datafile);
|
||||
$md5 = md5_file($datafile);
|
||||
|
||||
if ($k0 != $md5) {
|
||||
$stat = "FAILED";
|
||||
echo "server:err ".$md5." != ".$key."\n";
|
||||
}
|
||||
|
||||
$length += strlen($k0) + filesize($datafile);
|
||||
|
||||
unlink($datafile);
|
||||
$ret .= $k0."(".strlen($k0).") ";
|
||||
}
|
||||
else{
|
||||
$stat = "FAILED";
|
||||
echo "server:file err ".file_upload_error_message($error)."\n";
|
||||
}
|
||||
}
|
||||
$ret .= "]";
|
||||
echo "server:got data length " .$length."\n";
|
||||
}
|
||||
|
||||
|
||||
echo "-{$stat}-POST(".count($_POST).") FILE(".count($_FILES).")\n";
|
||||
|
||||
function file_upload_error_message($error_code) {
|
||||
switch ($error_code) {
|
||||
case UPLOAD_ERR_INI_SIZE:
|
||||
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
|
||||
case UPLOAD_ERR_FORM_SIZE:
|
||||
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
|
||||
case UPLOAD_ERR_PARTIAL:
|
||||
return 'The uploaded file was only partially uploaded';
|
||||
case UPLOAD_ERR_NO_FILE:
|
||||
return 'No file was uploaded';
|
||||
case UPLOAD_ERR_NO_TMP_DIR:
|
||||
return 'Missing a temporary folder';
|
||||
case UPLOAD_ERR_CANT_WRITE:
|
||||
return 'Failed to write file to disk';
|
||||
case UPLOAD_ERR_EXTENSION:
|
||||
return 'File upload stopped by extension';
|
||||
default:
|
||||
return 'Unknown upload error';
|
||||
}
|
||||
}
|
||||
+81
-76
@@ -1,21 +1,8 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Forked Jan. 2015 from http://bitbucket.org/PinIdea/fcgi_client
|
||||
// (which is forked from https://code.google.com/p/go-fastcgi-client/).
|
||||
// (which is forked from https://code.google.com/p/go-fastcgi-client/)
|
||||
|
||||
// This fork contains several fixes and improvements by Matt Holt and
|
||||
// other contributors to the Caddy project.
|
||||
// other contributors to this project.
|
||||
|
||||
// Copyright 2012 Junqing Tan <ivan@mysqlab.net> and The Go Authors
|
||||
// Use of this source code is governed by a BSD-style
|
||||
@@ -26,7 +13,6 @@ package fastcgi
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
@@ -121,6 +107,18 @@ const (
|
||||
maxPad = 255
|
||||
)
|
||||
|
||||
// Client interface
|
||||
type Client interface {
|
||||
Get(pair map[string]string) (response *http.Response, err error)
|
||||
Head(pair map[string]string) (response *http.Response, err error)
|
||||
Options(pairs map[string]string) (response *http.Response, err error)
|
||||
Post(pairs map[string]string, method string, bodyType string, body io.Reader, contentLength int) (response *http.Response, err error)
|
||||
Close() error
|
||||
StdErr() bytes.Buffer
|
||||
SetReadTimeout(time.Duration) error
|
||||
SetSendTimeout(time.Duration) error
|
||||
}
|
||||
|
||||
type header struct {
|
||||
Version uint8
|
||||
Type uint8
|
||||
@@ -152,7 +150,7 @@ func (rec *record) read(r io.Reader) (buf []byte, err error) {
|
||||
return
|
||||
}
|
||||
if rec.h.Version != 1 {
|
||||
err = errors.New("fcgi: invalid header version")
|
||||
err = errInvalidHeaderVersion
|
||||
return
|
||||
}
|
||||
if rec.h.Type == EndRequest {
|
||||
@@ -174,67 +172,64 @@ func (rec *record) read(r io.Reader) (buf []byte, err error) {
|
||||
// FCGIClient implements a FastCGI client, which is a standard for
|
||||
// interfacing external applications with Web servers.
|
||||
type FCGIClient struct {
|
||||
mutex sync.Mutex
|
||||
rwc io.ReadWriteCloser
|
||||
h header
|
||||
buf bytes.Buffer
|
||||
stderr bytes.Buffer
|
||||
keepAlive bool
|
||||
reqID uint16
|
||||
mutex sync.Mutex
|
||||
conn net.Conn
|
||||
h header
|
||||
buf bytes.Buffer
|
||||
stderr bytes.Buffer
|
||||
keepAlive bool
|
||||
reqID uint16
|
||||
readTimeout time.Duration
|
||||
sendTimeout time.Duration
|
||||
}
|
||||
|
||||
// DialWithDialerContext connects to the fcgi responder at the specified network address, using custom net.Dialer
|
||||
// and a context.
|
||||
// DialTimeout connects to the fcgi responder at the specified network address, using default net.Dialer.
|
||||
// See func net.Dial for a description of the network and address parameters.
|
||||
func DialWithDialerContext(ctx context.Context, network, address string, dialer net.Dialer) (fcgi *FCGIClient, err error) {
|
||||
var conn net.Conn
|
||||
conn, err = dialer.DialContext(ctx, network, address)
|
||||
func DialTimeout(network string, address string, timeout time.Duration) (fcgi *FCGIClient, err error) {
|
||||
conn, err := net.DialTimeout(network, address, timeout)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
fcgi = &FCGIClient{
|
||||
rwc: conn,
|
||||
keepAlive: false,
|
||||
reqID: 1,
|
||||
}
|
||||
fcgi = &FCGIClient{conn: conn, keepAlive: false, reqID: 1}
|
||||
|
||||
return
|
||||
return fcgi, nil
|
||||
}
|
||||
|
||||
// DialContext is like Dial but passes ctx to dialer.Dial.
|
||||
func DialContext(ctx context.Context, network, address string) (fcgi *FCGIClient, err error) {
|
||||
// TODO: why not set timeout here?
|
||||
return DialWithDialerContext(ctx, network, address, net.Dialer{})
|
||||
// Close closes fcgi connnection.
|
||||
func (c *FCGIClient) Close() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// Dial connects to the fcgi responder at the specified network address, using default net.Dialer.
|
||||
// See func net.Dial for a description of the network and address parameters.
|
||||
func Dial(network, address string) (fcgi *FCGIClient, err error) {
|
||||
return DialContext(context.Background(), network, address)
|
||||
}
|
||||
|
||||
// Close closes fcgi connection
|
||||
func (c *FCGIClient) Close() {
|
||||
c.rwc.Close()
|
||||
}
|
||||
|
||||
func (c *FCGIClient) writeRecord(recType uint8, content []byte) (err error) {
|
||||
func (c *FCGIClient) writeRecord(recType uint8, content []byte) error {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
c.buf.Reset()
|
||||
c.h.init(recType, c.reqID, len(content))
|
||||
|
||||
if err := binary.Write(&c.buf, binary.BigEndian, c.h); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := c.buf.Write(content); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := c.buf.Write(pad[:c.h.PaddingLength]); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.rwc.Write(c.buf.Bytes())
|
||||
return err
|
||||
|
||||
if c.sendTimeout != 0 {
|
||||
if err := c.conn.SetWriteDeadline(time.Now().Add(c.sendTimeout)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := c.conn.Write(c.buf.Bytes()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *FCGIClient) writeBeginRequest(role uint16, flags uint8) error {
|
||||
@@ -350,13 +345,14 @@ func (w *streamReader) Read(p []byte) (n int, err error) {
|
||||
|
||||
if len(p) > 0 {
|
||||
if len(w.buf) == 0 {
|
||||
|
||||
// filter outputs for error log
|
||||
for {
|
||||
rec := &record{}
|
||||
var buf []byte
|
||||
buf, err = rec.read(w.c.rwc)
|
||||
if err != nil {
|
||||
buf, err = rec.read(w.c.conn)
|
||||
if err == errInvalidHeaderVersion {
|
||||
continue
|
||||
} else if err != nil {
|
||||
return
|
||||
}
|
||||
// standard error output
|
||||
@@ -380,10 +376,15 @@ func (w *streamReader) Read(p []byte) (n int, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// StdErr returns stderr stream
|
||||
func (c *FCGIClient) StdErr() bytes.Buffer {
|
||||
return c.stderr
|
||||
}
|
||||
|
||||
// Do made the request and returns a io.Reader that translates the data read
|
||||
// from fcgi responder out of fcgi packet before returning it.
|
||||
func (c *FCGIClient) Do(p map[string]string, req io.Reader) (r io.Reader, err error) {
|
||||
err = c.writeBeginRequest(uint16(Responder), 0)
|
||||
err = c.writeBeginRequest(uint16(Responder), FCGIKeepConn)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -395,7 +396,7 @@ func (c *FCGIClient) Do(p map[string]string, req io.Reader) (r io.Reader, err er
|
||||
|
||||
body := newWriter(c, Stdin)
|
||||
if req != nil {
|
||||
_, _ = io.Copy(body, req)
|
||||
io.Copy(body, req)
|
||||
}
|
||||
body.Close()
|
||||
|
||||
@@ -406,11 +407,11 @@ func (c *FCGIClient) Do(p map[string]string, req io.Reader) (r io.Reader, err er
|
||||
// clientCloser is a io.ReadCloser. It wraps a io.Reader with a Closer
|
||||
// that closes FCGIClient connection.
|
||||
type clientCloser struct {
|
||||
*FCGIClient
|
||||
f *FCGIClient
|
||||
io.Reader
|
||||
}
|
||||
|
||||
func (f clientCloser) Close() error { return f.rwc.Close() }
|
||||
func (c clientCloser) Close() error { return c.f.Close() }
|
||||
|
||||
// Request returns a HTTP Response with Header and Body
|
||||
// from fcgi responder
|
||||
@@ -424,6 +425,12 @@ func (c *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Res
|
||||
tp := textproto.NewReader(rb)
|
||||
resp = new(http.Response)
|
||||
|
||||
if c.readTimeout != 0 {
|
||||
if err = c.conn.SetReadDeadline(time.Now().Add(c.readTimeout)); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the response headers.
|
||||
mimeHeader, err := tp.ReadMIMEHeader()
|
||||
if err != nil && err != io.EOF {
|
||||
@@ -458,12 +465,12 @@ func (c *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Res
|
||||
}
|
||||
|
||||
// Get issues a GET request to the fcgi responder.
|
||||
func (c *FCGIClient) Get(p map[string]string, body io.Reader, l int64) (resp *http.Response, err error) {
|
||||
func (c *FCGIClient) Get(p map[string]string) (resp *http.Response, err error) {
|
||||
|
||||
p["REQUEST_METHOD"] = "GET"
|
||||
p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10)
|
||||
p["CONTENT_LENGTH"] = "0"
|
||||
|
||||
return c.Request(p, body)
|
||||
return c.Request(p, nil)
|
||||
}
|
||||
|
||||
// Head issues a HEAD request to the fcgi responder.
|
||||
@@ -486,7 +493,7 @@ func (c *FCGIClient) Options(p map[string]string) (resp *http.Response, err erro
|
||||
|
||||
// Post issues a POST request to the fcgi responder. with request body
|
||||
// in the format that bodyType specified
|
||||
func (c *FCGIClient) Post(p map[string]string, method string, bodyType string, body io.Reader, l int64) (resp *http.Response, err error) {
|
||||
func (c *FCGIClient) Post(p map[string]string, method string, bodyType string, body io.Reader, l int) (resp *http.Response, err error) {
|
||||
if p == nil {
|
||||
p = make(map[string]string)
|
||||
}
|
||||
@@ -497,7 +504,7 @@ func (c *FCGIClient) Post(p map[string]string, method string, bodyType string, b
|
||||
p["REQUEST_METHOD"] = "POST"
|
||||
}
|
||||
|
||||
p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10)
|
||||
p["CONTENT_LENGTH"] = strconv.Itoa(l)
|
||||
if len(bodyType) > 0 {
|
||||
p["CONTENT_TYPE"] = bodyType
|
||||
} else {
|
||||
@@ -511,7 +518,7 @@ func (c *FCGIClient) Post(p map[string]string, method string, bodyType string, b
|
||||
// as a string key to a list values (url.Values)
|
||||
func (c *FCGIClient) PostForm(p map[string]string, data url.Values) (resp *http.Response, err error) {
|
||||
body := bytes.NewReader([]byte(data.Encode()))
|
||||
return c.Post(p, "POST", "application/x-www-form-urlencoded", body, int64(body.Len()))
|
||||
return c.Post(p, "POST", "application/x-www-form-urlencoded", body, body.Len())
|
||||
}
|
||||
|
||||
// PostFile issues a POST to the fcgi responder in multipart(RFC 2046) standard,
|
||||
@@ -553,26 +560,24 @@ func (c *FCGIClient) PostFile(p map[string]string, data url.Values, file map[str
|
||||
return
|
||||
}
|
||||
|
||||
return c.Post(p, "POST", bodyType, buf, int64(buf.Len()))
|
||||
return c.Post(p, "POST", bodyType, buf, buf.Len())
|
||||
}
|
||||
|
||||
// SetReadTimeout sets the read timeout for future calls that read from the
|
||||
// fcgi responder. A zero value for t means no timeout will be set.
|
||||
func (c *FCGIClient) SetReadTimeout(t time.Duration) error {
|
||||
if conn, ok := c.rwc.(net.Conn); ok && t != 0 {
|
||||
return conn.SetReadDeadline(time.Now().Add(t))
|
||||
}
|
||||
c.readTimeout = t
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetWriteTimeout sets the write timeout for future calls that send data to
|
||||
// SetSendTimeout sets the read timeout for future calls that send data to
|
||||
// the fcgi responder. A zero value for t means no timeout will be set.
|
||||
func (c *FCGIClient) SetWriteTimeout(t time.Duration) error {
|
||||
if conn, ok := c.rwc.(net.Conn); ok && t != 0 {
|
||||
return conn.SetWriteDeadline(time.Now().Add(t))
|
||||
}
|
||||
func (c *FCGIClient) SetSendTimeout(t time.Duration) error {
|
||||
c.sendTimeout = t
|
||||
return nil
|
||||
}
|
||||
|
||||
// Checks whether chunked is part of the encodings stack
|
||||
func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
|
||||
|
||||
var errInvalidHeaderVersion = errors.New("fcgi: invalid header version")
|
||||
+18
-44
@@ -1,17 +1,3 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// NOTE: These tests were adapted from the original
|
||||
// repository from which this package was forked.
|
||||
// The tests are slow (~10s) and in dire need of rewriting.
|
||||
@@ -44,7 +30,7 @@ import (
|
||||
// test fcgi protocol includes:
|
||||
// Get, Post, Post in multipart/form-data, and Post with files
|
||||
// each key should be the md5 of the value or the file uploaded
|
||||
// specify remote fcgi responder ip:port to test with php
|
||||
// sepicify remote fcgi responer ip:port to test with php
|
||||
// test failed if the remote fcgi(script) failed md5 verification
|
||||
// and output "FAILED" in response
|
||||
const (
|
||||
@@ -59,9 +45,7 @@ type FastCGIServer struct{}
|
||||
|
||||
func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
|
||||
|
||||
if err := req.ParseMultipartForm(100000000); err != nil {
|
||||
log.Printf("[ERROR] failed to parse: %v", err)
|
||||
}
|
||||
req.ParseMultipartForm(100000000)
|
||||
|
||||
stat := "PASSED"
|
||||
fmt.Fprintln(resp, "-")
|
||||
@@ -70,15 +54,15 @@ func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
|
||||
length := 0
|
||||
for k0, v0 := range req.Form {
|
||||
h := md5.New()
|
||||
_, _ = io.WriteString(h, v0[0])
|
||||
_md5 := fmt.Sprintf("%x", h.Sum(nil))
|
||||
io.WriteString(h, v0[0])
|
||||
md5 := fmt.Sprintf("%x", h.Sum(nil))
|
||||
|
||||
length += len(k0)
|
||||
length += len(v0[0])
|
||||
|
||||
// echo error when key != _md5(val)
|
||||
if _md5 != k0 {
|
||||
fmt.Fprintln(resp, "server:err ", _md5, k0)
|
||||
// echo error when key != md5(val)
|
||||
if md5 != k0 {
|
||||
fmt.Fprintln(resp, "server:err ", md5, k0)
|
||||
stat = "FAILED"
|
||||
}
|
||||
}
|
||||
@@ -119,7 +103,7 @@ func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
|
||||
}
|
||||
|
||||
func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[string]string, files map[string]string) (content []byte) {
|
||||
fcgi, err := Dial("tcp", ipPort)
|
||||
fcgi, err := DialTimeout("tcp", ipPort, 0)
|
||||
if err != nil {
|
||||
log.Println("err:", err)
|
||||
return
|
||||
@@ -133,7 +117,7 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[
|
||||
if len(data) > 0 {
|
||||
length = len(data)
|
||||
rd := bytes.NewReader(data)
|
||||
resp, err = fcgi.Post(fcgiParams, "", "", rd, int64(rd.Len()))
|
||||
resp, err = fcgi.Post(fcgiParams, "", "", rd, rd.Len())
|
||||
} else if len(posts) > 0 {
|
||||
values := url.Values{}
|
||||
for k, v := range posts {
|
||||
@@ -142,8 +126,7 @@ func sendFcgi(reqType int, fcgiParams map[string]string, data []byte, posts map[
|
||||
}
|
||||
resp, err = fcgi.PostForm(fcgiParams, values)
|
||||
} else {
|
||||
rd := bytes.NewReader(data)
|
||||
resp, err = fcgi.Get(fcgiParams, rd, int64(rd.Len()))
|
||||
resp, err = fcgi.Get(fcgiParams)
|
||||
}
|
||||
|
||||
default:
|
||||
@@ -199,12 +182,8 @@ func generateRandFile(size int) (p string, m string) {
|
||||
for i := 0; i < size/16; i++ {
|
||||
buf := make([]byte, 16)
|
||||
binary.PutVarint(buf, rand.Int63())
|
||||
if _, err := fo.Write(buf); err != nil {
|
||||
log.Printf("[ERROR] failed to write buffer: %v\n", err)
|
||||
}
|
||||
if _, err := h.Write(buf); err != nil {
|
||||
log.Printf("[ERROR] failed to write buffer: %v\n", err)
|
||||
}
|
||||
fo.Write(buf)
|
||||
h.Write(buf)
|
||||
}
|
||||
m = fmt.Sprintf("%x", h.Sum(nil))
|
||||
return
|
||||
@@ -220,13 +199,12 @@ func DisabledTest(t *testing.T) {
|
||||
go func() {
|
||||
listener, err := net.Listen("tcp", ipPort)
|
||||
if err != nil {
|
||||
// handle error
|
||||
log.Println("listener creation failed: ", err)
|
||||
}
|
||||
|
||||
srv := new(FastCGIServer)
|
||||
if err := fcgi.Serve(listener, srv); err != nil {
|
||||
log.Print("[ERROR] failed to start server: ", err)
|
||||
}
|
||||
fcgi.Serve(listener, srv)
|
||||
}()
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
@@ -251,7 +229,7 @@ func DisabledTest(t *testing.T) {
|
||||
for i := 0x00; i < 0xff; i++ {
|
||||
v0 := strings.Repeat(string(i), 256)
|
||||
h := md5.New()
|
||||
_, _ = io.WriteString(h, v0)
|
||||
io.WriteString(h, v0)
|
||||
k0 := fmt.Sprintf("%x", h.Sum(nil))
|
||||
data += k0 + "=" + url.QueryEscape(v0) + "&"
|
||||
}
|
||||
@@ -268,7 +246,7 @@ func DisabledTest(t *testing.T) {
|
||||
for i := 0x00; i < 0xff; i++ {
|
||||
v0 := strings.Repeat(string(i), 4096)
|
||||
h := md5.New()
|
||||
_, _ = io.WriteString(h, v0)
|
||||
io.WriteString(h, v0)
|
||||
k0 := fmt.Sprintf("%x", h.Sum(nil))
|
||||
p1[k0] = v0
|
||||
}
|
||||
@@ -292,10 +270,6 @@ func DisabledTest(t *testing.T) {
|
||||
delete(f0, "m0")
|
||||
sendFcgi(1, fcgiParams, nil, nil, f0)
|
||||
|
||||
if err := os.Remove(path0); err != nil {
|
||||
log.Println("[ERROR] failed to remove path: ", err)
|
||||
}
|
||||
if err := os.Remove(path1); err != nil {
|
||||
log.Println("[ERROR] failed to remove path: ", err)
|
||||
}
|
||||
os.Remove(path0)
|
||||
os.Remove(path1)
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package fastcgi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("fastcgi", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
// setup configures a new FastCGI middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
cfg := httpserver.GetConfig(c)
|
||||
absRoot, err := filepath.Abs(cfg.Root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rules, err := fastcgiParse(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
return Handler{
|
||||
Next: next,
|
||||
Rules: rules,
|
||||
Root: cfg.Root,
|
||||
AbsRoot: absRoot,
|
||||
FileSys: http.Dir(cfg.Root),
|
||||
SoftwareName: caddy.AppName,
|
||||
SoftwareVersion: caddy.AppVersion,
|
||||
ServerName: cfg.Addr.Host,
|
||||
ServerPort: cfg.Addr.Port,
|
||||
}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fastcgiParse(c *caddy.Controller) ([]Rule, error) {
|
||||
var rules []Rule
|
||||
|
||||
for c.Next() {
|
||||
args := c.RemainingArgs()
|
||||
|
||||
if len(args) < 2 || len(args) > 3 {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
|
||||
rule := Rule{Path: args[0], ReadTimeout: 60 * time.Second, SendTimeout: 60 * time.Second}
|
||||
upstreams := []string{args[1]}
|
||||
|
||||
if len(args) == 3 {
|
||||
if err := fastcgiPreset(args[2], &rule); err != nil {
|
||||
return rules, err
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
var pool int
|
||||
var connectTimeout = 60 * time.Second
|
||||
var dialers []dialer
|
||||
var poolSize = -1
|
||||
|
||||
for c.NextBlock() {
|
||||
switch c.Val() {
|
||||
case "ext":
|
||||
if !c.NextArg() {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
rule.Ext = c.Val()
|
||||
case "split":
|
||||
if !c.NextArg() {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
rule.SplitPath = c.Val()
|
||||
case "index":
|
||||
args := c.RemainingArgs()
|
||||
if len(args) == 0 {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
rule.IndexFiles = args
|
||||
|
||||
case "upstream":
|
||||
args := c.RemainingArgs()
|
||||
|
||||
if len(args) != 1 {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
|
||||
upstreams = append(upstreams, args[0])
|
||||
case "env":
|
||||
envArgs := c.RemainingArgs()
|
||||
if len(envArgs) < 2 {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
rule.EnvVars = append(rule.EnvVars, [2]string{envArgs[0], envArgs[1]})
|
||||
case "except":
|
||||
ignoredPaths := c.RemainingArgs()
|
||||
if len(ignoredPaths) == 0 {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
rule.IgnoredSubPaths = ignoredPaths
|
||||
|
||||
case "pool":
|
||||
if !c.NextArg() {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
pool, err = strconv.Atoi(c.Val())
|
||||
if err != nil {
|
||||
return rules, err
|
||||
}
|
||||
if pool >= 0 {
|
||||
poolSize = pool
|
||||
} else {
|
||||
return rules, c.Errf("positive integer expected, found %d", pool)
|
||||
}
|
||||
case "connect_timeout":
|
||||
if !c.NextArg() {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
connectTimeout, err = time.ParseDuration(c.Val())
|
||||
if err != nil {
|
||||
return rules, err
|
||||
}
|
||||
case "read_timeout":
|
||||
if !c.NextArg() {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
readTimeout, err := time.ParseDuration(c.Val())
|
||||
if err != nil {
|
||||
return rules, err
|
||||
}
|
||||
rule.ReadTimeout = readTimeout
|
||||
case "send_timeout":
|
||||
if !c.NextArg() {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
sendTimeout, err := time.ParseDuration(c.Val())
|
||||
if err != nil {
|
||||
return rules, err
|
||||
}
|
||||
rule.SendTimeout = sendTimeout
|
||||
}
|
||||
}
|
||||
|
||||
for _, rawAddress := range upstreams {
|
||||
network, address := parseAddress(rawAddress)
|
||||
if poolSize >= 0 {
|
||||
dialers = append(dialers, &persistentDialer{
|
||||
size: poolSize,
|
||||
network: network,
|
||||
address: address,
|
||||
timeout: connectTimeout,
|
||||
})
|
||||
} else {
|
||||
dialers = append(dialers, basicDialer{
|
||||
network: network,
|
||||
address: address,
|
||||
timeout: connectTimeout,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
rule.dialer = &loadBalancingDialer{dialers: dialers}
|
||||
rule.Address = strings.Join(upstreams, ",")
|
||||
rules = append(rules, rule)
|
||||
}
|
||||
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
// fastcgiPreset configures rule according to name. It returns an error if
|
||||
// name is not a recognized preset name.
|
||||
func fastcgiPreset(name string, rule *Rule) error {
|
||||
switch name {
|
||||
case "php":
|
||||
rule.Ext = ".php"
|
||||
rule.SplitPath = ".php"
|
||||
rule.IndexFiles = []string{"index.php"}
|
||||
default:
|
||||
return errors.New(name + " is not a valid preset name")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package fastcgi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `fastcgi / 127.0.0.1:9000`)
|
||||
err := setup(c)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no errors, got: %v", err)
|
||||
}
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
if len(mids) == 0 {
|
||||
t.Fatal("Expected middleware, got 0 instead")
|
||||
}
|
||||
|
||||
handler := mids[0](httpserver.EmptyNext)
|
||||
myHandler, ok := handler.(Handler)
|
||||
|
||||
if !ok {
|
||||
t.Fatalf("Expected handler to be type , got: %#v", handler)
|
||||
}
|
||||
|
||||
if myHandler.Rules[0].Path != "/" {
|
||||
t.Errorf("Expected / as the Path")
|
||||
}
|
||||
if myHandler.Rules[0].Address != "127.0.0.1:9000" {
|
||||
t.Errorf("Expected 127.0.0.1:9000 as the Address")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (p *persistentDialer) Equals(q *persistentDialer) bool {
|
||||
if p.size != q.size {
|
||||
return false
|
||||
}
|
||||
if p.network != q.network {
|
||||
return false
|
||||
}
|
||||
if p.address != q.address {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(p.pool) != len(q.pool) {
|
||||
return false
|
||||
}
|
||||
for i, client := range p.pool {
|
||||
if client != q.pool[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
// ignore mutex state
|
||||
return true
|
||||
}
|
||||
|
||||
func TestFastcgiParse(t *testing.T) {
|
||||
defaultAddress := "127.0.0.1:9001"
|
||||
network, address := parseAddress(defaultAddress)
|
||||
t.Logf("Address '%v' was parsed to network '%v' and address '%v'", defaultAddress, network, address)
|
||||
|
||||
tests := []struct {
|
||||
inputFastcgiConfig string
|
||||
shouldErr bool
|
||||
expectedFastcgiConfig []Rule
|
||||
}{
|
||||
|
||||
{`fastcgi /blog 127.0.0.1:9000 php`,
|
||||
false, []Rule{{
|
||||
Path: "/blog",
|
||||
Address: "127.0.0.1:9000",
|
||||
Ext: ".php",
|
||||
SplitPath: ".php",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: "tcp", address: "127.0.0.1:9000", timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{"index.php"},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{`fastcgi /blog 127.0.0.1:9000 php {
|
||||
upstream 127.0.0.1:9001
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/blog",
|
||||
Address: "127.0.0.1:9000,127.0.0.1:9001",
|
||||
Ext: ".php",
|
||||
SplitPath: ".php",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: "tcp", address: "127.0.0.1:9000", timeout: 60 * time.Second}, basicDialer{network: "tcp", address: "127.0.0.1:9001", timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{"index.php"},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{`fastcgi /blog 127.0.0.1:9000 {
|
||||
upstream 127.0.0.1:9001
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/blog",
|
||||
Address: "127.0.0.1:9000,127.0.0.1:9001",
|
||||
Ext: "",
|
||||
SplitPath: "",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: "tcp", address: "127.0.0.1:9000", timeout: 60 * time.Second}, basicDialer{network: "tcp", address: "127.0.0.1:9001", timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{`fastcgi / ` + defaultAddress + ` {
|
||||
split .html
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/",
|
||||
Address: defaultAddress,
|
||||
Ext: "",
|
||||
SplitPath: ".html",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: network, address: address, timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{`fastcgi / ` + defaultAddress + ` {
|
||||
split .html
|
||||
except /admin /user
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/",
|
||||
Address: "127.0.0.1:9001",
|
||||
Ext: "",
|
||||
SplitPath: ".html",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: network, address: address, timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
IgnoredSubPaths: []string{"/admin", "/user"},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{`fastcgi / ` + defaultAddress + ` {
|
||||
pool 0
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/",
|
||||
Address: defaultAddress,
|
||||
Ext: "",
|
||||
SplitPath: "",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{&persistentDialer{size: 0, network: network, address: address, timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{`fastcgi / 127.0.0.1:8080 {
|
||||
upstream 127.0.0.1:9000
|
||||
pool 5
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/",
|
||||
Address: "127.0.0.1:8080,127.0.0.1:9000",
|
||||
Ext: "",
|
||||
SplitPath: "",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{&persistentDialer{size: 5, network: "tcp", address: "127.0.0.1:8080", timeout: 60 * time.Second}, &persistentDialer{size: 5, network: "tcp", address: "127.0.0.1:9000", timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{`fastcgi / ` + defaultAddress + ` {
|
||||
split .php
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/",
|
||||
Address: defaultAddress,
|
||||
Ext: "",
|
||||
SplitPath: ".php",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: network, address: address, timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{`fastcgi / ` + defaultAddress + ` {
|
||||
connect_timeout 5s
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/",
|
||||
Address: defaultAddress,
|
||||
Ext: "",
|
||||
SplitPath: "",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: network, address: address, timeout: 5 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{
|
||||
`fastcgi / ` + defaultAddress + ` { connect_timeout BADVALUE }`,
|
||||
true,
|
||||
[]Rule{},
|
||||
},
|
||||
{`fastcgi / ` + defaultAddress + ` {
|
||||
read_timeout 5s
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/",
|
||||
Address: defaultAddress,
|
||||
Ext: "",
|
||||
SplitPath: "",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: network, address: address, timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
ReadTimeout: 5 * time.Second,
|
||||
SendTimeout: 60 * time.Second,
|
||||
}}},
|
||||
{
|
||||
`fastcgi / ` + defaultAddress + ` { read_timeout BADVALUE }`,
|
||||
true,
|
||||
[]Rule{},
|
||||
},
|
||||
{`fastcgi / ` + defaultAddress + ` {
|
||||
send_timeout 5s
|
||||
}`,
|
||||
false, []Rule{{
|
||||
Path: "/",
|
||||
Address: defaultAddress,
|
||||
Ext: "",
|
||||
SplitPath: "",
|
||||
dialer: &loadBalancingDialer{dialers: []dialer{basicDialer{network: network, address: address, timeout: 60 * time.Second}}},
|
||||
IndexFiles: []string{},
|
||||
ReadTimeout: 60 * time.Second,
|
||||
SendTimeout: 5 * time.Second,
|
||||
}}},
|
||||
{
|
||||
`fastcgi / ` + defaultAddress + ` { send_timeout BADVALUE }`,
|
||||
true,
|
||||
[]Rule{},
|
||||
},
|
||||
{`fastcgi / {
|
||||
|
||||
}`,
|
||||
true, []Rule{},
|
||||
},
|
||||
}
|
||||
for i, test := range tests {
|
||||
actualFastcgiConfigs, err := fastcgiParse(caddy.NewTestController("http", test.inputFastcgiConfig))
|
||||
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d didn't error, but it should have", i)
|
||||
} else if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
|
||||
}
|
||||
if len(actualFastcgiConfigs) != len(test.expectedFastcgiConfig) {
|
||||
t.Fatalf("Test %d expected %d no of FastCGI configs, but got %d ",
|
||||
i, len(test.expectedFastcgiConfig), len(actualFastcgiConfigs))
|
||||
}
|
||||
for j, actualFastcgiConfig := range actualFastcgiConfigs {
|
||||
|
||||
if actualFastcgiConfig.Path != test.expectedFastcgiConfig[j].Path {
|
||||
t.Errorf("Test %d expected %dth FastCGI Path to be %s , but got %s",
|
||||
i, j, test.expectedFastcgiConfig[j].Path, actualFastcgiConfig.Path)
|
||||
}
|
||||
|
||||
if actualFastcgiConfig.Address != test.expectedFastcgiConfig[j].Address {
|
||||
t.Errorf("Test %d expected %dth FastCGI Address to be %s , but got %s",
|
||||
i, j, test.expectedFastcgiConfig[j].Address, actualFastcgiConfig.Address)
|
||||
}
|
||||
|
||||
if actualFastcgiConfig.Ext != test.expectedFastcgiConfig[j].Ext {
|
||||
t.Errorf("Test %d expected %dth FastCGI Ext to be %s , but got %s",
|
||||
i, j, test.expectedFastcgiConfig[j].Ext, actualFastcgiConfig.Ext)
|
||||
}
|
||||
|
||||
if actualFastcgiConfig.SplitPath != test.expectedFastcgiConfig[j].SplitPath {
|
||||
t.Errorf("Test %d expected %dth FastCGI SplitPath to be %s , but got %s",
|
||||
i, j, test.expectedFastcgiConfig[j].SplitPath, actualFastcgiConfig.SplitPath)
|
||||
}
|
||||
|
||||
if reflect.TypeOf(actualFastcgiConfig.dialer) != reflect.TypeOf(test.expectedFastcgiConfig[j].dialer) {
|
||||
t.Errorf("Test %d expected %dth FastCGI dialer to be of type %T, but got %T",
|
||||
i, j, test.expectedFastcgiConfig[j].dialer, actualFastcgiConfig.dialer)
|
||||
} else {
|
||||
if !areDialersEqual(actualFastcgiConfig.dialer, test.expectedFastcgiConfig[j].dialer, t) {
|
||||
t.Errorf("Test %d expected %dth FastCGI dialer to be %v, but got %v",
|
||||
i, j, test.expectedFastcgiConfig[j].dialer, actualFastcgiConfig.dialer)
|
||||
}
|
||||
}
|
||||
|
||||
if fmt.Sprint(actualFastcgiConfig.IndexFiles) != fmt.Sprint(test.expectedFastcgiConfig[j].IndexFiles) {
|
||||
t.Errorf("Test %d expected %dth FastCGI IndexFiles to be %s , but got %s",
|
||||
i, j, test.expectedFastcgiConfig[j].IndexFiles, actualFastcgiConfig.IndexFiles)
|
||||
}
|
||||
|
||||
if fmt.Sprint(actualFastcgiConfig.IgnoredSubPaths) != fmt.Sprint(test.expectedFastcgiConfig[j].IgnoredSubPaths) {
|
||||
t.Errorf("Test %d expected %dth FastCGI IgnoredSubPaths to be %s , but got %s",
|
||||
i, j, test.expectedFastcgiConfig[j].IgnoredSubPaths, actualFastcgiConfig.IgnoredSubPaths)
|
||||
}
|
||||
|
||||
if fmt.Sprint(actualFastcgiConfig.ReadTimeout) != fmt.Sprint(test.expectedFastcgiConfig[j].ReadTimeout) {
|
||||
t.Errorf("Test %d expected %dth FastCGI ReadTimeout to be %s , but got %s",
|
||||
i, j, test.expectedFastcgiConfig[j].ReadTimeout, actualFastcgiConfig.ReadTimeout)
|
||||
}
|
||||
|
||||
if fmt.Sprint(actualFastcgiConfig.SendTimeout) != fmt.Sprint(test.expectedFastcgiConfig[j].SendTimeout) {
|
||||
t.Errorf("Test %d expected %dth FastCGI SendTimeout to be %s , but got %s",
|
||||
i, j, test.expectedFastcgiConfig[j].SendTimeout, actualFastcgiConfig.SendTimeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func areDialersEqual(current, expected dialer, t *testing.T) bool {
|
||||
|
||||
switch actual := current.(type) {
|
||||
case *loadBalancingDialer:
|
||||
if expected, ok := expected.(*loadBalancingDialer); ok {
|
||||
for i := 0; i < len(actual.dialers); i++ {
|
||||
if !areDialersEqual(actual.dialers[i], expected.dialers[i], t) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
case basicDialer:
|
||||
return current == expected
|
||||
case *persistentDialer:
|
||||
if expected, ok := expected.(*persistentDialer); ok {
|
||||
return actual.Equals(expected)
|
||||
}
|
||||
|
||||
default:
|
||||
t.Errorf("Unknown dialer type %T", current)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Package gzip provides a middleware layer that performs
|
||||
// gzip compression on the response.
|
||||
package gzip
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("gzip", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
// Gzip is a middleware type which gzips HTTP responses. It is
|
||||
// imperative that any handler which writes to a gzipped response
|
||||
// specifies the Content-Type, otherwise some clients will assume
|
||||
// application/x-gzip and try to download a file.
|
||||
type Gzip struct {
|
||||
Next httpserver.Handler
|
||||
Configs []Config
|
||||
}
|
||||
|
||||
// Config holds the configuration for Gzip middleware
|
||||
type Config struct {
|
||||
RequestFilters []RequestFilter
|
||||
ResponseFilters []ResponseFilter
|
||||
Level int // Compression level
|
||||
}
|
||||
|
||||
// ServeHTTP serves a gzipped response if the client supports it.
|
||||
func (g Gzip) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||
return g.Next.ServeHTTP(w, r)
|
||||
}
|
||||
outer:
|
||||
for _, c := range g.Configs {
|
||||
|
||||
// Check request filters to determine if gzipping is permitted for this request
|
||||
for _, filter := range c.RequestFilters {
|
||||
if !filter.ShouldCompress(r) {
|
||||
continue outer
|
||||
}
|
||||
}
|
||||
|
||||
// gzipWriter modifies underlying writer at init,
|
||||
// use a discard writer instead to leave ResponseWriter in
|
||||
// original form.
|
||||
gzipWriter, err := newWriter(c, ioutil.Discard)
|
||||
if err != nil {
|
||||
// should not happen
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
defer gzipWriter.Close()
|
||||
gz := &gzipResponseWriter{Writer: gzipWriter, ResponseWriter: w}
|
||||
|
||||
var rw http.ResponseWriter
|
||||
// if no response filter is used
|
||||
if len(c.ResponseFilters) == 0 {
|
||||
// replace discard writer with ResponseWriter
|
||||
gzipWriter.Reset(w)
|
||||
rw = gz
|
||||
} else {
|
||||
// wrap gzip writer with ResponseFilterWriter
|
||||
rw = NewResponseFilterWriter(c.ResponseFilters, gz)
|
||||
}
|
||||
|
||||
// Any response in forward middleware will now be compressed
|
||||
status, err := g.Next.ServeHTTP(rw, r)
|
||||
|
||||
// If there was an error that remained unhandled, we need
|
||||
// to send something back before gzipWriter gets closed at
|
||||
// the return of this method!
|
||||
if status >= 400 {
|
||||
httpserver.DefaultErrorFunc(w, r, status)
|
||||
return 0, err
|
||||
}
|
||||
return status, err
|
||||
}
|
||||
|
||||
// no matching filter
|
||||
return g.Next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// newWriter create a new Gzip Writer based on the compression level.
|
||||
// If the level is valid (i.e. between 1 and 9), it uses the level.
|
||||
// Otherwise, it uses default compression level.
|
||||
func newWriter(c Config, w io.Writer) (*gzip.Writer, error) {
|
||||
if c.Level >= gzip.BestSpeed && c.Level <= gzip.BestCompression {
|
||||
return gzip.NewWriterLevel(w, c.Level)
|
||||
}
|
||||
return gzip.NewWriter(w), nil
|
||||
}
|
||||
|
||||
// gzipResponeWriter wraps the underlying Write method
|
||||
// with a gzip.Writer to compress the output.
|
||||
type gzipResponseWriter struct {
|
||||
io.Writer
|
||||
http.ResponseWriter
|
||||
statusCodeWritten bool
|
||||
}
|
||||
|
||||
// WriteHeader wraps the underlying WriteHeader method to prevent
|
||||
// problems with conflicting headers from proxied backends. For
|
||||
// example, a backend system that calculates Content-Length would
|
||||
// be wrong because it doesn't know it's being gzipped.
|
||||
func (w *gzipResponseWriter) WriteHeader(code int) {
|
||||
w.Header().Del("Content-Length")
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
w.Header().Add("Vary", "Accept-Encoding")
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
w.statusCodeWritten = true
|
||||
}
|
||||
|
||||
// Write wraps the underlying Write method to do compression.
|
||||
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
|
||||
if w.Header().Get("Content-Type") == "" {
|
||||
w.Header().Set("Content-Type", http.DetectContentType(b))
|
||||
}
|
||||
if !w.statusCodeWritten {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
n, err := w.Writer.Write(b)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Hijack implements http.Hijacker. It simply wraps the underlying
|
||||
// ResponseWriter's Hijack method if there is one, or returns an error.
|
||||
func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
if hj, ok := w.ResponseWriter.(http.Hijacker); ok {
|
||||
return hj.Hijack()
|
||||
}
|
||||
return nil, nil, httpserver.NonHijackerError{Underlying: w.ResponseWriter}
|
||||
}
|
||||
|
||||
// Flush implements http.Flusher. It simply wraps the underlying
|
||||
// ResponseWriter's Flush method if there is one, or panics.
|
||||
func (w *gzipResponseWriter) Flush() {
|
||||
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
} else {
|
||||
panic(httpserver.NonFlusherError{Underlying: w.ResponseWriter}) // should be recovered at the beginning of middleware stack
|
||||
}
|
||||
}
|
||||
|
||||
// CloseNotify implements http.CloseNotifier.
|
||||
// It just inherits the underlying ResponseWriter's CloseNotify method.
|
||||
func (w *gzipResponseWriter) CloseNotify() <-chan bool {
|
||||
if cn, ok := w.ResponseWriter.(http.CloseNotifier); ok {
|
||||
return cn.CloseNotify()
|
||||
}
|
||||
panic(httpserver.NonCloseNotifierError{Underlying: w.ResponseWriter})
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package gzip
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestGzipHandler(t *testing.T) {
|
||||
pathFilter := PathFilter{make(Set)}
|
||||
badPaths := []string{"/bad", "/nogzip", "/nongzip"}
|
||||
for _, p := range badPaths {
|
||||
pathFilter.IgnoredPaths.Add(p)
|
||||
}
|
||||
extFilter := ExtFilter{make(Set)}
|
||||
for _, e := range []string{".txt", ".html", ".css", ".md"} {
|
||||
extFilter.Exts.Add(e)
|
||||
}
|
||||
gz := Gzip{Configs: []Config{
|
||||
{RequestFilters: []RequestFilter{pathFilter, extFilter}},
|
||||
}}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
gz.Next = nextFunc(true)
|
||||
var exts = []string{
|
||||
".html", ".css", ".md",
|
||||
}
|
||||
for _, e := range exts {
|
||||
url := "/file" + e
|
||||
r, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
_, err = gz.ServeHTTP(w, r)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
gz.Next = nextFunc(false)
|
||||
for _, p := range badPaths {
|
||||
for _, e := range exts {
|
||||
url := p + "/file" + e
|
||||
r, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
_, err = gz.ServeHTTP(w, r)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
gz.Next = nextFunc(false)
|
||||
exts = []string{
|
||||
".htm1", ".abc", ".mdx",
|
||||
}
|
||||
for _, e := range exts {
|
||||
url := "/file" + e
|
||||
r, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
_, err = gz.ServeHTTP(w, r)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nextFunc(shouldGzip bool) httpserver.Handler {
|
||||
return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
// write a relatively large text file
|
||||
b, err := ioutil.ReadFile("testdata/test.txt")
|
||||
if err != nil {
|
||||
return 500, err
|
||||
}
|
||||
if _, err := w.Write(b); err != nil {
|
||||
return 500, err
|
||||
}
|
||||
|
||||
if shouldGzip {
|
||||
if w.Header().Get("Content-Encoding") != "gzip" {
|
||||
return 0, fmt.Errorf("Content-Encoding must be gzip, found %v", r.Header.Get("Content-Encoding"))
|
||||
}
|
||||
if w.Header().Get("Vary") != "Accept-Encoding" {
|
||||
return 0, fmt.Errorf("Vary must be Accept-Encoding, found %v", r.Header.Get("Vary"))
|
||||
}
|
||||
if _, ok := w.(*gzipResponseWriter); !ok {
|
||||
return 0, fmt.Errorf("ResponseWriter should be gzipResponseWriter, found %T", w)
|
||||
}
|
||||
if strings.Contains(w.Header().Get("Content-Type"), "application/x-gzip") {
|
||||
return 0, fmt.Errorf("Content-Type should not be gzip")
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
if r.Header.Get("Accept-Encoding") == "" {
|
||||
return 0, fmt.Errorf("Accept-Encoding header expected")
|
||||
}
|
||||
if w.Header().Get("Content-Encoding") == "gzip" {
|
||||
return 0, fmt.Errorf("Content-Encoding must not be gzip, found gzip")
|
||||
}
|
||||
if _, ok := w.(*gzipResponseWriter); ok {
|
||||
return 0, fmt.Errorf("ResponseWriter should not be gzipResponseWriter")
|
||||
}
|
||||
return 0, nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package gzip
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"path"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// RequestFilter determines if a request should be gzipped.
|
||||
type RequestFilter interface {
|
||||
// ShouldCompress tells if gzip compression
|
||||
// should be done on the request.
|
||||
ShouldCompress(*http.Request) bool
|
||||
}
|
||||
|
||||
// defaultExtensions is the list of default extensions for which to enable gzipping.
|
||||
var defaultExtensions = []string{"", ".txt", ".htm", ".html", ".css", ".php", ".js", ".json",
|
||||
".md", ".mdown", ".xml", ".svg", ".go", ".cgi", ".py", ".pl", ".aspx", ".asp"}
|
||||
|
||||
// DefaultExtFilter creates an ExtFilter with default extensions.
|
||||
func DefaultExtFilter() ExtFilter {
|
||||
m := ExtFilter{Exts: make(Set)}
|
||||
for _, extension := range defaultExtensions {
|
||||
m.Exts.Add(extension)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// ExtFilter is RequestFilter for file name extensions.
|
||||
type ExtFilter struct {
|
||||
// Exts is the file name extensions to accept
|
||||
Exts Set
|
||||
}
|
||||
|
||||
// ExtWildCard is the wildcard for extensions.
|
||||
const ExtWildCard = "*"
|
||||
|
||||
// ShouldCompress checks if the request file extension matches any
|
||||
// of the registered extensions. It returns true if the extension is
|
||||
// found and false otherwise.
|
||||
func (e ExtFilter) ShouldCompress(r *http.Request) bool {
|
||||
ext := path.Ext(r.URL.Path)
|
||||
return e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)
|
||||
}
|
||||
|
||||
// PathFilter is RequestFilter for request path.
|
||||
type PathFilter struct {
|
||||
// IgnoredPaths is the paths to ignore
|
||||
IgnoredPaths Set
|
||||
}
|
||||
|
||||
// ShouldCompress checks if the request path matches any of the
|
||||
// registered paths to ignore. It returns false if an ignored path
|
||||
// is found and true otherwise.
|
||||
func (p PathFilter) ShouldCompress(r *http.Request) bool {
|
||||
return !p.IgnoredPaths.ContainsFunc(func(value string) bool {
|
||||
return httpserver.Path(r.URL.Path).Matches(value)
|
||||
})
|
||||
}
|
||||
|
||||
// Set stores distinct strings.
|
||||
type Set map[string]struct{}
|
||||
|
||||
// Add adds an element to the set.
|
||||
func (s Set) Add(value string) {
|
||||
s[value] = struct{}{}
|
||||
}
|
||||
|
||||
// Remove removes an element from the set.
|
||||
func (s Set) Remove(value string) {
|
||||
delete(s, value)
|
||||
}
|
||||
|
||||
// Contains check if the set contains value.
|
||||
func (s Set) Contains(value string) bool {
|
||||
_, ok := s[value]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ContainsFunc is similar to Contains. It iterates all the
|
||||
// elements in the set and passes each to f. It returns true
|
||||
// on the first call to f that returns true and false otherwise.
|
||||
func (s Set) ContainsFunc(f func(string) bool) bool {
|
||||
for k := range s {
|
||||
if f(k) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package gzip
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSet(t *testing.T) {
|
||||
set := make(Set)
|
||||
set.Add("a")
|
||||
if len(set) != 1 {
|
||||
t.Errorf("Expected 1 found %v", len(set))
|
||||
}
|
||||
set.Add("a")
|
||||
if len(set) != 1 {
|
||||
t.Errorf("Expected 1 found %v", len(set))
|
||||
}
|
||||
set.Add("b")
|
||||
if len(set) != 2 {
|
||||
t.Errorf("Expected 2 found %v", len(set))
|
||||
}
|
||||
if !set.Contains("a") {
|
||||
t.Errorf("Set should contain a")
|
||||
}
|
||||
if !set.Contains("b") {
|
||||
t.Errorf("Set should contain a")
|
||||
}
|
||||
set.Add("c")
|
||||
if len(set) != 3 {
|
||||
t.Errorf("Expected 3 found %v", len(set))
|
||||
}
|
||||
if !set.Contains("c") {
|
||||
t.Errorf("Set should contain c")
|
||||
}
|
||||
set.Remove("a")
|
||||
if len(set) != 2 {
|
||||
t.Errorf("Expected 2 found %v", len(set))
|
||||
}
|
||||
if set.Contains("a") {
|
||||
t.Errorf("Set should not contain a")
|
||||
}
|
||||
if !set.ContainsFunc(func(v string) bool {
|
||||
return v == "c"
|
||||
}) {
|
||||
t.Errorf("ContainsFunc should return true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtFilter(t *testing.T) {
|
||||
var filter RequestFilter = ExtFilter{make(Set)}
|
||||
for _, e := range []string{".txt", ".html", ".css", ".md"} {
|
||||
filter.(ExtFilter).Exts.Add(e)
|
||||
}
|
||||
r := urlRequest("file.txt")
|
||||
if !filter.ShouldCompress(r) {
|
||||
t.Errorf("Should be valid filter")
|
||||
}
|
||||
var exts = []string{
|
||||
".html", ".css", ".md",
|
||||
}
|
||||
for i, e := range exts {
|
||||
r := urlRequest("file" + e)
|
||||
if !filter.ShouldCompress(r) {
|
||||
t.Errorf("Test %v: Should be valid filter", i)
|
||||
}
|
||||
}
|
||||
exts = []string{
|
||||
".htm1", ".abc", ".mdx",
|
||||
}
|
||||
for i, e := range exts {
|
||||
r := urlRequest("file" + e)
|
||||
if filter.ShouldCompress(r) {
|
||||
t.Errorf("Test %v: Should not be valid filter", i)
|
||||
}
|
||||
}
|
||||
filter.(ExtFilter).Exts.Add(ExtWildCard)
|
||||
for i, e := range exts {
|
||||
r := urlRequest("file" + e)
|
||||
if !filter.ShouldCompress(r) {
|
||||
t.Errorf("Test %v: Should be valid filter. Wildcard used.", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathFilter(t *testing.T) {
|
||||
paths := []string{
|
||||
"/a", "/b", "/c", "/de",
|
||||
}
|
||||
var filter RequestFilter = PathFilter{make(Set)}
|
||||
for _, p := range paths {
|
||||
filter.(PathFilter).IgnoredPaths.Add(p)
|
||||
}
|
||||
for i, p := range paths {
|
||||
r := urlRequest(p)
|
||||
if filter.ShouldCompress(r) {
|
||||
t.Errorf("Test %v: Should not be valid filter", i)
|
||||
}
|
||||
}
|
||||
paths = []string{
|
||||
"/f", "/g", "/h", "/ed",
|
||||
}
|
||||
for i, p := range paths {
|
||||
r := urlRequest(p)
|
||||
if !filter.ShouldCompress(r) {
|
||||
t.Errorf("Test %v: Should be valid filter", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func urlRequest(url string) *http.Request {
|
||||
r, _ := http.NewRequest("GET", url, nil)
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package gzip
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ResponseFilter determines if the response should be gzipped.
|
||||
type ResponseFilter interface {
|
||||
ShouldCompress(http.ResponseWriter) bool
|
||||
}
|
||||
|
||||
// LengthFilter is ResponseFilter for minimum content length.
|
||||
type LengthFilter int64
|
||||
|
||||
// ShouldCompress returns if content length is greater than or
|
||||
// equals to minimum length.
|
||||
func (l LengthFilter) ShouldCompress(w http.ResponseWriter) bool {
|
||||
contentLength := w.Header().Get("Content-Length")
|
||||
length, err := strconv.ParseInt(contentLength, 10, 64)
|
||||
if err != nil || length == 0 {
|
||||
return false
|
||||
}
|
||||
return l != 0 && int64(l) <= length
|
||||
}
|
||||
|
||||
// SkipCompressedFilter is ResponseFilter that will discard already compressed responses
|
||||
type SkipCompressedFilter struct{}
|
||||
|
||||
// ShouldCompress returns true if served file is not already compressed
|
||||
// encodings via https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
|
||||
func (n SkipCompressedFilter) ShouldCompress(w http.ResponseWriter) bool {
|
||||
switch w.Header().Get("Content-Encoding") {
|
||||
case "gzip", "compress", "deflate", "br":
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// ResponseFilterWriter validates ResponseFilters. It writes
|
||||
// gzip compressed data if ResponseFilters are satisfied or
|
||||
// uncompressed data otherwise.
|
||||
type ResponseFilterWriter struct {
|
||||
filters []ResponseFilter
|
||||
shouldCompress bool
|
||||
statusCodeWritten bool
|
||||
*gzipResponseWriter
|
||||
}
|
||||
|
||||
// NewResponseFilterWriter creates and initializes a new ResponseFilterWriter.
|
||||
func NewResponseFilterWriter(filters []ResponseFilter, gz *gzipResponseWriter) *ResponseFilterWriter {
|
||||
return &ResponseFilterWriter{filters: filters, gzipResponseWriter: gz}
|
||||
}
|
||||
|
||||
// WriteHeader wraps underlying WriteHeader method and
|
||||
// compresses if filters are satisfied.
|
||||
func (r *ResponseFilterWriter) WriteHeader(code int) {
|
||||
// Determine if compression should be used or not.
|
||||
r.shouldCompress = true
|
||||
for _, filter := range r.filters {
|
||||
if !filter.ShouldCompress(r) {
|
||||
r.shouldCompress = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if r.shouldCompress {
|
||||
// replace discard writer with ResponseWriter
|
||||
if gzWriter, ok := r.gzipResponseWriter.Writer.(*gzip.Writer); ok {
|
||||
gzWriter.Reset(r.ResponseWriter)
|
||||
}
|
||||
// use gzip WriteHeader to include and delete
|
||||
// necessary headers
|
||||
r.gzipResponseWriter.WriteHeader(code)
|
||||
} else {
|
||||
r.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
r.statusCodeWritten = true
|
||||
}
|
||||
|
||||
// Write wraps underlying Write method and compresses if filters
|
||||
// are satisfied
|
||||
func (r *ResponseFilterWriter) Write(b []byte) (int, error) {
|
||||
if !r.statusCodeWritten {
|
||||
r.WriteHeader(http.StatusOK)
|
||||
}
|
||||
if r.shouldCompress {
|
||||
return r.gzipResponseWriter.Write(b)
|
||||
}
|
||||
return r.ResponseWriter.Write(b)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package gzip
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestLengthFilter(t *testing.T) {
|
||||
var filters = []ResponseFilter{
|
||||
LengthFilter(100),
|
||||
LengthFilter(1000),
|
||||
LengthFilter(0),
|
||||
}
|
||||
|
||||
var tests = []struct {
|
||||
length int64
|
||||
shouldCompress [3]bool
|
||||
}{
|
||||
{20, [3]bool{false, false, false}},
|
||||
{50, [3]bool{false, false, false}},
|
||||
{100, [3]bool{true, false, false}},
|
||||
{500, [3]bool{true, false, false}},
|
||||
{1000, [3]bool{true, true, false}},
|
||||
{1500, [3]bool{true, true, false}},
|
||||
}
|
||||
|
||||
for i, ts := range tests {
|
||||
for j, filter := range filters {
|
||||
r := httptest.NewRecorder()
|
||||
r.Header().Set("Content-Length", fmt.Sprint(ts.length))
|
||||
wWriter := NewResponseFilterWriter([]ResponseFilter{filter}, &gzipResponseWriter{gzip.NewWriter(r), r, false})
|
||||
if filter.ShouldCompress(wWriter) != ts.shouldCompress[j] {
|
||||
t.Errorf("Test %v: Expected %v found %v", i, ts.shouldCompress[j], filter.ShouldCompress(r))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponseFilterWriter(t *testing.T) {
|
||||
tests := []struct {
|
||||
body string
|
||||
shouldCompress bool
|
||||
}{
|
||||
{"Hello\t\t\t\n", false},
|
||||
{"Hello the \t\t\t world is\n\n\n great", true},
|
||||
{"Hello \t\t\nfrom gzip", true},
|
||||
{"Hello gzip\n", false},
|
||||
}
|
||||
|
||||
filters := []ResponseFilter{
|
||||
LengthFilter(15),
|
||||
}
|
||||
|
||||
server := Gzip{Configs: []Config{
|
||||
{ResponseFilters: filters},
|
||||
}}
|
||||
|
||||
for i, ts := range tests {
|
||||
server.Next = httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
w.Header().Set("Content-Length", fmt.Sprint(len(ts.body)))
|
||||
w.Write([]byte(ts.body))
|
||||
return 200, nil
|
||||
})
|
||||
|
||||
r := urlRequest("/")
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
server.ServeHTTP(w, r)
|
||||
|
||||
resp := w.Body.String()
|
||||
|
||||
if !ts.shouldCompress {
|
||||
if resp != ts.body {
|
||||
t.Errorf("Test %v: No compression expected, found %v", i, resp)
|
||||
}
|
||||
} else {
|
||||
if resp == ts.body {
|
||||
t.Errorf("Test %v: Compression expected, found %v", i, resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponseGzippedOutput(t *testing.T) {
|
||||
server := Gzip{Configs: []Config{
|
||||
{ResponseFilters: []ResponseFilter{SkipCompressedFilter{}}},
|
||||
}}
|
||||
|
||||
server.Next = httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
w.Write([]byte("gzipped"))
|
||||
return 200, nil
|
||||
})
|
||||
|
||||
r := urlRequest("/")
|
||||
r.Header.Set("Accept-Encoding", "gzip")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
server.ServeHTTP(w, r)
|
||||
resp := w.Body.String()
|
||||
|
||||
if resp != "gzipped" {
|
||||
t.Errorf("Expected output not to be gzipped")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package gzip
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// setup configures a new gzip middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
configs, err := gzipParse(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
return Gzip{Next: next, Configs: configs}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func gzipParse(c *caddy.Controller) ([]Config, error) {
|
||||
var configs []Config
|
||||
|
||||
for c.Next() {
|
||||
config := Config{}
|
||||
|
||||
// Request Filters
|
||||
pathFilter := PathFilter{IgnoredPaths: make(Set)}
|
||||
extFilter := ExtFilter{Exts: make(Set)}
|
||||
|
||||
// Response Filters
|
||||
lengthFilter := LengthFilter(0)
|
||||
|
||||
// No extra args expected
|
||||
if len(c.RemainingArgs()) > 0 {
|
||||
return configs, c.ArgErr()
|
||||
}
|
||||
|
||||
for c.NextBlock() {
|
||||
switch c.Val() {
|
||||
case "ext":
|
||||
exts := c.RemainingArgs()
|
||||
if len(exts) == 0 {
|
||||
return configs, c.ArgErr()
|
||||
}
|
||||
for _, e := range exts {
|
||||
if !strings.HasPrefix(e, ".") && e != ExtWildCard && e != "" {
|
||||
return configs, fmt.Errorf(`gzip: invalid extension "%v" (must start with dot)`, e)
|
||||
}
|
||||
extFilter.Exts.Add(e)
|
||||
}
|
||||
case "not":
|
||||
paths := c.RemainingArgs()
|
||||
if len(paths) == 0 {
|
||||
return configs, c.ArgErr()
|
||||
}
|
||||
for _, p := range paths {
|
||||
if p == "/" {
|
||||
return configs, fmt.Errorf(`gzip: cannot exclude path "/" - remove directive entirely instead`)
|
||||
}
|
||||
if !strings.HasPrefix(p, "/") {
|
||||
return configs, fmt.Errorf(`gzip: invalid path "%v" (must start with /)`, p)
|
||||
}
|
||||
pathFilter.IgnoredPaths.Add(p)
|
||||
}
|
||||
case "level":
|
||||
if !c.NextArg() {
|
||||
return configs, c.ArgErr()
|
||||
}
|
||||
level, _ := strconv.Atoi(c.Val())
|
||||
config.Level = level
|
||||
case "min_length":
|
||||
if !c.NextArg() {
|
||||
return configs, c.ArgErr()
|
||||
}
|
||||
length, err := strconv.ParseInt(c.Val(), 10, 64)
|
||||
if err != nil {
|
||||
return configs, err
|
||||
} else if length == 0 {
|
||||
return configs, fmt.Errorf(`gzip: min_length must be greater than 0`)
|
||||
}
|
||||
lengthFilter = LengthFilter(length)
|
||||
default:
|
||||
return configs, c.ArgErr()
|
||||
}
|
||||
}
|
||||
|
||||
// Request Filters
|
||||
config.RequestFilters = []RequestFilter{}
|
||||
|
||||
// If ignored paths are specified, put in front to filter with path first
|
||||
if len(pathFilter.IgnoredPaths) > 0 {
|
||||
config.RequestFilters = []RequestFilter{pathFilter}
|
||||
}
|
||||
|
||||
// Then, if extensions are specified, use those to filter.
|
||||
// Otherwise, use default extensions filter.
|
||||
if len(extFilter.Exts) > 0 {
|
||||
config.RequestFilters = append(config.RequestFilters, extFilter)
|
||||
} else {
|
||||
config.RequestFilters = append(config.RequestFilters, DefaultExtFilter())
|
||||
}
|
||||
|
||||
config.ResponseFilters = append(config.ResponseFilters, SkipCompressedFilter{})
|
||||
|
||||
// Response Filters
|
||||
// If min_length is specified, use it.
|
||||
if int64(lengthFilter) != 0 {
|
||||
config.ResponseFilters = append(config.ResponseFilters, lengthFilter)
|
||||
}
|
||||
|
||||
configs = append(configs, config)
|
||||
}
|
||||
|
||||
return configs, nil
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package gzip
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `gzip`)
|
||||
err := setup(c)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no errors, but got: %v", err)
|
||||
}
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
if mids == nil {
|
||||
t.Fatal("Expected middleware, was nil instead")
|
||||
}
|
||||
|
||||
handler := mids[0](httpserver.EmptyNext)
|
||||
myHandler, ok := handler.(Gzip)
|
||||
if !ok {
|
||||
t.Fatalf("Expected handler to be type Gzip, got: %#v", handler)
|
||||
}
|
||||
|
||||
if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
|
||||
t.Error("'Next' field of handler was not set properly")
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
input string
|
||||
shouldErr bool
|
||||
}{
|
||||
{`gzip {`, true},
|
||||
{`gzip {}`, true},
|
||||
{`gzip a b`, true},
|
||||
{`gzip a {`, true},
|
||||
{`gzip { not f } `, true},
|
||||
{`gzip { not } `, true},
|
||||
{`gzip { not /file
|
||||
ext .html
|
||||
level 1
|
||||
} `, false},
|
||||
{`gzip { level 9 } `, false},
|
||||
{`gzip { ext } `, true},
|
||||
{`gzip { ext /f
|
||||
} `, true},
|
||||
{`gzip { not /file
|
||||
ext .html
|
||||
level 1
|
||||
}
|
||||
gzip`, false},
|
||||
{`gzip {
|
||||
ext ""
|
||||
}`, false},
|
||||
{`gzip { not /file
|
||||
ext .html
|
||||
level 1
|
||||
}
|
||||
gzip { not /file1
|
||||
ext .htm
|
||||
level 3
|
||||
}
|
||||
`, false},
|
||||
{`gzip { not /file
|
||||
ext .html
|
||||
level 1
|
||||
}
|
||||
gzip { not /file1
|
||||
ext .htm
|
||||
level 3
|
||||
}
|
||||
`, false},
|
||||
{`gzip { not /file
|
||||
ext *
|
||||
level 1
|
||||
}
|
||||
`, false},
|
||||
{`gzip { not /file
|
||||
ext *
|
||||
level 1
|
||||
min_length ab
|
||||
}
|
||||
`, true},
|
||||
{`gzip { not /file
|
||||
ext *
|
||||
level 1
|
||||
min_length 1000
|
||||
}
|
||||
`, false},
|
||||
}
|
||||
for i, test := range tests {
|
||||
_, err := gzipParse(caddy.NewTestController("http", test.input))
|
||||
if test.shouldErr && err == nil {
|
||||
t.Errorf("Test %v: Expected error but found nil", i)
|
||||
} else if !test.shouldErr && err != nil {
|
||||
t.Errorf("Test %v: Expected no error but found error: %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldAddResponseFilters(t *testing.T) {
|
||||
configs, err := gzipParse(caddy.NewTestController("http", `gzip { min_length 654 }`))
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Test expected no error but found: %v", err)
|
||||
}
|
||||
filters := 0
|
||||
|
||||
for _, config := range configs {
|
||||
for _, filter := range config.ResponseFilters {
|
||||
switch filter.(type) {
|
||||
case SkipCompressedFilter:
|
||||
filters++
|
||||
case LengthFilter:
|
||||
filters++
|
||||
|
||||
if filter != LengthFilter(654) {
|
||||
t.Errorf("Expected LengthFilter to have length 654, got: %v", filter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if filters != 2 {
|
||||
t.Errorf("Expected 2 response filters to be registered, got: %v", filters)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+199
@@ -0,0 +1,199 @@
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis, dolor et feugiat suscipit, nisi urna consectetur enim, et porta libero dui eget dolor. Sed ac enim aliquet, ornare ipsum a, aliquet augue. Fusce faucibus id mi at porta. Donec scelerisque consectetur rutrum. In aliquam est vel quam molestie porttitor. Sed eget nunc blandit, commodo dui ac, tempus mi. Nulla ac est ac leo hendrerit rhoncus. Etiam id finibus neque. In ultrices diam orci, eu tempor neque bibendum sed. Fusce facilisis mauris in finibus elementum. Pellentesque tristique bibendum diam, nec molestie velit facilisis quis. Nulla facilisi. Morbi nec velit eget massa blandit consequat sed hendrerit velit. Ut euismod elit sit amet dui venenatis, a luctus tortor vestibulum.
|
||||
|
||||
Aliquam consequat rutrum sagittis. Donec eros felis, ultricies quis elementum nec, consequat et ex. Nullam feugiat eu sapien nec mollis. Quisque porttitor tortor ipsum, quis aliquam diam tincidunt a. Praesent tortor lorem, finibus sit amet tempor ac, iaculis et nunc. Duis enim justo, gravida in pharetra id, rhoncus id nisi. Maecenas dui risus, accumsan ut nisi vitae, placerat dignissim risus. Quisque orci lectus, sodales a lacus sit amet, bibendum gravida odio. Duis consectetur, ante et vulputate convallis, augue augue mollis ligula, sed tincidunt nunc ligula vel enim. Donec faucibus pulvinar consectetur. Nam laoreet, dolor ac elementum vestibulum, eros justo fringilla leo, pretium fringilla sem nunc non sem. Proin at nisl eget leo hendrerit lacinia.
|
||||
|
||||
Aliquam id lacus mauris. Morbi et justo urna. Vestibulum venenatis pharetra lectus in pharetra. Fusce feugiat nisl nec enim rutrum finibus. Etiam a nunc metus. Phasellus non dignissim eros, non feugiat quam. Nunc velit ante, commodo at ex eu, fringilla semper tellus.
|
||||
|
||||
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam rhoncus ultricies nisl, id vestibulum dolor eleifend id. Quisque condimentum condimentum nisi, at dapibus sapien pharetra ut. Suspendisse a sodales odio, sit amet facilisis risus. Vestibulum varius pretium pellentesque. Nunc sit amet sollicitudin sapien, eu finibus mi. Aenean justo arcu, ornare id massa et, auctor dictum dui. Morbi et aliquet velit.
|
||||
|
||||
Curabitur leo ligula, congue non tincidunt vel, consectetur at erat. In scelerisque orci in cursus molestie. Duis erat erat, vehicula sed sollicitudin eget, suscipit in erat. Quisque sed quam in ante dictum hendrerit. Aenean elementum mattis ipsum, sollicitudin luctus felis. Duis fringilla varius mattis. Integer dapibus efficitur blandit.
|
||||
|
||||
Vivamus placerat enim vel est feugiat, cursus pretium ante aliquam. Curabitur hendrerit iaculis odio, in tristique nisl rutrum non. Aenean varius luctus ipsum quis interdum. Nam suscipit purus et lacus accumsan, a rutrum turpis mattis. Sed non bibendum mi. Pellentesque pulvinar ligula eget massa feugiat pharetra. Sed malesuada sem metus, sit amet feugiat purus pretium vel. Fusce magna est, fermentum vitae mauris vel, elementum pharetra est. In blandit faucibus tortor in elementum. Maecenas vitae ornare dui, quis commodo orci. Pellentesque sed scelerisque dolor. Aliquam eget libero in risus tempor efficitur vitae sit amet libero. Sed sed eros dapibus, consectetur mauris eget, auctor mauris.
|
||||
|
||||
Quisque sed efficitur dui. Suspendisse tempor maximus varius. Vivamus tristique volutpat orci, sed placerat ligula condimentum in. Aliquam sodales mi interdum diam semper pulvinar. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum faucibus facilisis leo, eget suscipit urna luctus nec. Integer posuere gravida nibh in imperdiet. Nunc ultrices in lorem vel volutpat. Morbi laoreet augue id dapibus porta. Pellentesque ac convallis lectus. Proin placerat lorem sed lacus blandit rhoncus.
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mattis in nunc id scelerisque. Donec et elit ac odio blandit euismod. Mauris enim risus, fermentum ac accumsan in, rhoncus sed erat. Donec sed laoreet eros. In ut purus sed nunc consequat pretium sit amet in nibh. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aenean at semper nisl. Quisque vel lectus ut felis pellentesque imperdiet.
|
||||
|
||||
Maecenas eget lacinia mi. Vivamus eget sollicitudin tortor. Pellentesque molestie, massa in bibendum ultrices, nunc mauris finibus ex, non porttitor enim leo ac dolor. Vivamus dapibus nisl dui, sit amet convallis ipsum dictum ac. Nulla facilisi. Curabitur laoreet auctor sapien, at porttitor urna scelerisque sit amet. Ut placerat neque congue vulputate ullamcorper. Nunc ut sem tristique, volutpat sem at, commodo augue. Ut facilisis pulvinar vestibulum.
|
||||
|
||||
Duis volutpat eros laoreet, fringilla nulla eu, congue lorem. Fusce vestibulum bibendum ornare. Donec venenatis nisi at augue suscipit, vel cursus massa bibendum. Fusce facilisis nisl ut volutpat tempus. Fusce porttitor ante mauris, et bibendum sapien tincidunt non. In rhoncus tincidunt fermentum. Morbi id venenatis nunc. Maecenas blandit suscipit porta. Proin porttitor molestie nibh. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
|
||||
|
||||
Phasellus sed nulla nisi. Proin mollis hendrerit felis, ultricies sollicitudin mi semper eget. Fusce at neque at justo vehicula rhoncus a gravida lectus. Cras tristique eget arcu nec fringilla. Nam sit amet dolor mollis, fermentum lorem at, faucibus erat. Morbi eu urna laoreet, faucibus purus et, accumsan neque. Maecenas eget velit lorem. Sed eu est elementum, sagittis elit id, scelerisque elit. Nunc elementum fermentum sem, id viverra mauris viverra at. Sed molestie mi sed velit vestibulum, sit amet porttitor tellus dictum. Fusce rhoncus felis et molestie iaculis. Cras ornare eget urna non pulvinar. Pellentesque ultricies leo quis dignissim sollicitudin. Nunc elit mi, bibendum eu tellus quis, pellentesque dapibus erat.
|
||||
|
||||
Morbi blandit sit amet sem sed fringilla. Ut quis augue egestas, pharetra sapien at, tincidunt neque. Aliquam sodales, justo et tincidunt posuere, nunc lacus tincidunt lectus, non iaculis sem arcu nec diam. Nullam lobortis lorem at quam euismod, non elementum eros vulputate. Vivamus gravida non libero ac tristique. Morbi sit amet lectus elementum, malesuada diam a, pharetra odio. Phasellus non erat ipsum. Phasellus ullamcorper feugiat nunc, ut porta mauris feugiat eu. Ut egestas ligula dolor, ac mollis massa rhoncus at. Donec maximus pulvinar est non eleifend. Quisque vulputate turpis sed ligula accumsan tincidunt. Cras tortor augue, aliquam sed pretium vel, semper sit amet nisi. Pellentesque gravida dapibus libero porta viverra. Donec lacinia, ante et porta mollis, lorem est feugiat odio, vitae sollicitudin augue ipsum ac mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
|
||||
|
||||
Phasellus non mauris consequat, congue metus at, sodales quam. Phasellus imperdiet et elit quis rhoncus. Phasellus aliquet euismod ligula quis elementum. Etiam sed nibh arcu. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed enim sem, pulvinar quis elit non, dignissim rhoncus mi. Quisque vitae ullamcorper enim, vitae varius lacus. Nunc hendrerit augue quis volutpat bibendum. Nulla ultricies justo sit amet lorem dignissim interdum. Duis congue, mauris vel posuere ornare, lacus justo accumsan ex, a malesuada arcu orci sit amet risus. Sed at nisl non massa sollicitudin convallis at in erat. Ut imperdiet, eros at hendrerit maximus, lacus orci molestie dolor, vitae aliquam ligula lacus eget mi. Sed massa purus, sagittis sed sollicitudin nec, condimentum eget metus. Sed commodo nunc in nibh auctor, a pellentesque nisl pretium. Vivamus ac ex sit amet libero posuere malesuada. Interdum et malesuada fames ac ante ipsum primis in faucibus.
|
||||
|
||||
Praesent molestie est et pulvinar placerat. Sed tincidunt sapien eu justo vulputate rutrum. Donec vel ultrices erat. Morbi quis rhoncus metus. Cras pellentesque augue quis auctor eleifend. Suspendisse quis commodo quam. Etiam dapibus metus nec tortor pharetra lobortis. Quisque pharetra lectus ac velit commodo, nec blandit nisl viverra. Pellentesque aliquet tincidunt molestie. Vestibulum ullamcorper, eros eu posuere varius, metus enim rutrum elit, quis fringilla orci tellus at odio. Ut malesuada, justo vitae lobortis porta, nisi magna dictum metus, sed porta arcu turpis vitae tortor. Morbi in elit sapien.
|
||||
|
||||
Maecenas quis feugiat augue. Integer sollicitudin dolor sit amet mi dictum, non consequat turpis scelerisque. Aliquam erat volutpat. Aliquam venenatis mollis orci, nec sollicitudin elit convallis quis. Vivamus varius, libero a sagittis lobortis, massa massa suscipit neque, lacinia lacinia ante justo non massa. Quisque ut erat ac purus euismod consequat. Phasellus malesuada elementum ipsum sed rutrum. Vivamus scelerisque erat vel nisl tempus euismod id eget arcu.
|
||||
|
||||
Ut fermentum dapibus finibus. Praesent aliquam magna tellus, et pulvinar ipsum dignissim volutpat. Ut mollis diam eros, lacinia euismod lectus venenatis in. Sed lobortis eros massa, at vulputate ipsum hendrerit ac. Aenean id commodo sapien, id suscipit metus. Ut fringilla quam laoreet posuere pretium. Donec vel dapibus nibh. Donec non neque felis. Sed consequat efficitur semper. In ac porta mi. Fusce non elit urna. Aenean pharetra urna laoreet enim malesuada, vitae feugiat nibh molestie. Nam varius porta arcu non convallis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam tempus ex et quam accumsan sodales. Aliquam eget metus ac est accumsan ultrices.
|
||||
|
||||
Nullam eleifend mauris ac maximus scelerisque. Integer nec sapien massa. Ut laoreet, nibh non egestas congue, enim metus mollis mi, sit amet sodales dolor diam sed augue. Vestibulum dignissim metus at felis faucibus faucibus. Pellentesque molestie nisi viverra quam tincidunt, ut molestie est feugiat. Sed nulla tortor, gravida quis varius sed, commodo sit amet arcu. Curabitur viverra, lacus at placerat vestibulum, ligula orci semper ipsum, et mollis mi erat a ligula. Pellentesque ornare urna eu lorem blandit vestibulum. Mauris quis rutrum justo. Vivamus non sollicitudin odio. Curabitur ornare ante vitae justo mollis efficitur.
|
||||
|
||||
Suspendisse interdum bibendum lobortis. Etiam commodo gravida sollicitudin. Curabitur interdum vel nisi a auctor. Nunc varius dui in aliquam porttitor. Nam consequat mi enim, sed tempor eros scelerisque eu. Proin auctor, enim nec imperdiet mollis, dui magna blandit tellus, non elementum orci lorem vitae odio. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec laoreet cursus risus. Curabitur porta massa vitae lorem posuere, non tristique mauris lacinia. Ut ligula nisl, pulvinar eget ligula eu, suscipit hendrerit ligula.
|
||||
|
||||
Maecenas elementum justo quis odio vestibulum ullamcorper. Quisque commodo non odio quis vehicula. Ut vel ornare erat. Duis quis tristique tellus. Suspendisse dignissim aliquet purus sed consectetur. Cras in sollicitudin lectus. Donec posuere venenatis efficitur. Nullam ac pellentesque mi.
|
||||
|
||||
Etiam malesuada ut tellus nec sodales. Cras malesuada eu arcu quis tincidunt. Sed consequat malesuada eleifend. Aenean accumsan vel ligula efficitur elementum. Sed elementum sapien nec magna iaculis pharetra. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed in augue sit amet sem malesuada facilisis at ac risus. Aliquam aliquam dignissim mauris vel pharetra. In hac habitasse platea dictumst. Phasellus varius risus id urna pretium, fermentum tristique lorem condimentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum tincidunt eu dolor at vehicula. Proin pulvinar ex non gravida venenatis. Donec lacinia, ipsum in congue hendrerit, risus turpis elementum elit, eget tempor purus lorem ut sapien. Maecenas dapibus eros eget viverra imperdiet. Donec ullamcorper nulla hendrerit molestie rutrum.
|
||||
|
||||
Duis maximus molestie pellentesque. Duis mattis hendrerit dolor, et vulputate turpis pretium ut. Aliquam porta elit in pretium faucibus. Vivamus tortor nunc, elementum nec cursus facilisis, consequat ac elit. Suspendisse porttitor lobortis sollicitudin. Curabitur auctor velit ac gravida feugiat. Praesent convallis tempor nulla, id sodales eros ullamcorper eget. Praesent blandit massa quis placerat molestie. Integer elementum lacinia fermentum. Phasellus ullamcorper mattis finibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur diam quam, egestas nec arcu vitae, efficitur pellentesque nisl. Curabitur a dui vitae metus vehicula condimentum vel sit amet dolor. Vestibulum vehicula dictum semper. Sed vitae aliquet odio.
|
||||
|
||||
Etiam quis purus molestie, finibus nisi aliquam, venenatis nunc. Phasellus tempor id erat sed mattis. Praesent at facilisis diam. In tortor turpis, eleifend vitae facilisis sit amet, ultrices ut nibh. Cras placerat mollis risus, nec accumsan massa aliquam eu. Aliquam erat volutpat. Aliquam tincidunt, leo in laoreet viverra, metus sapien convallis justo, ut pellentesque massa est sit amet ligula. Suspendisse et arcu justo. Quisque at luctus urna. Vestibulum elit eros, dapibus at faucibus sit amet, dapibus a sem. Donec nec mi pulvinar, luctus nisi quis, sollicitudin mauris. Phasellus id velit a enim vehicula eleifend.
|
||||
|
||||
Sed volutpat vel eros sit amet efficitur. Nullam ut neque lobortis, rutrum dui at, blandit massa. Vivamus quis commodo mi. Praesent ultrices lacinia consectetur. Phasellus nec imperdiet augue, eget eleifend arcu. Morbi viverra a sapien vel eleifend. Pellentesque in volutpat sapien. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque facilisis metus a nulla fermentum sollicitudin. Nam hendrerit risus eget purus bibendum ultricies eu commodo leo. Nulla placerat feugiat massa nec efficitur. Nam quis mattis erat, vel porta ex.
|
||||
|
||||
Fusce ullamcorper nibh velit. Praesent porttitor dignissim eros, nec fermentum tellus pellentesque sit amet. Suspendisse potenti. Suspendisse eget quam in lorem sollicitudin porttitor sed a arcu. Cras eget ligula venenatis, posuere sem ac, semper leo. Nam dictum ipsum at leo convallis finibus. Nam a lorem consectetur, ullamcorper nulla ut, posuere sapien. Quisque quis vulputate enim, sit amet consectetur tellus. Integer in massa sed diam mattis imperdiet non a velit. Maecenas consectetur posuere erat, sed cursus dui pretium sed. Etiam at pellentesque mi. Aliquam pharetra rutrum rhoncus.
|
||||
|
||||
Proin finibus luctus leo, at iaculis arcu. Pellentesque ullamcorper ligula sapien, quis tempor velit bibendum ac. Fusce vestibulum posuere purus, quis efficitur diam venenatis quis. Sed posuere arcu ut diam varius laoreet. Integer non eros id odio finibus eleifend. Mauris vulputate arcu non sem placerat, vel sodales dolor accumsan. Phasellus felis elit, viverra nec congue ac, pretium in ante. Fusce ut ex eu massa rutrum dictum id sit amet lectus. Duis venenatis ligula erat, eu congue enim gravida suscipit. Pellentesque luctus eget sem eu luctus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean dignissim suscipit hendrerit.
|
||||
|
||||
Vivamus vel dui ac leo maximus efficitur eget iaculis nisl. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent et elit ultrices, aliquet diam sed, placerat lorem. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed lectus ex, elementum pretium sem nec, tincidunt tincidunt felis. Ut viverra neque mi, vitae convallis dolor tempor vel. Nam eleifend non erat id cursus.
|
||||
|
||||
In euismod scelerisque auctor. Fusce ligula nunc, dictum non euismod nec, ultricies eget sapien. Fusce ultrices in ipsum non vehicula. Nunc a elit a mauris dapibus ullamcorper quis ac neque. Integer vel commodo eros, nec tincidunt mi. Maecenas mi augue, congue a condimentum a, gravida non tellus. Pellentesque tortor eros, fermentum in nunc non, placerat cursus tortor. Donec malesuada eleifend sem, ac consectetur neque ultricies dictum.
|
||||
|
||||
Pellentesque mattis nulla sed bibendum viverra. Phasellus maximus dolor justo, et aliquam felis ultricies vel. Curabitur aliquet pulvinar elit vitae pulvinar. Praesent sed gravida turpis. Praesent ipsum ipsum, lacinia nec bibendum in, sagittis id felis. Donec nibh neque, aliquet non porttitor vitae, maximus id urna. Pellentesque est libero, placerat in libero et, cursus consectetur felis.
|
||||
|
||||
Donec eget ipsum eu nisl aliquam pharetra. Suspendisse consequat enim mi, lacinia ullamcorper nisi vulputate id. Aliquam finibus ligula tortor, eget varius erat convallis a. Donec sollicitudin rutrum rutrum. Aenean mollis lacinia dictum. Morbi ac tempus arcu, sit amet auctor nunc. Nulla sed est dignissim, dictum sem vitae, tincidunt dolor. Pellentesque nunc ipsum, semper quis eros ut, luctus hendrerit velit. Maecenas risus ipsum, posuere et molestie id, tempor a elit. Etiam aliquam turpis sit amet accumsan vestibulum. Curabitur consectetur erat vel magna sodales, sit amet aliquet metus scelerisque. Proin pretium lacus in commodo efficitur. Pellentesque congue aliquam neque at imperdiet. Suspendisse faucibus, ex quis varius consectetur, sem magna congue ligula, sed fringilla urna ligula a libero. Nullam ut sapien at erat ullamcorper venenatis sit amet eu mauris.
|
||||
|
||||
Praesent ante massa, laoreet eu tortor ut, molestie tristique risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur fermentum vulputate mauris eget sodales. Nunc eleifend leo ac dui efficitur, sit amet volutpat enim semper. Morbi lorem diam, dictum nec felis sed, lobortis tempor nunc. Curabitur dapibus volutpat arcu, eget lacinia ipsum ultricies sed. Fusce hendrerit erat nunc, nec tempus risus pulvinar in. Suspendisse fringilla sagittis ante vel molestie. Suspendisse vulputate sagittis congue. Quisque gravida metus sit amet risus rutrum bibendum. Nullam id ex risus. Aliquam erat volutpat. Nunc vitae tellus id purus scelerisque efficitur. Quisque nulla dui, tempor sed sollicitudin vitae, hendrerit dapibus enim. Nullam tincidunt non est ut lobortis.
|
||||
|
||||
Nunc molestie nisi non vestibulum maximus. Phasellus tincidunt maximus fringilla. Donec justo sem, viverra vel ligula in, ullamcorper mattis odio. Duis commodo urna nec pharetra mollis. Sed vehicula metus et nibh laoreet congue. In tincidunt, metus sit amet pulvinar placerat, arcu quam vestibulum lorem, vel efficitur elit mi at dui. Etiam id congue urna, sit amet tincidunt tellus. Vestibulum euismod magna eget orci semper, in placerat quam congue. Suspendisse eget turpis quis sapien imperdiet sollicitudin. Nullam sodales gravida justo at iaculis. Nunc iaculis leo at orci viverra, in facilisis neque ultricies. Integer gravida neque ut ex sodales posuere. Nullam odio mauris, consectetur ut ultrices eget, porttitor eu tortor. Proin ut risus quis erat tristique ornare non ut est. Nulla dignissim sed ipsum ut sagittis. Curabitur facilisis mattis nunc eget molestie.
|
||||
|
||||
Nam ultrices vitae velit sollicitudin volutpat. Aenean sagittis diam aliquet pretium imperdiet. Donec ultricies nisl a nisi porttitor iaculis. Donec quis tempus purus, in suscipit nibh. Nulla dignissim tristique vulputate. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent egestas sit amet enim at porttitor. Vivamus nec tortor lobortis mauris tempus varius non sed ante. Praesent lorem nisl, blandit ac rutrum at, faucibus eu sem. Nunc arcu nulla, mollis nec eros eget, hendrerit cursus ex. Praesent ut pretium dolor. Vestibulum varius sapien et eleifend commodo. Fusce auctor ut orci a consectetur. Praesent condimentum sit amet elit sit amet sollicitudin.
|
||||
|
||||
In luctus, diam eu ultrices maximus, urna nibh ullamcorper orci, id tempor nibh arcu eu mauris. Phasellus lacus nunc, fringilla eu turpis sed, pharetra ultricies diam. Etiam nisi enim, sagittis et erat non, finibus rhoncus ex. Cras maximus ullamcorper magna, vel tempor lacus venenatis quis. Vivamus fringilla tincidunt purus et maximus. Quisque commodo ullamcorper tellus, eget accumsan massa maximus nec. Curabitur in imperdiet mi. Proin lorem est, pellentesque quis hendrerit at, condimentum non mi. Nulla id ante placerat, dapibus metus nec, hendrerit justo. Praesent pretium, est quis eleifend aliquam, nunc odio convallis mi, vitae dapibus enim sem quis quam. Nulla facilisi.
|
||||
|
||||
Quisque ornare, erat non egestas vulputate, odio massa consequat ex, nec convallis ligula dui at urna. Pellentesque lacinia, est a ornare facilisis, mi leo malesuada nunc, sed tristique ex augue sed magna. Mauris imperdiet pharetra blandit. Etiam eget nisl id massa elementum imperdiet. Nullam tortor leo, volutpat ac nulla id, feugiat pulvinar eros. Pellentesque tempus bibendum felis et luctus. Duis non imperdiet nibh. Sed blandit ex a odio feugiat maximus. Maecenas elementum odio sit amet purus fermentum, ut mattis enim maximus. Proin efficitur lectus enim, nec fringilla velit pharetra quis. Aliquam ligula massa, tincidunt venenatis dolor sit amet, condimentum suscipit nisi. Cras a velit mi. Curabitur id ligula vestibulum, semper erat ut, tincidunt lacus. Nunc egestas urna et velit hendrerit, eu posuere libero sollicitudin. Suspendisse vitae fringilla nunc. Aenean eros ipsum, scelerisque at laoreet sed, mollis vel eros.
|
||||
|
||||
Proin ac placerat nulla. Proin sollicitudin eget dolor eu luctus. Maecenas sit amet ante volutpat, molestie metus sit amet, tempus justo. Cras tellus odio, accumsan vitae urna eget, tempor eleifend turpis. Nulla venenatis posuere lacus congue convallis. Fusce suscipit egestas aliquet. Vivamus condimentum massa eget lacinia finibus. Morbi vitae leo ut eros consequat dapibus.
|
||||
|
||||
Sed vel arcu a lorem posuere placerat in quis purus. Aliquam dapibus libero dui. Etiam in ex diam. Morbi nec nibh ut purus posuere euismod. Sed lobortis neque mauris, ac efficitur arcu venenatis ac. Donec orci purus, accumsan cursus ligula eu, mollis fermentum metus. Donec placerat diam et lorem dignissim, vel varius odio sagittis. Suspendisse potenti. Nam et erat facilisis ex maximus ultricies. Sed non magna nec turpis malesuada vulputate ac in massa.
|
||||
|
||||
Cras ac dignissim purus, quis vehicula tortor. Maecenas vulputate, nisl vel egestas dignissim, nibh elit commodo elit, et maximus elit est vel massa. Vestibulum fermentum, dolor sed pellentesque scelerisque, ligula mauris lacinia lorem, ac commodo elit turpis rhoncus velit. Donec a enim in metus eleifend pharetra et ac elit. Morbi sed pellentesque leo. Nullam fringilla ultricies ante, nec pellentesque massa convallis nec. Maecenas elementum, mi a congue ullamcorper, arcu enim hendrerit enim, vitae fermentum sapien tellus ac sem. Nunc et tempus est. Aliquam lacinia, quam non tempor consequat, lorem lectus mollis nisl, id tempor nisl turpis eu purus. Sed eget maximus diam, convallis hendrerit neque.
|
||||
|
||||
Donec venenatis odio ipsum, in consectetur dui tristique sit amet. Duis placerat neque nec lorem laoreet, et fermentum sapien rutrum. Quisque et diam odio. Phasellus ultrices nibh nec dolor laoreet fringilla. Nulla facilisi. Curabitur pretium erat quam, id facilisis nunc euismod ac. Duis condimentum risus ut vestibulum dapibus. Suspendisse lorem nunc, aliquet quis commodo eu, sagittis a neque. In sodales augue mattis odio sagittis scelerisque. Sed sem purus, commodo nec ornare non, dapibus id enim.
|
||||
|
||||
Mauris urna nisl, consectetur vitae blandit a, posuere a dui. Praesent ut nisl accumsan, vehicula erat a, mattis ligula. Nam metus neque, blandit vel diam a, finibus sagittis orci. Sed metus lorem, congue in tincidunt quis, varius ut lectus. In ultrices augue nec sem bibendum ultricies. Cras a tellus at est gravida tempor vel id risus. Nullam erat nulla, fringilla nec nunc sit amet, placerat ultricies turpis. Sed interdum mi vitae ullamcorper posuere. Proin eu faucibus urna. Mauris maximus, quam a accumsan commodo, justo diam mollis nunc, ac laoreet lacus magna quis nisl. Quisque tincidunt lacus ipsum, ut sagittis elit mattis in. Donec elementum vitae purus ut tristique. Fusce lobortis orci ante, ut bibendum risus imperdiet at.
|
||||
|
||||
Donec dignissim tristique tincidunt. Sed vitae felis justo. Curabitur tincidunt, enim non finibus luctus, elit nunc consectetur libero, sit amet tincidunt odio purus eget quam. Nam tincidunt id metus malesuada feugiat. Vivamus metus quam, posuere quis quam sollicitudin, tincidunt placerat nisi. Aenean nec enim elementum, varius augue id, iaculis urna. Mauris nec risus eu arcu elementum tristique. Nullam ultrices diam eget lorem porta iaculis. Donec fringilla nibh mi, vel auctor enim maximus sed. Vestibulum metus erat, sollicitudin nec pharetra at, sodales vel tellus.
|
||||
|
||||
Phasellus sed erat ac velit faucibus semper ut ut justo. Proin commodo porttitor magna dapibus rutrum. Maecenas placerat neque ac aliquet maximus. Praesent rutrum, felis quis venenatis placerat, tortor ligula porta ipsum, eu dapibus mi urna eget nisl. Proin ultrices vitae ipsum non tristique. Donec convallis massa metus, id mollis felis sollicitudin eu. Nulla gravida nunc id dui bibendum blandit. Suspendisse ut venenatis quam, vitae tempus massa. Quisque tincidunt mi eget erat congue, ac volutpat nunc posuere. Aenean aliquet eros id sapien rhoncus, ac hendrerit urna tincidunt. Morbi vitae euismod nisl, ut accumsan diam. Sed ultricies, tellus nec mollis rhoncus, lacus tellus feugiat est, eu ullamcorper arcu eros nec nulla.
|
||||
|
||||
Donec pretium arcu eget justo efficitur mollis. Vivamus id arcu sit amet mauris congue vulputate sit amet in tellus. Vivamus commodo est libero, et vulputate lorem convallis in. Donec cursus arcu et nibh congue porta. Suspendisse laoreet neque sit amet magna ultrices, consequat scelerisque velit fermentum. Curabitur faucibus lorem faucibus, condimentum sem id, volutpat velit. Donec sed odio dolor. Fusce sodales ligula sit amet pretium hendrerit.
|
||||
|
||||
Mauris ultrices vehicula metus, sed finibus lectus tristique et. Morbi id egestas lacus. Nulla volutpat, lectus et molestie elementum, urna nulla semper massa, at feugiat enim magna quis lacus. Phasellus vitae erat vitae turpis mattis tempus et sed dui. Ut vitae cursus orci. Etiam in massa lectus. Donec purus augue, bibendum sit amet feugiat et, lacinia vitae velit.
|
||||
|
||||
Nulla ac enim tempus, accumsan nunc quis, malesuada quam. Etiam cursus nisi ut aliquam dapibus. Ut vulputate pulvinar ante, id condimentum dui euismod a. Maecenas arcu velit, ornare in nibh eu, feugiat volutpat augue. Duis a diam vitae orci tristique auctor id auctor nisi. Curabitur tincidunt, leo viverra elementum auctor, mi ex efficitur libero, vel aliquet eros mauris sed odio. Nulla consectetur, metus non ullamcorper rutrum, quam eros egestas lacus, vitae luctus odio neque hendrerit nulla. Suspendisse ullamcorper orci massa, non pretium libero dignissim id. Aenean scelerisque justo sapien, quis convallis augue dapibus ut. Aenean ut tincidunt justo. Aenean a lacus lectus.
|
||||
|
||||
Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed sit amet magna eleifend, dictum risus non, dictum turpis. Nam ut quam malesuada, accumsan magna rhoncus, malesuada arcu. In id egestas purus. Nunc nec arcu vel elit vulputate dignissim accumsan sed quam. Suspendisse lacinia ex mattis mi ornare, et maximus ex rhoncus. Morbi ac posuere ligula, eu imperdiet mi. Fusce a dapibus turpis. Duis vel odio elementum, laoreet ipsum sit amet, blandit tellus. Vestibulum eleifend condimentum enim, fermentum vehicula nisi tincidunt nec. Aenean at maximus ante. Maecenas iaculis enim ac tortor feugiat, ac ultricies metus mollis. Nam posuere et turpis vitae egestas.
|
||||
|
||||
Proin vitae eros vel quam tristique ullamcorper. In nec feugiat diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean dui elit, dictum sit amet mi non, dignissim laoreet nisi. Nulla eget congue ipsum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis vitae libero sed nulla sagittis placerat nec sed lorem. Phasellus accumsan suscipit nunc a ultricies. Sed dapibus et elit a hendrerit. Ut fermentum quis velit vel dignissim. Etiam vel odio justo. In aliquet eros ut ultrices imperdiet. Aliquam erat volutpat. Phasellus quis dolor aliquam, lacinia mauris ut, blandit elit. Proin risus ipsum, laoreet nec gravida ut, condimentum at nisl.
|
||||
|
||||
Nam eu ipsum vel sem semper consectetur porttitor ut sem. Pellentesque ac leo ultricies, ornare risus pulvinar, elementum ipsum. Maecenas a turpis et lorem auctor sagittis. Pellentesque porttitor eu erat non maximus. Duis tristique in orci sed facilisis. Nulla orci justo, facilisis eu libero et, consequat varius lectus. Fusce quis quam et mauris tristique condimentum at vitae urna. Proin tristique ex ut mauris eleifend, sed dapibus felis semper. Aenean placerat sollicitudin sollicitudin. Ut elementum tincidunt neque in feugiat. Aliquam rhoncus ligula id hendrerit dapibus. Nulla ac ex dolor. Phasellus ex nisi, viverra sit amet faucibus nec, malesuada nec nisl. Aliquam erat volutpat. Ut consequat egestas odio, pretium ullamcorper massa viverra at.
|
||||
|
||||
Pellentesque blandit sit amet est a auctor. Nullam et arcu et risus tempus eleifend. Nunc tristique lectus est, quis rutrum magna sagittis eget. Etiam iaculis tellus eget metus laoreet faucibus vel vel nisi. Fusce et posuere enim. Morbi nec interdum nisl. Donec diam est, semper vel hendrerit at, rutrum sed eros. Nunc eu dapibus sem, eget ultricies elit. Nam condimentum ex pharetra turpis ornare, at pretium orci vehicula. Proin in tristique est, eu mollis ante. Sed tortor nisl, tincidunt et maximus quis, porta vitae elit. Quisque bibendum condimentum sodales. Vivamus fermentum posuere molestie. Morbi pharetra elit eget turpis vulputate, eget laoreet metus rutrum.
|
||||
|
||||
Suspendisse at diam ac nisl vestibulum facilisis. Quisque non sollicitudin urna, sed lacinia tortor. Duis ultrices ut mauris at aliquet. Vestibulum eu mauris dapibus, dictum nibh rhoncus, bibendum magna. Suspendisse rutrum ligula eu posuere efficitur. Nullam in egestas arcu. Proin a urna ac felis tempor sagittis egestas nec tortor. Donec ac feugiat leo. Ut ac tempor sapien, ac lacinia dolor. In placerat sagittis libero, sit amet varius massa auctor sit amet. Fusce pellentesque finibus odio vel scelerisque. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus euismod nisi nisi, ac luctus sapien venenatis nec.
|
||||
|
||||
Quisque sit amet metus et turpis laoreet pulvinar. Sed at accumsan ex. Aliquam eu tempus odio. Fusce consectetur dolor ut magna fringilla venenatis. Pellentesque rhoncus libero elementum, placerat eros et, laoreet eros. Nulla sit amet ligula viverra, aliquam felis accumsan, blandit eros. Vestibulum porta volutpat magna vel malesuada.
|
||||
|
||||
Duis semper aliquam nisi, vel finibus tellus pretium mollis. Vivamus nec libero vitae neque blandit finibus. Aliquam maximus, libero ut tristique cursus, magna risus placerat dui, sit amet semper odio metus vel mauris. Aenean porta ut nisi in aliquet. Vivamus in felis eu odio porttitor finibus. Phasellus placerat urna non leo congue, at placerat magna volutpat. Etiam ut fermentum ligula. Sed nunc lectus, posuere et tellus sed, rutrum pulvinar ex. Nulla ullamcorper at mauris at efficitur. Vivamus ultrices, odio sit amet congue porttitor, purus ante mattis justo, quis dapibus sem tellus sit amet dui. Morbi nec neque efficitur, scelerisque erat in, posuere diam. Nam faucibus nunc eget condimentum pulvinar. Praesent rutrum nisi et mauris fermentum sagittis. Cras imperdiet elit in eros mollis, ut pulvinar lacus tincidunt.
|
||||
|
||||
Vestibulum vel convallis ante. Duis et varius nibh. Praesent sodales purus at efficitur lacinia. In eget lacus odio. Vivamus eros nisi, lobortis non quam et, sollicitudin congue nulla. Pellentesque vestibulum turpis non purus pharetra egestas. Quisque accumsan vestibulum fermentum. Nam eu hendrerit neque. Proin ut aliquet lorem, id suscipit massa. Sed volutpat viverra magna, vel faucibus felis convallis in. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a hendrerit odio, ac facilisis purus.
|
||||
|
||||
Nam a nulla ultricies tellus porttitor feugiat. Morbi et urna suscipit, accumsan massa id, semper nisl. Nam eros nibh, eleifend semper erat vitae, vehicula cursus mauris. Nam semper pulvinar augue eu auctor. Morbi eget laoreet magna. Proin porta, nulla egestas commodo ultrices, risus felis efficitur eros, et mollis augue nisl in neque. Nullam dignissim dui eget tellus gravida, non congue nisl elementum. Nulla ac eros hendrerit, sollicitudin mauris vitae, tristique turpis. Maecenas id laoreet erat.
|
||||
|
||||
Nullam vestibulum in felis euismod aliquam. Sed sit amet magna in mauris feugiat scelerisque et fermentum lorem. Aenean scelerisque eget mauris vel molestie. Sed vel ipsum non magna eleifend tristique. Phasellus viverra nulla justo, sed maximus neque sollicitudin hendrerit. Mauris facilisis sem vel elit mattis iaculis. Vivamus ac dapibus sem. Sed quis egestas sapien, eu volutpat augue. Vestibulum molestie suscipit est, ut fermentum diam rhoncus eu. Maecenas accumsan massa sed sapien viverra commodo. Duis eget lacus a urna accumsan mattis at sed orci. Aenean at scelerisque felis. Sed magna lectus, lacinia eu pharetra ac, pharetra at ex. Vestibulum vel tortor a sem luctus placerat. Maecenas efficitur, est sed auctor vehicula, ante lorem finibus dolor, tristique efficitur lacus risus eget ex. Pellentesque maximus velit eu ipsum lobortis blandit.
|
||||
|
||||
Maecenas aliquam sollicitudin tellus, consequat ultricies lacus. Proin pretium nibh fermentum, malesuada quam sit amet, luctus orci. Curabitur sodales varius tortor, eu rutrum nisi blandit eu. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque nec lectus quis nisi mattis dapibus. Donec dapibus leo ac nibh elementum pharetra. Aliquam lobortis ante a risus facilisis condimentum. Sed mauris enim, tristique sed viverra eu, varius vel lorem. Vivamus non ex mi. Etiam sed pellentesque ante. Ut leo ipsum, mattis a eleifend sed, tincidunt pharetra nibh. Nam vel tellus nunc.
|
||||
|
||||
Nullam libero urna, euismod at consequat quis, fringilla eu turpis. Aliquam tellus leo, posuere elementum risus vel, pulvinar tincidunt quam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut non nibh id massa bibendum porta a sed ante. Donec commodo accumsan orci, quis volutpat sem tincidunt id. Nulla mollis, lacus id pretium cursus, nisi nulla rhoncus quam, non maximus leo ligula consequat metus. In fringilla et est quis tristique. Nullam vestibulum urna leo, non molestie ipsum dignissim at. Donec tristique erat vitae interdum gravida. Vestibulum tincidunt nec nunc eget blandit. Vestibulum at laoreet arcu, sed ultrices orci. Nam vitae sapien bibendum, aliquam massa quis, convallis mauris. Morbi eu mi ultrices, aliquam tortor sit amet, elementum diam. Sed pulvinar lorem eget urna consequat consectetur. Integer hendrerit tortor quis ipsum suscipit, eget vulputate neque semper. Duis pulvinar hendrerit nisi sed pretium.
|
||||
|
||||
Ut imperdiet tempor convallis. Nullam vehicula sem id ligula hendrerit consectetur. Nunc a ornare justo. Donec elementum eros id mi sagittis, sit amet consectetur nisi semper. Maecenas varius gravida turpis, quis dapibus ex consectetur sed. Cras tortor neque, lacinia et neque scelerisque, hendrerit semper est. In ultricies blandit nisl ut finibus.
|
||||
|
||||
In sapien ante, euismod non molestie vel, venenatis eu tortor. Pellentesque nec tortor sed ante posuere faucibus. Morbi sed euismod urna, vel dictum neque. Aenean ultrices in eros a lobortis. Suspendisse lacinia est eu lacus porttitor ornare. Donec vitae sapien diam. Integer vitae pellentesque ex. Maecenas iaculis purus id felis hendrerit suscipit vitae non tortor. Pellentesque rhoncus facilisis orci, at ultrices nibh egestas nec.
|
||||
|
||||
Quisque eu quam eros. Nam venenatis pharetra augue. Donec ut mauris maximus, rutrum nulla id, dignissim purus. Curabitur nec sem id risus mollis bibendum nec sit amet ipsum. Nam dignissim hendrerit ullamcorper. Suspendisse eu risus scelerisque, dapibus nibh vitae, pellentesque eros. Proin finibus sapien id cursus consequat. Quisque augue mi, imperdiet vitae dignissim eget, lacinia id lectus. Etiam at augue non lectus iaculis fermentum vel in arcu. Suspendisse et nunc sodales, auctor arcu in, faucibus est. Ut quis neque vitae leo placerat luctus sed quis velit. Suspendisse vehicula, erat vel dictum posuere, ligula sapien tristique velit, vel tincidunt orci leo at enim. Quisque non ullamcorper lectus.
|
||||
|
||||
Aliquam dapibus mattis purus eu euismod. Maecenas sagittis mi quis tellus sodales hendrerit. Phasellus at sem egestas, condimentum purus in, cursus quam. Praesent nec suscipit diam, at laoreet ex. Suspendisse cursus lectus eu erat convallis accumsan et nec orci. Pellentesque finibus hendrerit tellus, at rutrum enim rhoncus eget. Etiam id hendrerit nulla. Phasellus tempus urna a lorem ullamcorper accumsan. Proin sit amet orci ante.
|
||||
|
||||
Aenean pulvinar sem quis ligula dignissim tincidunt. Maecenas eu odio ut tortor venenatis elementum. Aenean a purus nunc. Suspendisse ut hendrerit elit. Phasellus ac lectus in tellus ullamcorper tincidunt. Aliquam ac pellentesque leo. Nam dignissim semper quam a efficitur. Suspendisse finibus pretium risus non lacinia. Phasellus consectetur porta pellentesque. Integer ac facilisis libero. Quisque pellentesque imperdiet tortor. Fusce porta mi nec consequat sagittis. Aliquam turpis sem, finibus ut tellus at, efficitur tincidunt velit. Nullam vitae diam sit amet quam malesuada lacinia.
|
||||
|
||||
Proin in hendrerit nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean elementum tortor libero, ac volutpat eros euismod quis. Ut malesuada convallis tortor a consectetur. Curabitur urna sem, consectetur in elit at, mollis dictum elit. Nulla rhoncus libero id purus fermentum faucibus. Curabitur finibus auctor suscipit. Ut sed molestie elit. In ut sem non sapien varius commodo. Duis nec facilisis erat. Donec sollicitudin mollis ex, in dapibus erat commodo eget. Vestibulum lorem sapien, consequat sed commodo ac, maximus vitae nunc. Pellentesque interdum interdum nulla, id facilisis magna viverra at. Donec porttitor ante id congue dignissim. Aliquam dignissim eget diam pellentesque accumsan.
|
||||
|
||||
Donec a efficitur neque. Integer iaculis sit amet augue sed pharetra. Nulla dignissim dolor a orci maximus ullamcorper. Morbi varius enim ut posuere molestie. Donec volutpat magna ut suscipit interdum. Cras magna dolor, rutrum eget nisi quis, ornare fringilla libero. Nullam tempor tempor erat eget condimentum. Vivamus egestas ex ac tellus finibus maximus. Donec eget vehicula purus, a venenatis neque. Duis mollis quam sit amet lectus ullamcorper tempus. Etiam eget sapien in orci porta pharetra. Phasellus et viverra dolor, vitae placerat urna. Nullam vel porttitor tellus. Aenean dictum imperdiet lobortis.
|
||||
|
||||
Suspendisse auctor metus ut aliquam ullamcorper. Morbi ac aliquet massa, a porta lorem. Etiam luctus dignissim erat. Etiam eu mi eu nisi convallis bibendum vel a nisi. Aenean condimentum enim et magna placerat, dictum aliquet tellus bibendum. Nam interdum mauris at facilisis porta. Morbi sodales sollicitudin tempus.
|
||||
|
||||
Nam quis aliquam tellus. Vestibulum placerat nisi eget tempus egestas. Etiam congue diam ut leo blandit fermentum. Curabitur eu dui quis mauris sodales imperdiet ac ac urna. Integer at nisl cursus, suscipit odio vel, consequat neque. Suspendisse in lectus turpis. Nullam dui odio, tempus ut feugiat at, suscipit a justo. Phasellus mauris augue, aliquet efficitur cursus eu, finibus sit amet ipsum. Vestibulum urna mauris, mollis sit amet ex at, cursus imperdiet nulla. Donec velit justo, viverra et erat in, hendrerit hendrerit turpis. Proin pharetra nunc aliquam neque congue eleifend.
|
||||
|
||||
Praesent vel egestas metus. Sed dui mi, laoreet a euismod ac, ullamcorper in orci. Aenean eu risus pulvinar, aliquet ex ac, ornare ex. Mauris lectus purus, placerat ut lacus ac, pellentesque sollicitudin sem. Proin sed volutpat sapien. Ut posuere ex ac odio eleifend, ac ultrices ligula ultricies. Vestibulum nec nunc a leo volutpat convallis eget vel turpis. Suspendisse ut dapibus enim, at scelerisque ligula. Mauris vestibulum nec tellus a porta. Quisque ac placerat sapien, nec maximus nunc. Vivamus mollis tincidunt risus in auctor. In laoreet elit et eleifend facilisis. Integer facilisis tortor quam, sed tristique purus mattis id. Etiam faucibus leo augue.
|
||||
|
||||
Sed tristique efficitur nulla, et rutrum mauris euismod non. Praesent ac leo luctus dui rutrum dictum a vel ipsum. Vestibulum faucibus risus vitae imperdiet rhoncus. Nunc volutpat viverra nisl. Nunc sit amet urna sed purus iaculis egestas. Nam pretium dui eget ante ullamcorper tempus. Pellentesque gravida, dui non cursus tempus, nisl lorem viverra diam, in condimentum metus neque eu justo. In malesuada tortor sagittis posuere finibus. Nunc ac nisi lacus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin nec nibh nec orci sagittis venenatis sed et justo. Vestibulum et nisl vitae ex mattis efficitur. Interdum et malesuada fames ac ante ipsum primis in faucibus.
|
||||
|
||||
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse hendrerit nibh nec ex consequat tempor. Suspendisse vestibulum urna in blandit iaculis. Aenean lacinia odio ex, eget tempor nulla condimentum sed. Proin suscipit, est eget sollicitudin feugiat, nisl felis ultrices massa, non finibus justo risus quis lectus. Mauris ipsum tellus, suscipit nec gravida sed, aliquet non sem. Ut suscipit sodales ante, vitae feugiat quam scelerisque in. Curabitur id luctus dui, eget interdum dui. Maecenas sagittis quis nisi et laoreet. Cras maximus in leo et feugiat. Proin aliquam egestas consequat. Suspendisse sit amet arcu auctor eros imperdiet rhoncus sed in lorem. Sed porttitor at elit laoreet mattis. Donec dui eros, dictum sit amet massa at, facilisis consequat nisi. Phasellus arcu est, viverra vel lacus id, efficitur sodales ligula.
|
||||
|
||||
Nam ultrices dignissim mi vel vestibulum. Mauris a euismod lorem, in scelerisque enim. Pellentesque molestie fermentum purus, nec semper nunc placerat sit amet. Aenean ullamcorper sollicitudin faucibus. Curabitur a hendrerit leo. Donec congue massa nulla, vitae sodales ex posuere non. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras pharetra risus eu consequat commodo. Donec iaculis lorem vitae diam mollis feugiat.
|
||||
|
||||
Nulla molestie dui quis blandit pretium. Curabitur et tempus nisi. Aliquam luctus interdum libero a varius. Morbi nec volutpat odio. Quisque elementum velit vitae mi hendrerit, nec aliquet arcu tempus. Aenean ullamcorper, tortor sit amet rutrum dapibus, metus dui sagittis nisl, id volutpat velit lorem sodales erat. Quisque vel justo sed massa rutrum accumsan eget non elit. Fusce luctus felis mi, id aliquet massa commodo sit amet. Morbi blandit et est ac faucibus. Quisque eget malesuada nibh, sit amet venenatis purus. Proin risus eros, ullamcorper nec posuere a, hendrerit eu dolor. Nunc a mattis dolor. Fusce ultricies arcu eu lectus consequat elementum. Phasellus euismod nunc sapien, eget lobortis urna efficitur vitae. Phasellus sed ligula rhoncus, imperdiet neque eget, luctus est. Praesent aliquam aliquet turpis, quis ornare lacus sagittis ut.
|
||||
|
||||
Quisque rhoncus velit in suscipit commodo. Donec massa turpis, posuere ut vulputate vitae, ultrices gravida velit. Aenean lectus nulla, hendrerit vitae laoreet imperdiet, ultrices a ipsum. Morbi a tincidunt odio, et lacinia nisi. In in pulvinar nibh. Vestibulum vehicula tellus quis est mollis efficitur. Maecenas non pellentesque dui, et sagittis erat. Sed sed diam blandit diam convallis euismod sit amet sit amet arcu.
|
||||
|
||||
Proin ullamcorper maximus suscipit. Aenean non volutpat quam. Vivamus ex justo, aliquam vitae vulputate eu, porttitor ut leo. Sed lorem mauris, finibus in feugiat sit amet, tincidunt ac risus. Duis accumsan lectus at purus dapibus ultricies. Ut ac sagittis velit. In vel enim eu neque imperdiet interdum eget eget massa. Aliquam varius sagittis pulvinar. Etiam fermentum sit amet mi finibus tempor. Aliquam varius risus erat, ac commodo sapien euismod et. Proin pretium mattis turpis et aliquet. Suspendisse facilisis ut mi ut maximus. Donec dictum dapibus feugiat.
|
||||
|
||||
Proin tempor diam vestibulum odio elementum aliquam. Integer nunc urna, dictum id tortor eget, efficitur accumsan elit. Quisque lobortis ante ac mollis dignissim. Integer vel nunc rutrum, malesuada metus a, vestibulum neque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec ac erat ut mi fermentum consequat. Praesent tempor, erat id porttitor tempor, erat mauris semper massa, ac vulputate lacus justo ac ligula. Sed ligula neque, tincidunt ut tortor sed, volutpat sollicitudin diam. Pellentesque ligula purus, volutpat nec velit non, vulputate euismod arcu. Aenean quis purus volutpat, placerat sem vitae, sollicitudin nunc. Cras laoreet semper ipsum quis finibus. Fusce pellentesque purus at nibh mattis, et consequat dui viverra. Proin eu tellus sit amet sapien volutpat dictum. Curabitur luctus feugiat massa ac vehicula. Nullam eu lacus tempus, hendrerit lectus ac, posuere odio. Donec eu dui metus.
|
||||
|
||||
Quisque molestie turpis eget dolor iaculis cursus. Suspendisse facilisis tristique enim at efficitur. Quisque sit amet nunc nisl. Nam placerat interdum fringilla. Aliquam vulputate, risus et euismod vulputate, ante dolor consequat odio, at finibus diam ante quis sem. Nulla accumsan quam id neque aliquam maximus. Proin sed convallis eros. Phasellus imperdiet in quam a ultrices. Fusce et imperdiet elit. Sed et hendrerit ipsum. Fusce arcu odio, rutrum vitae posuere vitae, facilisis lacinia nibh.
|
||||
|
||||
Fusce nec tincidunt sem. Morbi tempus, nisi quis malesuada ornare, turpis neque condimentum justo, bibendum bibendum justo ex eu nulla. Pellentesque laoreet tincidunt dolor nec venenatis. Morbi eros risus, venenatis ac luctus ut, luctus quis sapien. Etiam et tellus massa. Aenean sit amet libero massa. Fusce venenatis elit vitae tellus commodo hendrerit. Curabitur ipsum tellus, dignissim nec lacus non, suscipit efficitur magna.
|
||||
|
||||
Integer et erat tortor. Ut elementum pharetra scelerisque. Pellentesque mollis, urna quis faucibus cursus, arcu orci mattis lorem, varius maximus magna justo quis massa. Donec id scelerisque metus. Fusce sit amet ex a lectus ornare mollis. Donec ut metus nisl. Sed at turpis turpis. Suspendisse ut nibh nunc. Duis eget viverra nisi.
|
||||
|
||||
In massa velit, ultricies sit amet elementum vel, sollicitudin ac tellus. Ut euismod nisl non leo porta varius. Phasellus sapien velit, auctor quis pulvinar nec, venenatis in urna. Aliquam elementum, eros vitae dignissim condimentum, enim lacus suscipit nibh, eget imperdiet nibh metus ac arcu. Quisque condimentum, ligula in luctus pharetra, elit tortor lacinia neque, et aliquam ex velit sed ipsum. Maecenas convallis ante odio, finibus egestas dolor porta non. Nunc fringilla erat diam, nec lobortis est scelerisque eget. Cras dictum lectus rhoncus, rhoncus dui at, bibendum risus. Aenean eget tristique nunc. Etiam eget elementum urna. Nulla facilisi.
|
||||
|
||||
Aliquam porta magna id est fermentum, sit amet iaculis mi viverra. Nullam pharetra, ex non ultricies fringilla, dui ligula cursus ipsum, vitae iaculis eros quam vel sem. Sed lacinia vestibulum tellus at sodales. Quisque vulputate, quam eu porta convallis, lectus lacus viverra metus, quis tincidunt augue libero nec tellus. Curabitur et fermentum turpis. Praesent urna neque, fermentum ac magna vitae, convallis fermentum enim. Nam ut nulla at dui viverra faucibus vel at justo. Praesent feugiat commodo ante et dictum. Nullam quis gravida diam. Curabitur nec nisl ac elit luctus bibendum a sed augue. Mauris nec dolor eget eros ullamcorper condimentum.
|
||||
|
||||
In leo mauris, sagittis id rhoncus vel, aliquet non augue. Pellentesque ornare vitae nibh luctus pulvinar. Proin eu lacinia neque, ut faucibus lorem. Curabitur quis justo porttitor, tincidunt mauris id, porta turpis. Sed id leo elit. Morbi auctor nisi eget augue feugiat consequat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed ut purus felis.
|
||||
|
||||
Ut pretium, purus eget ultricies condimentum, diam quam finibus lacus, non scelerisque leo nisi at arcu. Vestibulum consectetur quam ac dapibus dignissim. Cras et lacus sit amet nisl sodales dignissim non eu tortor. Nam ultrices enim quam, vitae lobortis est varius in. Sed tincidunt tincidunt eros eget semper. Etiam accumsan efficitur suscipit. Donec at facilisis purus, et egestas ex. Vivamus dapibus iaculis sapien. Sed fermentum dui sit amet est blandit scelerisque non vitae neque. Vivamus a placerat ex. Mauris feugiat ultrices turpis, id luctus nulla rhoncus mattis. Curabitur accumsan eleifend ligula id viverra.
|
||||
|
||||
Aliquam molestie maximus nisl, vitae fermentum odio hendrerit quis. Fusce varius quis velit at sagittis. Morbi eu magna aliquet, scelerisque risus sit amet, sollicitudin ante. Mauris scelerisque pellentesque lacinia. Duis quis ligula nec mauris pretium lacinia. Nulla imperdiet lorem est, nec laoreet ante commodo et. Suspendisse et sollicitudin turpis, ut luctus nibh.
|
||||
|
||||
Ut id libero nec purus condimentum pharetra eget ac mauris. Vivamus finibus dignissim lacus, at porta leo sodales sit amet. Nunc augue leo, eleifend eu ultricies eget, posuere et tellus. Maecenas porta, nibh in rutrum semper, ex eros fringilla nisl, eu ultricies sem nunc sit amet magna. Aenean nec pharetra odio. Pellentesque quis diam quam. Fusce tincidunt justo enim, in condimentum erat euismod id. Etiam varius dui ut turpis placerat efficitur non id nulla. Nunc in velit magna. Sed posuere enim enim, sed semper urna auctor at. Nam scelerisque, est sed accumsan convallis, ipsum ligula imperdiet purus, eget malesuada urna nisi at nisl. Donec massa purus, venenatis at ex in, lobortis porttitor erat. In hac habitasse platea dictumst.
|
||||
|
||||
Mauris varius mattis fringilla. Ut pretium leo turpis. Etiam nec scelerisque sem. Donec velit elit, suscipit in dolor scelerisque, sagittis dignissim justo. Morbi egestas sit amet turpis vitae elementum. Integer maximus justo ac elit tempus faucibus. Donec consequat elementum dui consequat lobortis. Etiam eget est nec nibh pulvinar maximus. Integer egestas pulvinar leo vitae luctus. Nullam enim justo, vestibulum ac bibendum et, pharetra eleifend mauris. In ut ligula nec risus eleifend blandit.
|
||||
|
||||
Mauris sagittis arcu quis magna pulvinar, quis interdum leo semper. Aenean viverra turpis eget erat molestie, sit amet malesuada ipsum maximus. Duis eros metus, consequat vel metus quis, ullamcorper ullamcorper tortor. Duis condimentum, metus non molestie mollis, ante augue eleifend elit, nec porttitor nunc ex id purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam nisi velit, placerat et dictum sed, vulputate et mauris. Sed bibendum porttitor tellus vel vehicula.
|
||||
|
||||
Nam non gravida sapien, et euismod nulla. Pellentesque dapibus tristique lectus, sed finibus turpis accumsan ut. Pellentesque ultricies diam eu felis iaculis, vitae egestas nulla tempus. Ut pharetra, sem ac feugiat lobortis, ex nisl congue libero, vel pellentesque leo nibh eu elit. Etiam vehicula non metus at ornare. Aliquam orci leo, eleifend a fermentum condimentum, eleifend at lectus. Ut sit amet iaculis elit. Nullam molestie mattis leo a aliquet. Vestibulum convallis commodo rhoncus. Vestibulum at eros leo. Nam tempus urna sit amet nunc sagittis blandit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam condimentum, felis sit amet ultricies consectetur, velit ex ultrices ipsum, sit amet condimentum enim dui pulvinar risus. Vivamus euismod a quam et sagittis. Fusce posuere at sem non egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
|
||||
|
||||
Maecenas urna felis, condimentum vitae pretium vel, consequat id ligula. Proin eget ante eget tellus luctus maximus vitae sit amet libero. Donec at risus eget tellus feugiat vulputate. Aliquam laoreet sapien at pellentesque vehicula. In egestas laoreet lobortis. Duis ultrices molestie urna sit amet dapibus. Fusce ultricies mauris lectus, in luctus est facilisis sit amet. Nunc sed faucibus orci. Fusce fringilla est a dictum commodo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam aliquam lacus a eros tincidunt maximus.
|
||||
|
||||
Aenean vestibulum, metus vel interdum lacinia, libero metus consectetur tellus, non sollicitudin ante ipsum ut velit. Donec accumsan laoreet justo hendrerit venenatis. Mauris hendrerit tincidunt diam eu accumsan. Suspendisse egestas non orci at vulputate. Praesent sollicitudin congue magna egestas aliquet. Mauris at molestie mi. Mauris vel magna viverra, mattis velit at, fringilla elit. Cras porta lorem leo, ut tincidunt velit pharetra non.
|
||||
|
||||
Praesent commodo turpis et ligula vulputate, non ullamcorper ante faucibus. Phasellus cursus magna quis est mollis, id suscipit libero mattis. Nam felis lectus, accumsan vitae sollicitudin eu, facilisis nec velit. Nam sollicitudin odio ut sapien vulputate, quis commodo diam convallis. Aliquam fringilla est quis lacus elementum lobortis. Mauris pulvinar enim justo, ut sollicitudin eros pulvinar sit amet. Sed lobortis vestibulum eleifend. Morbi at mattis elit. In sit amet porttitor lacus, eget pharetra sapien. Proin elit metus, varius in dictum sed, ornare vel odio.
|
||||
|
||||
Suspendisse luctus viverra mollis. Vivamus est ante, egestas nec dignissim egestas, varius a libero. Phasellus id lacinia tellus. Sed pellentesque porttitor rutrum. Duis a mi sollicitudin, mollis purus et, fermentum ante. Nullam non metus et lacus vehicula ultricies eget non risus. Aenean ipsum dui, venenatis ut leo sed, ultricies volutpat tellus. Praesent consectetur id felis maximus suscipit. Nulla vel ipsum vel massa convallis ornare a vel felis. Aliquam convallis vestibulum ante.
|
||||
|
||||
Quisque eu pretium libero. Morbi volutpat velit ut est finibus, eu condimentum dui tristique. Cras dignissim tempus risus id gravida. Donec vitae lorem dolor. Aliquam et cursus lorem. Sed molestie dui nibh, et bibendum turpis elementum quis. Nunc consequat diam et tortor consectetur, eget sollicitudin urna mollis.
|
||||
|
||||
Cras vel est posuere ipsum viverra mollis. In lacus elit, interdum eget pretium non, dictum vitae dolor. Nulla arcu neque, sollicitudin varius iaculis in, gravida id justo. Phasellus ut condimentum justo. Aenean consectetur vitae sem quis rhoncus. Nam id nulla sit amet mauris ultricies bibendum et vitae quam. Mauris blandit metus in egestas egestas. Aenean erat ligula, consectetur nec elementum in, elementum quis quam. Quisque est arcu, auctor sed est eget, bibendum tristique mauris. Aliquam a varius purus, sit amet faucibus augue. Vestibulum a mattis lacus. Mauris eleifend, tortor sit amet fermentum lobortis, libero risus feugiat erat, sodales imperdiet magna nibh ut elit. In porta sapien urna, eget viverra magna egestas ut. Aliquam ac eleifend ligula. Morbi dignissim magna id varius pulvinar. Ut pulvinar commodo placerat.
|
||||
|
||||
In iaculis tortor id molestie scelerisque. Quisque congue tristique nisi bibendum efficitur. Proin rutrum ultrices tincidunt. Praesent faucibus, mauris in dictum tincidunt, quam ligula suscipit nisi, nec efficitur ligula mi sit amet purus. Donec porta, velit convallis elementum posuere, sem nibh ornare dui, eget semper purus erat dictum diam. Mauris congue eros tellus, eget bibendum purus blandit sit amet. Sed faucibus ipsum vel velit maximus, vitae lobortis lectus luctus. Morbi tempor lacus sit amet hendrerit auctor. Aliquam auctor maximus laoreet. Nulla viverra massa eu tortor porta molestie. Fusce quis nisi arcu. Duis sit amet vestibulum quam, in posuere nunc. Nulla non placerat tortor. Curabitur malesuada eget metus ac auctor. Interdum et malesuada fames ac ante ipsum primis in faucibus.
|
||||
|
||||
Donec bibendum libero nisl, eu varius est imperdiet id. Morbi sed arcu rhoncus, maximus libero eleifend, facilisis lacus. Sed sollicitudin, odio suscipit congue malesuada, justo magna finibus mauris, sed faucibus ipsum ligula ac augue. Sed sodales nulla mauris, efficitur bibendum sapien sagittis sit amet. Fusce consectetur justo diam, eu consequat nunc lacinia at. Curabitur ex ante, tempus at elementum non, maximus id lacus. Pellentesque in urna turpis. Proin tristique consequat lacus tincidunt faucibus. Proin ac tortor metus. Maecenas mollis blandit arcu, sit amet aliquam mauris laoreet sit amet. Nullam vulputate erat ac magna convallis efficitur. Proin cursus sodales est non suscipit. Nunc commodo lorem aliquet, commodo felis sit amet, dapibus orci. Nulla a enim vel ex facilisis laoreet. Donec malesuada laoreet turpis vel interdum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
|
||||
|
||||
Donec venenatis lectus eu tortor lobortis cursus. Quisque sit amet scelerisque quam, quis imperdiet ex. Morbi lacus purus, interdum non fringilla ut, ornare eget nisl. Morbi eleifend justo magna. Ut rutrum, nisl quis ultrices euismod, ligula arcu auctor quam, vel mattis ipsum lectus sit amet felis. Pellentesque vitae sagittis lorem. Morbi blandit finibus purus, quis commodo velit ultrices venenatis. Pellentesque eu erat enim. Fusce sollicitudin nunc nisi, non viverra neque aliquet at.
|
||||
|
||||
Curabitur bibendum vel augue eget viverra. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus id hendrerit quam, id tempor ex. Fusce quis sem dapibus, ornare leo ut, fringilla metus. Praesent molestie posuere scelerisque. Praesent ut libero vitae nisi iaculis venenatis maximus in leo. Donec sed ipsum massa. Aenean id purus tellus.
|
||||
|
||||
Maecenas varius pharetra dignissim. Nulla iaculis in elit a facilisis. Nam ipsum enim, tristique nec feugiat ut, tristique vel felis. Donec tincidunt suscipit justo, at dictum ante sollicitudin sed. Mauris nisi ipsum, faucibus id sollicitudin at, consequat eu nibh. Duis lorem lectus, vestibulum vel eros eget, efficitur semper ligula. Quisque tristique tortor eu eros fringilla scelerisque. Aenean nisl nisi, mollis non dolor in, sagittis blandit metus. Cras tellus turpis, volutpat in varius non, semper eget magna. Pellentesque finibus augue id fringilla cursus.
|
||||
|
||||
Fusce id est elit. Aliquam sit amet nunc finibus mi consectetur hendrerit in sit amet leo. Nunc posuere lectus ut est pellentesque, eu mollis tortor efficitur. Aliquam tincidunt placerat mauris non aliquam. Sed finibus dapibus tortor, sit amet fringilla libero tincidunt ut. Morbi at lectus volutpat, congue turpis sit amet, dignissim quam. Sed suscipit dolor vel nibh facilisis porta. Donec ut purus a leo volutpat pellentesque.
|
||||
|
||||
Mauris vitae ipsum bibendum, interdum metus nec, pharetra purus. Nulla facilisi. Donec dolor ligula, iaculis vitae tempor quis, euismod non tortor. Phasellus condimentum accumsan augue, vel hendrerit nisi dictum id. Nullam eget ante sit amet turpis tempus finibus. Morbi a dolor sollicitudin, sollicitudin sem a, placerat massa. Aenean consectetur elit non aliquet lacinia. Maecenas lobortis ex turpis, vel sollicitudin dolor elementum in. Sed sit amet facilisis elit. Duis iaculis faucibus ante, ac bibendum ex placerat id. Nulla facilisi. Praesent sollicitudin ut velit at interdum. Nulla viverra volutpat lorem. Sed mattis gravida auctor. Nam pharetra erat id convallis luctus. Vestibulum congue est lorem, eget fermentum magna consequat eu.
|
||||
|
||||
Sed ac luctus lectus, egestas gravida lorem. Suspendisse a tortor et velit mattis efficitur. Integer ornare accumsan justo nec molestie. Donec leo nunc, ultrices a consequat ut, bibendum at nisl. Mauris varius sem ac malesuada pharetra. Quisque bibendum diam at interdum molestie. Mauris ac ante sapien. Integer ultricies vitae justo eu dictum. Nulla facilisi. Etiam aliquet tellus id dignissim pharetra.
|
||||
|
||||
Nam sed nibh ex. Phasellus faucibus ante sapien, sit amet tristique elit posuere mattis. Proin porta vitae enim sed auctor. Vestibulum quis ex euismod, imperdiet ante iaculis, vehicula mi. Vivamus convallis augue pellentesque commodo bibendum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer gravida vitae leo vel varius. Aenean porta vehicula lorem, vitae commodo turpis sagittis eu. Aenean mattis elit et mi sagittis vulputate. Morbi vitae nisi quis mauris malesuada scelerisque. Morbi id efficitur quam. Ut id elit quam. Fusce at nisi fringilla, pharetra diam ut, suscipit erat.
|
||||
@@ -0,0 +1,136 @@
|
||||
// Package header provides middleware that appends headers to
|
||||
// requests based on a set of configuration rules that define
|
||||
// which routes receive which headers.
|
||||
package header
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
// Headers is middleware that adds headers to the responses
|
||||
// for requests matching a certain path.
|
||||
type Headers struct {
|
||||
Next httpserver.Handler
|
||||
Rules []Rule
|
||||
}
|
||||
|
||||
// ServeHTTP implements the httpserver.Handler interface and serves requests,
|
||||
// setting headers on the response according to the configured rules.
|
||||
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
replacer := httpserver.NewReplacer(r, nil, "")
|
||||
rww := &responseWriterWrapper{w: w}
|
||||
for _, rule := range h.Rules {
|
||||
if httpserver.Path(r.URL.Path).Matches(rule.Path) {
|
||||
for name := range rule.Headers {
|
||||
|
||||
// One can either delete a header, add multiple values to a header, or simply
|
||||
// set a header.
|
||||
|
||||
if strings.HasPrefix(name, "-") {
|
||||
rww.delHeader(strings.TrimLeft(name, "-"))
|
||||
} else if strings.HasPrefix(name, "+") {
|
||||
for _, value := range rule.Headers[name] {
|
||||
rww.Header().Add(strings.TrimLeft(name, "+"), replacer.Replace(value))
|
||||
}
|
||||
} else {
|
||||
for _, value := range rule.Headers[name] {
|
||||
rww.Header().Set(name, replacer.Replace(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return h.Next.ServeHTTP(rww, r)
|
||||
}
|
||||
|
||||
type (
|
||||
// Rule groups a slice of HTTP headers by a URL pattern.
|
||||
Rule struct {
|
||||
Path string
|
||||
Headers http.Header
|
||||
}
|
||||
)
|
||||
|
||||
// headerOperation represents an operation on the header
|
||||
type headerOperation func(http.Header)
|
||||
|
||||
// responseWriterWrapper wraps the real ResponseWriter.
|
||||
// It defers header operations until writeHeader
|
||||
type responseWriterWrapper struct {
|
||||
w http.ResponseWriter
|
||||
ops []headerOperation
|
||||
wroteHeader bool
|
||||
}
|
||||
|
||||
func (rww *responseWriterWrapper) Header() http.Header {
|
||||
return rww.w.Header()
|
||||
}
|
||||
|
||||
func (rww *responseWriterWrapper) Write(d []byte) (int, error) {
|
||||
if !rww.wroteHeader {
|
||||
rww.WriteHeader(http.StatusOK)
|
||||
}
|
||||
return rww.w.Write(d)
|
||||
}
|
||||
|
||||
func (rww *responseWriterWrapper) WriteHeader(status int) {
|
||||
if rww.wroteHeader {
|
||||
return
|
||||
}
|
||||
rww.wroteHeader = true
|
||||
// capture the original headers
|
||||
h := rww.Header()
|
||||
|
||||
// perform our revisions
|
||||
for _, op := range rww.ops {
|
||||
op(h)
|
||||
}
|
||||
|
||||
rww.w.WriteHeader(status)
|
||||
}
|
||||
|
||||
// delHeader deletes the existing header according to the key
|
||||
// Also it will delete that header added later.
|
||||
func (rww *responseWriterWrapper) delHeader(key string) {
|
||||
// remove the existing one if any
|
||||
rww.Header().Del(key)
|
||||
|
||||
// register a future deletion
|
||||
rww.ops = append(rww.ops, func(h http.Header) {
|
||||
h.Del(key)
|
||||
})
|
||||
}
|
||||
|
||||
// Hijack implements http.Hijacker. It simply wraps the underlying
|
||||
// ResponseWriter's Hijack method if there is one, or returns an error.
|
||||
func (rww *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
if hj, ok := rww.w.(http.Hijacker); ok {
|
||||
return hj.Hijack()
|
||||
}
|
||||
return nil, nil, httpserver.NonHijackerError{Underlying: rww.w}
|
||||
}
|
||||
|
||||
// Flush implements http.Flusher. It simply wraps the underlying
|
||||
// ResponseWriter's Flush method if there is one, or panics.
|
||||
func (rww *responseWriterWrapper) Flush() {
|
||||
if f, ok := rww.w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
} else {
|
||||
panic(httpserver.NonFlusherError{Underlying: rww.w}) // should be recovered at the beginning of middleware stack
|
||||
}
|
||||
}
|
||||
|
||||
// CloseNotify implements http.CloseNotifier.
|
||||
// It just inherits the underlying ResponseWriter's CloseNotify method.
|
||||
// It panics if the underlying ResponseWriter is not a CloseNotifier.
|
||||
func (rww *responseWriterWrapper) CloseNotify() <-chan bool {
|
||||
if cn, ok := rww.w.(http.CloseNotifier); ok {
|
||||
return cn.CloseNotify()
|
||||
}
|
||||
panic(httpserver.NonCloseNotifierError{Underlying: rww.w})
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package header
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestHeader(t *testing.T) {
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
t.Fatalf("Could not determine hostname: %v", err)
|
||||
}
|
||||
for i, test := range []struct {
|
||||
from string
|
||||
name string
|
||||
value string
|
||||
}{
|
||||
{"/a", "Foo", "Bar"},
|
||||
{"/a", "Bar", ""},
|
||||
{"/a", "Baz", ""},
|
||||
{"/a", "Server", ""},
|
||||
{"/a", "ServerName", hostname},
|
||||
{"/b", "Foo", ""},
|
||||
{"/b", "Bar", "Removed in /a"},
|
||||
} {
|
||||
he := Headers{
|
||||
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
w.Header().Set("Bar", "Removed in /a")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return 0, nil
|
||||
}),
|
||||
Rules: []Rule{
|
||||
{Path: "/a", Headers: http.Header{
|
||||
"Foo": []string{"Bar"},
|
||||
"ServerName": []string{"{hostname}"},
|
||||
"-Bar": []string{""},
|
||||
"-Server": []string{},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", test.from, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Test %d: Could not create HTTP request: %v", i, err)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
// preset header
|
||||
rec.Header().Set("Server", "Caddy")
|
||||
|
||||
he.ServeHTTP(rec, req)
|
||||
|
||||
if got := rec.Header().Get(test.name); got != test.value {
|
||||
t.Errorf("Test %d: Expected %s header to be %q but was %q",
|
||||
i, test.name, test.value, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultipleHeaders(t *testing.T) {
|
||||
he := Headers{
|
||||
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||
fmt.Fprint(w, "This is a test")
|
||||
return 0, nil
|
||||
}),
|
||||
Rules: []Rule{
|
||||
{Path: "/a", Headers: http.Header{
|
||||
"+Link": []string{"</images/image.png>; rel=preload", "</css/main.css>; rel=preload"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", "/a", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Could not create HTTP request: %v", err)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
he.ServeHTTP(rec, req)
|
||||
|
||||
desiredHeaders := []string{"</css/main.css>; rel=preload", "</images/image.png>; rel=preload"}
|
||||
actualHeaders := rec.HeaderMap[http.CanonicalHeaderKey("Link")]
|
||||
sort.Strings(actualHeaders)
|
||||
|
||||
if !reflect.DeepEqual(desiredHeaders, actualHeaders) {
|
||||
t.Errorf("Expected header to contain: %v but got: %v", desiredHeaders, actualHeaders)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package header
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func init() {
|
||||
caddy.RegisterPlugin("header", caddy.Plugin{
|
||||
ServerType: "http",
|
||||
Action: setup,
|
||||
})
|
||||
}
|
||||
|
||||
// setup configures a new Headers middleware instance.
|
||||
func setup(c *caddy.Controller) error {
|
||||
rules, err := headersParse(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
|
||||
return Headers{Next: next, Rules: rules}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func headersParse(c *caddy.Controller) ([]Rule, error) {
|
||||
var rules []Rule
|
||||
|
||||
for c.NextLine() {
|
||||
var head Rule
|
||||
head.Headers = http.Header{}
|
||||
var isNewPattern bool
|
||||
|
||||
if !c.NextArg() {
|
||||
return rules, c.ArgErr()
|
||||
}
|
||||
pattern := c.Val()
|
||||
|
||||
// See if we already have a definition for this Path pattern...
|
||||
for _, h := range rules {
|
||||
if h.Path == pattern {
|
||||
head = h
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// ...otherwise, this is a new pattern
|
||||
if head.Path == "" {
|
||||
head.Path = pattern
|
||||
isNewPattern = true
|
||||
}
|
||||
|
||||
for c.NextBlock() {
|
||||
// A block of headers was opened...
|
||||
name := c.Val()
|
||||
value := ""
|
||||
|
||||
args := c.RemainingArgs()
|
||||
|
||||
if len(args) > 1 {
|
||||
return rules, c.ArgErr()
|
||||
} else if len(args) == 1 {
|
||||
value = args[0]
|
||||
}
|
||||
|
||||
head.Headers.Add(name, value)
|
||||
}
|
||||
if c.NextArg() {
|
||||
// ... or single header was defined as an argument instead.
|
||||
|
||||
name := c.Val()
|
||||
value := c.Val()
|
||||
|
||||
if c.NextArg() {
|
||||
value = c.Val()
|
||||
}
|
||||
|
||||
head.Headers.Add(name, value)
|
||||
}
|
||||
|
||||
if isNewPattern {
|
||||
rules = append(rules, head)
|
||||
} else {
|
||||
for i := 0; i < len(rules); i++ {
|
||||
if rules[i].Path == pattern {
|
||||
rules[i] = head
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rules, nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package header
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
"github.com/mholt/caddy/caddyhttp/httpserver"
|
||||
)
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
c := caddy.NewTestController("http", `header / Foo Bar`)
|
||||
err := setup(c)
|
||||
if err != nil {
|
||||
t.Errorf("Expected no errors, but got: %v", err)
|
||||
}
|
||||
|
||||
mids := httpserver.GetConfig(c).Middleware()
|
||||
if len(mids) == 0 {
|
||||
t.Fatal("Expected middleware, had 0 instead")
|
||||
}
|
||||
|
||||
handler := mids[0](httpserver.EmptyNext)
|
||||
myHandler, ok := handler.(Headers)
|
||||
if !ok {
|
||||
t.Fatalf("Expected handler to be type Headers, got: %#v", handler)
|
||||
}
|
||||
|
||||
if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
|
||||
t.Error("'Next' field of handler was not set properly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeadersParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
shouldErr bool
|
||||
expected []Rule
|
||||
}{
|
||||
{`header /foo Foo "Bar Baz"`,
|
||||
false, []Rule{
|
||||
{Path: "/foo", Headers: http.Header{
|
||||
"Foo": []string{"Bar Baz"},
|
||||
}},
|
||||
}},
|
||||
{`header /bar {
|
||||
Foo "Bar Baz"
|
||||
Baz Qux
|
||||
Foobar
|
||||
}`,
|
||||
false, []Rule{
|
||||
{Path: "/bar", Headers: http.Header{
|
||||
"Foo": []string{"Bar Baz"},
|
||||
"Baz": []string{"Qux"},
|
||||
"Foobar": []string{""},
|
||||
}},
|
||||
}},
|
||||
{`header /foo {
|
||||
Foo Bar Baz
|
||||
}`, true,
|
||||
[]Rule{}},
|
||||
{`header /foo {
|
||||
Test "max-age=1814400";
|
||||
}`, true, []Rule{}},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
actual, err := headersParse(caddy.NewTestController("http", test.input))
|
||||
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d didn't error, but it should have", i)
|
||||
} else if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
|
||||
}
|
||||
|
||||
if len(actual) != len(test.expected) {
|
||||
t.Fatalf("Test %d expected %d rules, but got %d",
|
||||
i, len(test.expected), len(actual))
|
||||
}
|
||||
|
||||
for j, expectedRule := range test.expected {
|
||||
actualRule := actual[j]
|
||||
|
||||
if actualRule.Path != expectedRule.Path {
|
||||
t.Errorf("Test %d, rule %d: Expected path %s, but got %s",
|
||||
i, j, expectedRule.Path, actualRule.Path)
|
||||
}
|
||||
|
||||
expectedHeaders := fmt.Sprintf("%v", expectedRule.Headers)
|
||||
actualHeaders := fmt.Sprintf("%v", actualRule.Headers)
|
||||
|
||||
if !reflect.DeepEqual(actualRule.Headers, expectedRule.Headers) {
|
||||
t.Errorf("Test %d, rule %d: Expected headers %s, but got %s",
|
||||
i, j, expectedHeaders, actualHeaders)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
)
|
||||
|
||||
// SetupIfMatcher parses `if` or `if_op` in the current dispenser block.
|
||||
// It returns a RequestMatcher and an error if any.
|
||||
func SetupIfMatcher(controller *caddy.Controller) (RequestMatcher, error) {
|
||||
var c = controller.Dispenser // copy the dispenser
|
||||
var matcher IfMatcher
|
||||
for c.NextBlock() {
|
||||
switch c.Val() {
|
||||
case "if":
|
||||
args1 := c.RemainingArgs()
|
||||
if len(args1) != 3 {
|
||||
return matcher, c.ArgErr()
|
||||
}
|
||||
ifc, err := newIfCond(args1[0], args1[1], args1[2])
|
||||
if err != nil {
|
||||
return matcher, err
|
||||
}
|
||||
matcher.ifs = append(matcher.ifs, ifc)
|
||||
case "if_op":
|
||||
if !c.NextArg() {
|
||||
return matcher, c.ArgErr()
|
||||
}
|
||||
switch c.Val() {
|
||||
case "and":
|
||||
matcher.isOr = false
|
||||
case "or":
|
||||
matcher.isOr = true
|
||||
default:
|
||||
return matcher, c.ArgErr()
|
||||
}
|
||||
}
|
||||
}
|
||||
return matcher, nil
|
||||
}
|
||||
|
||||
// operators
|
||||
const (
|
||||
isOp = "is"
|
||||
notOp = "not"
|
||||
hasOp = "has"
|
||||
notHasOp = "not_has"
|
||||
startsWithOp = "starts_with"
|
||||
endsWithOp = "ends_with"
|
||||
matchOp = "match"
|
||||
notMatchOp = "not_match"
|
||||
)
|
||||
|
||||
func operatorError(operator string) error {
|
||||
return fmt.Errorf("Invalid operator %v", operator)
|
||||
}
|
||||
|
||||
// ifCondition is a 'if' condition.
|
||||
type ifCondition func(string, string) bool
|
||||
|
||||
var ifConditions = map[string]ifCondition{
|
||||
isOp: isFunc,
|
||||
notOp: notFunc,
|
||||
hasOp: hasFunc,
|
||||
notHasOp: notHasFunc,
|
||||
startsWithOp: startsWithFunc,
|
||||
endsWithOp: endsWithFunc,
|
||||
matchOp: matchFunc,
|
||||
notMatchOp: notMatchFunc,
|
||||
}
|
||||
|
||||
// isFunc is condition for Is operator.
|
||||
// It checks for equality.
|
||||
func isFunc(a, b string) bool {
|
||||
return a == b
|
||||
}
|
||||
|
||||
// notFunc is condition for Not operator.
|
||||
// It checks for inequality.
|
||||
func notFunc(a, b string) bool {
|
||||
return a != b
|
||||
}
|
||||
|
||||
// hasFunc is condition for Has operator.
|
||||
// It checks if b is a substring of a.
|
||||
func hasFunc(a, b string) bool {
|
||||
return strings.Contains(a, b)
|
||||
}
|
||||
|
||||
// notHasFunc is condition for NotHas operator.
|
||||
// It checks if b is not a substring of a.
|
||||
func notHasFunc(a, b string) bool {
|
||||
return !strings.Contains(a, b)
|
||||
}
|
||||
|
||||
// startsWithFunc is condition for StartsWith operator.
|
||||
// It checks if b is a prefix of a.
|
||||
func startsWithFunc(a, b string) bool {
|
||||
return strings.HasPrefix(a, b)
|
||||
}
|
||||
|
||||
// endsWithFunc is condition for EndsWith operator.
|
||||
// It checks if b is a suffix of a.
|
||||
func endsWithFunc(a, b string) bool {
|
||||
return strings.HasSuffix(a, b)
|
||||
}
|
||||
|
||||
// matchFunc is condition for Match operator.
|
||||
// It does regexp matching of a against pattern in b
|
||||
// and returns if they match.
|
||||
func matchFunc(a, b string) bool {
|
||||
matched, _ := regexp.MatchString(b, a)
|
||||
return matched
|
||||
}
|
||||
|
||||
// notMatchFunc is condition for NotMatch operator.
|
||||
// It does regexp matching of a against pattern in b
|
||||
// and returns if they do not match.
|
||||
func notMatchFunc(a, b string) bool {
|
||||
matched, _ := regexp.MatchString(b, a)
|
||||
return !matched
|
||||
}
|
||||
|
||||
// ifCond is statement for a IfMatcher condition.
|
||||
type ifCond struct {
|
||||
a string
|
||||
op string
|
||||
b string
|
||||
}
|
||||
|
||||
// newIfCond creates a new If condition.
|
||||
func newIfCond(a, operator, b string) (ifCond, error) {
|
||||
if _, ok := ifConditions[operator]; !ok {
|
||||
return ifCond{}, operatorError(operator)
|
||||
}
|
||||
return ifCond{
|
||||
a: a,
|
||||
op: operator,
|
||||
b: b,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// True returns true if the condition is true and false otherwise.
|
||||
// If r is not nil, it replaces placeholders before comparison.
|
||||
func (i ifCond) True(r *http.Request) bool {
|
||||
if c, ok := ifConditions[i.op]; ok {
|
||||
a, b := i.a, i.b
|
||||
if r != nil {
|
||||
replacer := NewReplacer(r, nil, "")
|
||||
a = replacer.Replace(i.a)
|
||||
b = replacer.Replace(i.b)
|
||||
}
|
||||
return c(a, b)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IfMatcher is a RequestMatcher for 'if' conditions.
|
||||
type IfMatcher struct {
|
||||
ifs []ifCond // list of If
|
||||
isOr bool // if true, conditions are 'or' instead of 'and'
|
||||
}
|
||||
|
||||
// Match satisfies RequestMatcher interface.
|
||||
// It returns true if the conditions in m are true.
|
||||
func (m IfMatcher) Match(r *http.Request) bool {
|
||||
if m.isOr {
|
||||
return m.Or(r)
|
||||
}
|
||||
return m.And(r)
|
||||
}
|
||||
|
||||
// And returns true if all conditions in m are true.
|
||||
func (m IfMatcher) And(r *http.Request) bool {
|
||||
for _, i := range m.ifs {
|
||||
if !i.True(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Or returns true if any of the conditions in m is true.
|
||||
func (m IfMatcher) Or(r *http.Request) bool {
|
||||
for _, i := range m.ifs {
|
||||
if i.True(r) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IfMatcherKeyword checks if the next value in the dispenser is a keyword for 'if' config block.
|
||||
// If true, remaining arguments in the dispinser are cleard to keep the dispenser valid for use.
|
||||
func IfMatcherKeyword(c *caddy.Controller) bool {
|
||||
if c.Val() == "if" || c.Val() == "if_op" {
|
||||
// clear remainig args
|
||||
c.RemainingArgs()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mholt/caddy"
|
||||
)
|
||||
|
||||
func TestConditions(t *testing.T) {
|
||||
tests := []struct {
|
||||
condition string
|
||||
isTrue bool
|
||||
}{
|
||||
{"a is b", false},
|
||||
{"a is a", true},
|
||||
{"a not b", true},
|
||||
{"a not a", false},
|
||||
{"a has a", true},
|
||||
{"a has b", false},
|
||||
{"ba has b", true},
|
||||
{"bab has b", true},
|
||||
{"bab has bb", false},
|
||||
{"a not_has a", false},
|
||||
{"a not_has b", true},
|
||||
{"ba not_has b", false},
|
||||
{"bab not_has b", false},
|
||||
{"bab not_has bb", true},
|
||||
{"bab starts_with bb", false},
|
||||
{"bab starts_with ba", true},
|
||||
{"bab starts_with bab", true},
|
||||
{"bab ends_with bb", false},
|
||||
{"bab ends_with bab", true},
|
||||
{"bab ends_with ab", true},
|
||||
{"a match *", false},
|
||||
{"a match a", true},
|
||||
{"a match .*", true},
|
||||
{"a match a.*", true},
|
||||
{"a match b.*", false},
|
||||
{"ba match b.*", true},
|
||||
{"ba match b[a-z]", true},
|
||||
{"b0 match b[a-z]", false},
|
||||
{"b0a match b[a-z]", false},
|
||||
{"b0a match b[a-z]+", false},
|
||||
{"b0a match b[a-z0-9]+", true},
|
||||
{"a not_match *", true},
|
||||
{"a not_match a", false},
|
||||
{"a not_match .*", false},
|
||||
{"a not_match a.*", false},
|
||||
{"a not_match b.*", true},
|
||||
{"ba not_match b.*", false},
|
||||
{"ba not_match b[a-z]", false},
|
||||
{"b0 not_match b[a-z]", true},
|
||||
{"b0a not_match b[a-z]", true},
|
||||
{"b0a not_match b[a-z]+", true},
|
||||
{"b0a not_match b[a-z0-9]+", false},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
str := strings.Fields(test.condition)
|
||||
ifCond, err := newIfCond(str[0], str[1], str[2])
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
isTrue := ifCond.True(nil)
|
||||
if isTrue != test.isTrue {
|
||||
t.Errorf("Test %d: expected %v found %v", i, test.isTrue, isTrue)
|
||||
}
|
||||
}
|
||||
|
||||
invalidOperators := []string{"ss", "and", "if"}
|
||||
for _, op := range invalidOperators {
|
||||
_, err := newIfCond("a", op, "b")
|
||||
if err == nil {
|
||||
t.Errorf("Invalid operator %v used, expected error.", op)
|
||||
}
|
||||
}
|
||||
|
||||
replaceTests := []struct {
|
||||
url string
|
||||
condition string
|
||||
isTrue bool
|
||||
}{
|
||||
{"/home", "{uri} match /home", true},
|
||||
{"/hom", "{uri} match /home", false},
|
||||
{"/hom", "{uri} starts_with /home", false},
|
||||
{"/hom", "{uri} starts_with /h", true},
|
||||
{"/home/.hiddenfile", `{uri} match \/\.(.*)`, true},
|
||||
{"/home/.hiddendir/afile", `{uri} match \/\.(.*)`, true},
|
||||
}
|
||||
|
||||
for i, test := range replaceTests {
|
||||
r, err := http.NewRequest("GET", test.url, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
str := strings.Fields(test.condition)
|
||||
ifCond, err := newIfCond(str[0], str[1], str[2])
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
isTrue := ifCond.True(r)
|
||||
if isTrue != test.isTrue {
|
||||
t.Errorf("Test %v: expected %v found %v", i, test.isTrue, isTrue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIfMatcher(t *testing.T) {
|
||||
tests := []struct {
|
||||
conditions []string
|
||||
isOr bool
|
||||
isTrue bool
|
||||
}{
|
||||
{
|
||||
[]string{
|
||||
"a is a",
|
||||
"b is b",
|
||||
"c is c",
|
||||
},
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
[]string{
|
||||
"a is b",
|
||||
"b is c",
|
||||
"c is c",
|
||||
},
|
||||
true,
|
||||
true,
|
||||
},
|
||||
{
|
||||
[]string{
|
||||
"a is a",
|
||||
"b is a",
|
||||
"c is c",
|
||||
},
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
[]string{
|
||||
"a is b",
|
||||
"b is c",
|
||||
"c is a",
|
||||
},
|
||||
true,
|
||||
false,
|
||||
},
|
||||
{
|
||||
[]string{},
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
[]string{},
|
||||
true,
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
matcher := IfMatcher{isOr: test.isOr}
|
||||
for _, condition := range test.conditions {
|
||||
str := strings.Fields(condition)
|
||||
ifCond, err := newIfCond(str[0], str[1], str[2])
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
matcher.ifs = append(matcher.ifs, ifCond)
|
||||
}
|
||||
isTrue := matcher.Match(nil)
|
||||
if isTrue != test.isTrue {
|
||||
t.Errorf("Test %d: expected %v found %v", i, test.isTrue, isTrue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupIfMatcher(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
shouldErr bool
|
||||
expected IfMatcher
|
||||
}{
|
||||
{`test {
|
||||
if a match b
|
||||
}`, false, IfMatcher{
|
||||
ifs: []ifCond{
|
||||
{a: "a", op: "match", b: "b"},
|
||||
},
|
||||
}},
|
||||
{`test {
|
||||
if a match b
|
||||
if_op or
|
||||
}`, false, IfMatcher{
|
||||
ifs: []ifCond{
|
||||
{a: "a", op: "match", b: "b"},
|
||||
},
|
||||
isOr: true,
|
||||
}},
|
||||
{`test {
|
||||
if a match
|
||||
}`, true, IfMatcher{},
|
||||
},
|
||||
{`test {
|
||||
if a isn't b
|
||||
}`, true, IfMatcher{},
|
||||
},
|
||||
{`test {
|
||||
if a match b c
|
||||
}`, true, IfMatcher{},
|
||||
},
|
||||
{`test {
|
||||
if goal has go
|
||||
if cook not_has go
|
||||
}`, false, IfMatcher{
|
||||
ifs: []ifCond{
|
||||
{a: "goal", op: "has", b: "go"},
|
||||
{a: "cook", op: "not_has", b: "go"},
|
||||
},
|
||||
}},
|
||||
{`test {
|
||||
if goal has go
|
||||
if cook not_has go
|
||||
if_op and
|
||||
}`, false, IfMatcher{
|
||||
ifs: []ifCond{
|
||||
{a: "goal", op: "has", b: "go"},
|
||||
{a: "cook", op: "not_has", b: "go"},
|
||||
},
|
||||
}},
|
||||
{`test {
|
||||
if goal has go
|
||||
if cook not_has go
|
||||
if_op not
|
||||
}`, true, IfMatcher{},
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
c := caddy.NewTestController("http", test.input)
|
||||
c.Next()
|
||||
matcher, err := SetupIfMatcher(c)
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf("Test %d didn't error, but it should have", i)
|
||||
} else if err != nil && !test.shouldErr {
|
||||
t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
|
||||
} else if err != nil && test.shouldErr {
|
||||
continue
|
||||
}
|
||||
if _, ok := matcher.(IfMatcher); !ok {
|
||||
t.Error("RequestMatcher should be of type IfMatcher")
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, but got: %v", err)
|
||||
}
|
||||
if fmt.Sprint(matcher) != fmt.Sprint(test.expected) {
|
||||
t.Errorf("Test %v: Expected %v, found %v", i,
|
||||
fmt.Sprint(test.expected), fmt.Sprint(matcher))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIfMatcherKeyword(t *testing.T) {
|
||||
tests := []struct {
|
||||
keyword string
|
||||
expected bool
|
||||
}{
|
||||
{"if", true},
|
||||
{"ifs", false},
|
||||
{"tls", false},
|
||||
{"http", false},
|
||||
{"if_op", true},
|
||||
{"if_type", false},
|
||||
{"if_cond", false},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
c := caddy.NewTestController("http", test.keyword)
|
||||
c.Next()
|
||||
valid := IfMatcherKeyword(c)
|
||||
if valid != test.expected {
|
||||
t.Errorf("Test %d: expected %v found %v", i, test.expected, valid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"os"
|
||||
|
||||
"github.com/russross/blackfriday"
|
||||
)
|
||||
|
||||
// This file contains the context and functions available for
|
||||
// use in the templates.
|
||||
|
||||
// Context is the context with which Caddy templates are executed.
|
||||
type Context struct {
|
||||
Root http.FileSystem
|
||||
Req *http.Request
|
||||
URL *url.URL
|
||||
Args []interface{} // defined by arguments to .Include
|
||||
}
|
||||
|
||||
// Include returns the contents of filename relative to the site root.
|
||||
func (c Context) Include(filename string, args ...interface{}) (string, error) {
|
||||
c.Args = args
|
||||
return ContextInclude(filename, c, c.Root)
|
||||
}
|
||||
|
||||
// Now returns the current timestamp in the specified format.
|
||||
func (c Context) Now(format string) string {
|
||||
return time.Now().Format(format)
|
||||
}
|
||||
|
||||
// NowDate returns the current date/time that can be used
|
||||
// in other time functions.
|
||||
func (c Context) NowDate() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// Cookie gets the value of a cookie with name name.
|
||||
func (c Context) Cookie(name string) string {
|
||||
cookies := c.Req.Cookies()
|
||||
for _, cookie := range cookies {
|
||||
if cookie.Name == name {
|
||||
return cookie.Value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Header gets the value of a request header with field name.
|
||||
func (c Context) Header(name string) string {
|
||||
return c.Req.Header.Get(name)
|
||||
}
|
||||
|
||||
// Env gets a map of the environment variables.
|
||||
func (c Context) Env() map[string]string {
|
||||
osEnv := os.Environ()
|
||||
envVars := make(map[string]string, len(osEnv))
|
||||
for _, env := range osEnv {
|
||||
data := strings.SplitN(env, "=", 2)
|
||||
if len(data) == 2 && len(data[0]) > 0 {
|
||||
envVars[data[0]] = data[1]
|
||||
}
|
||||
}
|
||||
return envVars
|
||||
}
|
||||
|
||||
// IP gets the (remote) IP address of the client making the request.
|
||||
func (c Context) IP() string {
|
||||
ip, _, err := net.SplitHostPort(c.Req.RemoteAddr)
|
||||
if err != nil {
|
||||
return c.Req.RemoteAddr
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
// URI returns the raw, unprocessed request URI (including query
|
||||
// string and hash) obtained directly from the Request-Line of
|
||||
// the HTTP request.
|
||||
func (c Context) URI() string {
|
||||
return c.Req.RequestURI
|
||||
}
|
||||
|
||||
// Host returns the hostname portion of the Host header
|
||||
// from the HTTP request.
|
||||
func (c Context) Host() (string, error) {
|
||||
host, _, err := net.SplitHostPort(c.Req.Host)
|
||||
if err != nil {
|
||||
if !strings.Contains(c.Req.Host, ":") {
|
||||
// common with sites served on the default port 80
|
||||
return c.Req.Host, nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return host, nil
|
||||
}
|
||||
|
||||
// Port returns the port portion of the Host header if specified.
|
||||
func (c Context) Port() (string, error) {
|
||||
_, port, err := net.SplitHostPort(c.Req.Host)
|
||||
if err != nil {
|
||||
if !strings.Contains(c.Req.Host, ":") {
|
||||
// common with sites served on the default port 80
|
||||
return "80", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return port, nil
|
||||
}
|
||||
|
||||
// Method returns the method (GET, POST, etc.) of the request.
|
||||
func (c Context) Method() string {
|
||||
return c.Req.Method
|
||||
}
|
||||
|
||||
// PathMatches returns true if the path portion of the request
|
||||
// URL matches pattern.
|
||||
func (c Context) PathMatches(pattern string) bool {
|
||||
return Path(c.Req.URL.Path).Matches(pattern)
|
||||
}
|
||||
|
||||
// Truncate truncates the input string to the given length.
|
||||
// If length is negative, it returns that many characters
|
||||
// starting from the end of the string. If the absolute value
|
||||
// of length is greater than len(input), the whole input is
|
||||
// returned.
|
||||
func (c Context) Truncate(input string, length int) string {
|
||||
if length < 0 && len(input)+length > 0 {
|
||||
return input[len(input)+length:]
|
||||
}
|
||||
if length >= 0 && len(input) > length {
|
||||
return input[:length]
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
// StripHTML returns s without HTML tags. It is fairly naive
|
||||
// but works with most valid HTML inputs.
|
||||
func (c Context) StripHTML(s string) string {
|
||||
var buf bytes.Buffer
|
||||
var inTag, inQuotes bool
|
||||
var tagStart int
|
||||
for i, ch := range s {
|
||||
if inTag {
|
||||
if ch == '>' && !inQuotes {
|
||||
inTag = false
|
||||
} else if ch == '<' && !inQuotes {
|
||||
// false start
|
||||
buf.WriteString(s[tagStart:i])
|
||||
tagStart = i
|
||||
} else if ch == '"' {
|
||||
inQuotes = !inQuotes
|
||||
}
|
||||
continue
|
||||
}
|
||||
if ch == '<' {
|
||||
inTag = true
|
||||
tagStart = i
|
||||
continue
|
||||
}
|
||||
buf.WriteRune(ch)
|
||||
}
|
||||
if inTag {
|
||||
// false start
|
||||
buf.WriteString(s[tagStart:])
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// Ext returns the suffix beginning at the final dot in the final
|
||||
// slash-separated element of the pathStr (or in other words, the
|
||||
// file extension).
|
||||
func (c Context) Ext(pathStr string) string {
|
||||
return path.Ext(pathStr)
|
||||
}
|
||||
|
||||
// StripExt returns the input string without the extension,
|
||||
// which is the suffix starting with the final '.' character
|
||||
// but not before the final path separator ('/') character.
|
||||
// If there is no extension, the whole input is returned.
|
||||
func (c Context) StripExt(path string) string {
|
||||
for i := len(path) - 1; i >= 0 && path[i] != '/'; i-- {
|
||||
if path[i] == '.' {
|
||||
return path[:i]
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// Replace replaces instances of find in input with replacement.
|
||||
func (c Context) Replace(input, find, replacement string) string {
|
||||
return strings.Replace(input, find, replacement, -1)
|
||||
}
|
||||
|
||||
// Markdown returns the HTML contents of the markdown contained in filename
|
||||
// (relative to the site root).
|
||||
func (c Context) Markdown(filename string) (string, error) {
|
||||
body, err := c.Include(filename)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
renderer := blackfriday.HtmlRenderer(0, "", "")
|
||||
extns := 0
|
||||
extns |= blackfriday.EXTENSION_TABLES
|
||||
extns |= blackfriday.EXTENSION_FENCED_CODE
|
||||
extns |= blackfriday.EXTENSION_STRIKETHROUGH
|
||||
extns |= blackfriday.EXTENSION_DEFINITION_LISTS
|
||||
markdown := blackfriday.Markdown([]byte(body), renderer, extns)
|
||||
|
||||
return string(markdown), nil
|
||||
}
|
||||
|
||||
// ContextInclude opens filename using fs and executes a template with the context ctx.
|
||||
// This does the same thing that Context.Include() does, but with the ability to provide
|
||||
// your own context so that the included files can have access to additional fields your
|
||||
// type may provide. You can embed Context in your type, then override its Include method
|
||||
// to call this function with ctx being the instance of your type, and fs being Context.Root.
|
||||
func ContextInclude(filename string, ctx interface{}, fs http.FileSystem) (string, error) {
|
||||
file, err := fs.Open(filename)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
tpl, err := template.New(filename).Parse(string(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err = tpl.Execute(&buf, ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// ToLower will convert the given string to lower case.
|
||||
func (c Context) ToLower(s string) string {
|
||||
return strings.ToLower(s)
|
||||
}
|
||||
|
||||
// ToUpper will convert the given string to upper case.
|
||||
func (c Context) ToUpper(s string) string {
|
||||
return strings.ToUpper(s)
|
||||
}
|
||||
|
||||
// Split is a pass-through to strings.Split. It will split the first argument at each instance of the separator and return a slice of strings.
|
||||
func (c Context) Split(s string, sep string) []string {
|
||||
return strings.Split(s, sep)
|
||||
}
|
||||
|
||||
// Join is a pass-through to strings.Join. It will join the first argument slice with the separator in the second argument and return the result.
|
||||
func (c Context) Join(a []string, sep string) string {
|
||||
return strings.Join(a, sep)
|
||||
}
|
||||
|
||||
// Slice will convert the given arguments into a slice.
|
||||
func (c Context) Slice(elems ...interface{}) []interface{} {
|
||||
return elems
|
||||
}
|
||||
|
||||
// Map will convert the arguments into a map. It expects alternating string keys and values. This is useful for building more complicated data structures
|
||||
// if you are using subtemplates or things like that.
|
||||
func (c Context) Map(values ...interface{}) (map[string]interface{}, error) {
|
||||
if len(values)%2 != 0 {
|
||||
return nil, fmt.Errorf("Map expects an even number of arguments")
|
||||
}
|
||||
dict := make(map[string]interface{}, len(values)/2)
|
||||
for i := 0; i < len(values); i += 2 {
|
||||
key, ok := values[i].(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Map keys must be strings")
|
||||
}
|
||||
dict[key] = values[i+1]
|
||||
}
|
||||
return dict, nil
|
||||
}
|
||||
|
||||
// Files reads and returns a slice of names from the given directory
|
||||
// relative to the root of Context c.
|
||||
func (c Context) Files(name string) ([]string, error) {
|
||||
dir, err := c.Root.Open(path.Clean(name))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer dir.Close()
|
||||
|
||||
stat, err := dir.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !stat.IsDir() {
|
||||
return nil, fmt.Errorf("%v is not a directory", name)
|
||||
}
|
||||
|
||||
dirInfo, err := dir.Readdir(0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
names := make([]string, len(dirInfo))
|
||||
for i, fileInfo := range dirInfo {
|
||||
names[i] = fileInfo.Name()
|
||||
}
|
||||
|
||||
return names, nil
|
||||
}
|
||||
@@ -0,0 +1,796 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"text/template"
|
||||
)
|
||||
|
||||
func TestInclude(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
inputFilename := "test_file"
|
||||
absInFilePath := filepath.Join(fmt.Sprintf("%s", context.Root), inputFilename)
|
||||
defer func() {
|
||||
err := os.Remove(absInFilePath)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf("Failed to clean test file!")
|
||||
}
|
||||
}()
|
||||
|
||||
tests := []struct {
|
||||
args []interface{}
|
||||
fileContent string
|
||||
expectedContent string
|
||||
shouldErr bool
|
||||
expectedErrorContent string
|
||||
}{
|
||||
// Test 0 - all good
|
||||
{
|
||||
fileContent: `str1 {{ .Root }} str2`,
|
||||
expectedContent: fmt.Sprintf("str1 %s str2", context.Root),
|
||||
shouldErr: false,
|
||||
expectedErrorContent: "",
|
||||
},
|
||||
// Test 1 - all good, with args
|
||||
{
|
||||
args: []interface{}{"hello", 5},
|
||||
fileContent: `str1 {{ .Root }} str2 {{index .Args 0}} {{index .Args 1}}`,
|
||||
expectedContent: fmt.Sprintf("str1 %s str2 %s %d", context.Root, "hello", 5),
|
||||
shouldErr: false,
|
||||
expectedErrorContent: "",
|
||||
},
|
||||
// Test 2 - failure on template.Parse
|
||||
{
|
||||
fileContent: `str1 {{ .Root } str2`,
|
||||
expectedContent: "",
|
||||
shouldErr: true,
|
||||
expectedErrorContent: `unexpected "}" in operand`,
|
||||
},
|
||||
// Test 3 - failure on template.Execute
|
||||
{
|
||||
fileContent: `str1 {{ .InvalidField }} str2`,
|
||||
expectedContent: "",
|
||||
shouldErr: true,
|
||||
expectedErrorContent: `InvalidField`,
|
||||
},
|
||||
{
|
||||
fileContent: `str1 {{ .InvalidField }} str2`,
|
||||
expectedContent: "",
|
||||
shouldErr: true,
|
||||
expectedErrorContent: `type httpserver.Context`,
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
testPrefix := getTestPrefix(i)
|
||||
|
||||
// WriteFile truncates the contentt
|
||||
err := ioutil.WriteFile(absInFilePath, []byte(test.fileContent), os.ModePerm)
|
||||
if err != nil {
|
||||
t.Fatal(testPrefix+"Failed to create test file. Error was: %v", err)
|
||||
}
|
||||
|
||||
content, err := context.Include(inputFilename, test.args...)
|
||||
if err != nil {
|
||||
if !test.shouldErr {
|
||||
t.Errorf(testPrefix+"Expected no error, found [%s]", test.expectedErrorContent, err.Error())
|
||||
}
|
||||
if !strings.Contains(err.Error(), test.expectedErrorContent) {
|
||||
t.Errorf(testPrefix+"Expected error content [%s], found [%s]", test.expectedErrorContent, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if err == nil && test.shouldErr {
|
||||
t.Errorf(testPrefix+"Expected error [%s] but found nil. Input file was: %s", test.expectedErrorContent, inputFilename)
|
||||
}
|
||||
|
||||
if content != test.expectedContent {
|
||||
t.Errorf(testPrefix+"Expected content [%s] but found [%s]. Input file was: %s", test.expectedContent, content, inputFilename)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncludeNotExisting(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
_, err := context.Include("not_existing")
|
||||
if err == nil {
|
||||
t.Errorf("Expected error but found nil!")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkdown(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
inputFilename := "test_file"
|
||||
absInFilePath := filepath.Join(fmt.Sprintf("%s", context.Root), inputFilename)
|
||||
defer func() {
|
||||
err := os.Remove(absInFilePath)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf("Failed to clean test file!")
|
||||
}
|
||||
}()
|
||||
|
||||
tests := []struct {
|
||||
fileContent string
|
||||
expectedContent string
|
||||
}{
|
||||
// Test 0 - test parsing of markdown
|
||||
{
|
||||
fileContent: "* str1\n* str2\n",
|
||||
expectedContent: "<ul>\n<li>str1</li>\n<li>str2</li>\n</ul>\n",
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
testPrefix := getTestPrefix(i)
|
||||
|
||||
// WriteFile truncates the contentt
|
||||
err := ioutil.WriteFile(absInFilePath, []byte(test.fileContent), os.ModePerm)
|
||||
if err != nil {
|
||||
t.Fatal(testPrefix+"Failed to create test file. Error was: %v", err)
|
||||
}
|
||||
|
||||
content, _ := context.Markdown(inputFilename)
|
||||
if content != test.expectedContent {
|
||||
t.Errorf(testPrefix+"Expected content [%s] but found [%s]. Input file was: %s", test.expectedContent, content, inputFilename)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookie(t *testing.T) {
|
||||
|
||||
tests := []struct {
|
||||
cookie *http.Cookie
|
||||
cookieName string
|
||||
expectedValue string
|
||||
}{
|
||||
// Test 0 - happy path
|
||||
{
|
||||
cookie: &http.Cookie{Name: "cookieName", Value: "cookieValue"},
|
||||
cookieName: "cookieName",
|
||||
expectedValue: "cookieValue",
|
||||
},
|
||||
// Test 1 - try to get a non-existing cookie
|
||||
{
|
||||
cookie: &http.Cookie{Name: "cookieName", Value: "cookieValue"},
|
||||
cookieName: "notExisting",
|
||||
expectedValue: "",
|
||||
},
|
||||
// Test 2 - partial name match
|
||||
{
|
||||
cookie: &http.Cookie{Name: "cookie", Value: "cookieValue"},
|
||||
cookieName: "cook",
|
||||
expectedValue: "",
|
||||
},
|
||||
// Test 3 - cookie with optional fields
|
||||
{
|
||||
cookie: &http.Cookie{Name: "cookie", Value: "cookieValue", Path: "/path", Domain: "https://localhost", Expires: (time.Now().Add(10 * time.Minute)), MaxAge: 120},
|
||||
cookieName: "cookie",
|
||||
expectedValue: "cookieValue",
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
testPrefix := getTestPrefix(i)
|
||||
|
||||
// reinitialize the context for each test
|
||||
context := getContextOrFail(t)
|
||||
|
||||
context.Req.AddCookie(test.cookie)
|
||||
|
||||
actualCookieVal := context.Cookie(test.cookieName)
|
||||
|
||||
if actualCookieVal != test.expectedValue {
|
||||
t.Errorf(testPrefix+"Expected cookie value [%s] but found [%s] for cookie with name %s", test.expectedValue, actualCookieVal, test.cookieName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookieMultipleCookies(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
cookieNameBase, cookieValueBase := "cookieName", "cookieValue"
|
||||
|
||||
// make sure that there's no state and multiple requests for different cookies return the correct result
|
||||
for i := 0; i < 10; i++ {
|
||||
context.Req.AddCookie(&http.Cookie{Name: fmt.Sprintf("%s%d", cookieNameBase, i), Value: fmt.Sprintf("%s%d", cookieValueBase, i)})
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
expectedCookieVal := fmt.Sprintf("%s%d", cookieValueBase, i)
|
||||
actualCookieVal := context.Cookie(fmt.Sprintf("%s%d", cookieNameBase, i))
|
||||
if actualCookieVal != expectedCookieVal {
|
||||
t.Fatalf("Expected cookie value %s, found %s", expectedCookieVal, actualCookieVal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeader(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
headerKey, headerVal := "Header1", "HeaderVal1"
|
||||
context.Req.Header.Add(headerKey, headerVal)
|
||||
|
||||
actualHeaderVal := context.Header(headerKey)
|
||||
if actualHeaderVal != headerVal {
|
||||
t.Errorf("Expected header %s, found %s", headerVal, actualHeaderVal)
|
||||
}
|
||||
|
||||
missingHeaderVal := context.Header("not-existing")
|
||||
if missingHeaderVal != "" {
|
||||
t.Errorf("Expected empty header value, found %s", missingHeaderVal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnv(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
name := "ENV_TEST_NAME"
|
||||
testValue := "TEST_VALUE"
|
||||
os.Setenv(name, testValue)
|
||||
|
||||
notExisting := "ENV_TEST_NOT_EXISTING"
|
||||
os.Unsetenv(notExisting)
|
||||
|
||||
invalidName := "ENV_TEST_INVALID_NAME"
|
||||
os.Setenv("="+invalidName, testValue)
|
||||
|
||||
env := context.Env()
|
||||
if value := env[name]; value != testValue {
|
||||
t.Errorf("Expected env-variable %s value '%s', found '%s'",
|
||||
name, testValue, value)
|
||||
}
|
||||
|
||||
if value, ok := env[notExisting]; ok {
|
||||
t.Errorf("Expected empty env-variable %s, found '%s'",
|
||||
notExisting, value)
|
||||
}
|
||||
|
||||
for k, v := range env {
|
||||
if strings.Contains(k, invalidName) {
|
||||
t.Errorf("Expected invalid name not to be included in Env %s, found in key '%s'", invalidName, k)
|
||||
}
|
||||
if strings.Contains(v, invalidName) {
|
||||
t.Errorf("Expected invalid name not be be included in Env %s, found in value '%s'", invalidName, v)
|
||||
}
|
||||
}
|
||||
|
||||
os.Unsetenv("=" + invalidName)
|
||||
}
|
||||
|
||||
func TestIP(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
tests := []struct {
|
||||
inputRemoteAddr string
|
||||
expectedIP string
|
||||
}{
|
||||
// Test 0 - ipv4 with port
|
||||
{"1.1.1.1:1111", "1.1.1.1"},
|
||||
// Test 1 - ipv4 without port
|
||||
{"1.1.1.1", "1.1.1.1"},
|
||||
// Test 2 - ipv6 with port
|
||||
{"[::1]:11", "::1"},
|
||||
// Test 3 - ipv6 without port and brackets
|
||||
{"[2001:db8:a0b:12f0::1]", "[2001:db8:a0b:12f0::1]"},
|
||||
// Test 4 - ipv6 with zone and port
|
||||
{`[fe80:1::3%eth0]:44`, `fe80:1::3%eth0`},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
testPrefix := getTestPrefix(i)
|
||||
|
||||
context.Req.RemoteAddr = test.inputRemoteAddr
|
||||
actualIP := context.IP()
|
||||
|
||||
if actualIP != test.expectedIP {
|
||||
t.Errorf(testPrefix+"Expected IP %s, found %s", test.expectedIP, actualIP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestURL(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
inputURL := "http://localhost"
|
||||
context.Req.RequestURI = inputURL
|
||||
|
||||
if inputURL != context.URI() {
|
||||
t.Errorf("Expected url %s, found %s", inputURL, context.URI())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHost(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
expectedHost string
|
||||
shouldErr bool
|
||||
}{
|
||||
{
|
||||
input: "localhost:123",
|
||||
expectedHost: "localhost",
|
||||
shouldErr: false,
|
||||
},
|
||||
{
|
||||
input: "localhost",
|
||||
expectedHost: "localhost",
|
||||
shouldErr: false,
|
||||
},
|
||||
{
|
||||
input: "[::]",
|
||||
expectedHost: "",
|
||||
shouldErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
testHostOrPort(t, true, test.input, test.expectedHost, test.shouldErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPort(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
expectedPort string
|
||||
shouldErr bool
|
||||
}{
|
||||
{
|
||||
input: "localhost:123",
|
||||
expectedPort: "123",
|
||||
shouldErr: false,
|
||||
},
|
||||
{
|
||||
input: "localhost",
|
||||
expectedPort: "80", // assuming 80 is the default port
|
||||
shouldErr: false,
|
||||
},
|
||||
{
|
||||
input: ":8080",
|
||||
expectedPort: "8080",
|
||||
shouldErr: false,
|
||||
},
|
||||
{
|
||||
input: "[::]",
|
||||
expectedPort: "",
|
||||
shouldErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
testHostOrPort(t, false, test.input, test.expectedPort, test.shouldErr)
|
||||
}
|
||||
}
|
||||
|
||||
func testHostOrPort(t *testing.T, isTestingHost bool, input, expectedResult string, shouldErr bool) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
context.Req.Host = input
|
||||
var actualResult, testedObject string
|
||||
var err error
|
||||
|
||||
if isTestingHost {
|
||||
actualResult, err = context.Host()
|
||||
testedObject = "host"
|
||||
} else {
|
||||
actualResult, err = context.Port()
|
||||
testedObject = "port"
|
||||
}
|
||||
|
||||
if shouldErr && err == nil {
|
||||
t.Errorf("Expected error, found nil!")
|
||||
return
|
||||
}
|
||||
|
||||
if !shouldErr && err != nil {
|
||||
t.Errorf("Expected no error, found %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
if actualResult != expectedResult {
|
||||
t.Errorf("Expected %s %s, found %s", testedObject, expectedResult, actualResult)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMethod(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
method := "POST"
|
||||
context.Req.Method = method
|
||||
|
||||
if method != context.Method() {
|
||||
t.Errorf("Expected method %s, found %s", method, context.Method())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPathMatches(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
|
||||
tests := []struct {
|
||||
urlStr string
|
||||
pattern string
|
||||
shouldMatch bool
|
||||
}{
|
||||
// Test 0
|
||||
{
|
||||
urlStr: "http://localhost/",
|
||||
pattern: "",
|
||||
shouldMatch: true,
|
||||
},
|
||||
// Test 1
|
||||
{
|
||||
urlStr: "http://localhost",
|
||||
pattern: "",
|
||||
shouldMatch: true,
|
||||
},
|
||||
// Test 1
|
||||
{
|
||||
urlStr: "http://localhost/",
|
||||
pattern: "/",
|
||||
shouldMatch: true,
|
||||
},
|
||||
// Test 3
|
||||
{
|
||||
urlStr: "http://localhost/?param=val",
|
||||
pattern: "/",
|
||||
shouldMatch: true,
|
||||
},
|
||||
// Test 4
|
||||
{
|
||||
urlStr: "http://localhost/dir1/dir2",
|
||||
pattern: "/dir2",
|
||||
shouldMatch: false,
|
||||
},
|
||||
// Test 5
|
||||
{
|
||||
urlStr: "http://localhost/dir1/dir2",
|
||||
pattern: "/dir1",
|
||||
shouldMatch: true,
|
||||
},
|
||||
// Test 6
|
||||
{
|
||||
urlStr: "http://localhost:444/dir1/dir2",
|
||||
pattern: "/dir1",
|
||||
shouldMatch: true,
|
||||
},
|
||||
// Test 7
|
||||
{
|
||||
urlStr: "http://localhost/dir1/dir2",
|
||||
pattern: "*/dir2",
|
||||
shouldMatch: false,
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
testPrefix := getTestPrefix(i)
|
||||
var err error
|
||||
context.Req.URL, err = url.Parse(test.urlStr)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to prepare test URL from string %s! Error was: %s", test.urlStr, err)
|
||||
}
|
||||
|
||||
matches := context.PathMatches(test.pattern)
|
||||
if matches != test.shouldMatch {
|
||||
t.Errorf(testPrefix+"Expected and actual result differ: expected to match [%t], actual matches [%t]", test.shouldMatch, matches)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
tests := []struct {
|
||||
inputString string
|
||||
inputLength int
|
||||
expected string
|
||||
}{
|
||||
// Test 0 - small length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: 1,
|
||||
expected: "s",
|
||||
},
|
||||
// Test 1 - exact length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: 6,
|
||||
expected: "string",
|
||||
},
|
||||
// Test 2 - bigger length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: 10,
|
||||
expected: "string",
|
||||
},
|
||||
// Test 3 - zero length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: 0,
|
||||
expected: "",
|
||||
},
|
||||
// Test 4 - negative, smaller length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: -5,
|
||||
expected: "tring",
|
||||
},
|
||||
// Test 5 - negative, exact length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: -6,
|
||||
expected: "string",
|
||||
},
|
||||
// Test 6 - negative, bigger length
|
||||
{
|
||||
inputString: "string",
|
||||
inputLength: -7,
|
||||
expected: "string",
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
actual := context.Truncate(test.inputString, test.inputLength)
|
||||
if actual != test.expected {
|
||||
t.Errorf(getTestPrefix(i)+"Expected '%s', found '%s'. Input was Truncate(%q, %d)", test.expected, actual, test.inputString, test.inputLength)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripHTML(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
tests := []struct {
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
// Test 0 - no tags
|
||||
{
|
||||
input: `h1`,
|
||||
expected: `h1`,
|
||||
},
|
||||
// Test 1 - happy path
|
||||
{
|
||||
input: `<h1>h1</h1>`,
|
||||
expected: `h1`,
|
||||
},
|
||||
// Test 2 - tag in quotes
|
||||
{
|
||||
input: `<h1">">h1</h1>`,
|
||||
expected: `h1`,
|
||||
},
|
||||
// Test 3 - multiple tags
|
||||
{
|
||||
input: `<h1><b>h1</b></h1>`,
|
||||
expected: `h1`,
|
||||
},
|
||||
// Test 4 - tags not closed
|
||||
{
|
||||
input: `<h1`,
|
||||
expected: `<h1`,
|
||||
},
|
||||
// Test 5 - false start
|
||||
{
|
||||
input: `<h1<b>hi`,
|
||||
expected: `<h1hi`,
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
actual := context.StripHTML(test.input)
|
||||
if actual != test.expected {
|
||||
t.Errorf(getTestPrefix(i)+"Expected %s, found %s. Input was StripHTML(%s)", test.expected, actual, test.input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripExt(t *testing.T) {
|
||||
context := getContextOrFail(t)
|
||||
tests := []struct {
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
// Test 0 - empty input
|
||||
{
|
||||
input: "",
|
||||
expected: "",
|
||||
},
|
||||
// Test 1 - relative file with ext
|
||||
{
|
||||
input: "file.ext",
|
||||
expected: "file",
|
||||
},
|
||||
// Test 2 - relative file without ext
|
||||
{
|
||||
input: "file",
|
||||
expected: "file",
|
||||
},
|
||||
// Test 3 - absolute file without ext
|
||||
{
|
||||
input: "/file",
|
||||
expected: "/file",
|
||||
},
|
||||
// Test 4 - absolute file with ext
|
||||
{
|
||||
input: "/file.ext",
|
||||
expected: "/file",
|
||||
},
|
||||
// Test 5 - with ext but ends with /
|
||||
{
|
||||
input: "/dir.ext/",
|
||||
expected: "/dir.ext/",
|
||||
},
|
||||
// Test 6 - file with ext under dir with ext
|
||||
{
|
||||
input: "/dir.ext/file.ext",
|
||||
expected: "/dir.ext/file",
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
actual := context.StripExt(test.input)
|
||||
if actual != test.expected {
|
||||
t.Errorf(getTestPrefix(i)+"Expected %s, found %s. Input was StripExt(%q)", test.expected, actual, test.input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func initTestContext() (Context, error) {
|
||||
body := bytes.NewBufferString("request body")
|
||||
request, err := http.NewRequest("GET", "https://localhost", body)
|
||||
if err != nil {
|
||||
return Context{}, err
|
||||
}
|
||||
|
||||
return Context{Root: http.Dir(os.TempDir()), Req: request}, nil
|
||||
}
|
||||
|
||||
func getContextOrFail(t *testing.T) Context {
|
||||
context, err := initTestContext()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to prepare test context")
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
func getTestPrefix(testN int) string {
|
||||
return fmt.Sprintf("Test [%d]: ", testN)
|
||||
}
|
||||
|
||||
func TestTemplates(t *testing.T) {
|
||||
tests := []struct{ tmpl, expected string }{
|
||||
{`{{.ToUpper "aAA"}}`, "AAA"},
|
||||
{`{{"bbb" | .ToUpper}}`, "BBB"},
|
||||
{`{{.ToLower "CCc"}}`, "ccc"},
|
||||
{`{{range (.Split "a,b,c" ",")}}{{.}}{{end}}`, "abc"},
|
||||
{`{{range .Split "a,b,c" ","}}{{.}}{{end}}`, "abc"},
|
||||
{`{{range .Slice "a" "b" "c"}}{{.}}{{end}}`, "abc"},
|
||||
{`{{with .Map "A" "a" "B" "b" "c" "d"}}{{.A}}{{.B}}{{.c}}{{end}}`, "abd"},
|
||||
}
|
||||
for i, test := range tests {
|
||||
ctx := getContextOrFail(t)
|
||||
tmpl, err := template.New("").Parse(test.tmpl)
|
||||
if err != nil {
|
||||
t.Errorf("Test %d: %s", i, err)
|
||||
continue
|
||||
}
|
||||
buf := &bytes.Buffer{}
|
||||
err = tmpl.Execute(buf, ctx)
|
||||
if err != nil {
|
||||
t.Errorf("Test %d: %s", i, err)
|
||||
continue
|
||||
}
|
||||
if buf.String() != test.expected {
|
||||
t.Errorf("Test %d: Results do not match. '%s' != '%s'", i, buf.String(), test.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFiles(t *testing.T) {
|
||||
tests := []struct {
|
||||
fileNames []string
|
||||
inputBase string
|
||||
shouldErr bool
|
||||
verifyErr func(error) bool
|
||||
}{
|
||||
// Test 1 - directory and files exist
|
||||
{
|
||||
fileNames: []string{"file1", "file2"},
|
||||
shouldErr: false,
|
||||
},
|
||||
// Test 2 - directory exists, no files
|
||||
{
|
||||
fileNames: []string{},
|
||||
shouldErr: false,
|
||||
},
|
||||
// Test 3 - file or directory does not exist
|
||||
{
|
||||
fileNames: nil,
|
||||
inputBase: "doesNotExist",
|
||||
shouldErr: true,
|
||||
verifyErr: os.IsNotExist,
|
||||
},
|
||||
// Test 4 - directory and files exist, but path to a file
|
||||
{
|
||||
fileNames: []string{"file1", "file2"},
|
||||
inputBase: "file1",
|
||||
shouldErr: true,
|
||||
verifyErr: func(err error) bool {
|
||||
return strings.HasSuffix(err.Error(), "is not a directory")
|
||||
},
|
||||
},
|
||||
// Test 5 - try to leave Context Root
|
||||
{
|
||||
fileNames: nil,
|
||||
inputBase: filepath.Join("..", "..", "..", "..", "..", "etc"),
|
||||
shouldErr: true,
|
||||
verifyErr: os.IsNotExist,
|
||||
},
|
||||
}
|
||||
|
||||
for i, test := range tests {
|
||||
context := getContextOrFail(t)
|
||||
testPrefix := getTestPrefix(i + 1)
|
||||
var dirPath string
|
||||
var err error
|
||||
|
||||
// Create directory / files from test case.
|
||||
if test.fileNames != nil {
|
||||
dirPath, err = ioutil.TempDir(fmt.Sprintf("%s", context.Root), "caddy_ctxtest")
|
||||
if err != nil {
|
||||
os.RemoveAll(dirPath)
|
||||
t.Fatalf(testPrefix+"Expected no error creating directory, got: '%s'", err.Error())
|
||||
}
|
||||
|
||||
for _, name := range test.fileNames {
|
||||
absFilePath := filepath.Join(dirPath, name)
|
||||
if err = ioutil.WriteFile(absFilePath, []byte(""), os.ModePerm); err != nil {
|
||||
os.RemoveAll(dirPath)
|
||||
t.Fatalf(testPrefix+"Expected no error creating file, got: '%s'", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Perform test case.
|
||||
input := filepath.ToSlash(filepath.Join(filepath.Base(dirPath), test.inputBase))
|
||||
actual, err := context.Files(input)
|
||||
if err != nil {
|
||||
if !test.shouldErr {
|
||||
t.Errorf(testPrefix+"Expected no error, got: '%s'", err.Error())
|
||||
} else if !test.verifyErr(err) {
|
||||
t.Errorf(testPrefix+"Could not verify error content, got: '%s'", err.Error())
|
||||
}
|
||||
} else if test.shouldErr {
|
||||
t.Errorf(testPrefix + "Expected error but had none")
|
||||
} else {
|
||||
numFiles := len(test.fileNames)
|
||||
// reflect.DeepEqual does not consider two empty slices to be equal
|
||||
if numFiles == 0 && len(actual) != 0 {
|
||||
t.Errorf(testPrefix+"Expected files %v, got: %v",
|
||||
test.fileNames, actual)
|
||||
} else {
|
||||
sort.Strings(actual)
|
||||
if numFiles > 0 && !reflect.DeepEqual(test.fileNames, actual) {
|
||||
t.Errorf(testPrefix+"Expected files %v, got: %v",
|
||||
test.fileNames, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if dirPath != "" {
|
||||
if err := os.RemoveAll(dirPath); err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf(testPrefix+"Expected no error removing directory, got: '%s'", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user