├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── README.md ├── circle.yml ├── examples ├── passthrough.rs └── proxy.rs ├── scripts └── circleci │ ├── build.sh │ └── test.sh └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | target 3 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | [root] 2 | name = "mysql-proxy" 3 | version = "0.2.1" 4 | dependencies = [ 5 | "byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", 6 | "curl 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 7 | "env_logger 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", 8 | "futures 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 9 | "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 10 | "tokio-core 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 11 | ] 12 | 13 | [[package]] 14 | name = "aho-corasick" 15 | version = "0.5.2" 16 | source = "registry+https://github.com/rust-lang/crates.io-index" 17 | dependencies = [ 18 | "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", 19 | ] 20 | 21 | [[package]] 22 | name = "bitflags" 23 | version = "0.4.0" 24 | source = "registry+https://github.com/rust-lang/crates.io-index" 25 | 26 | [[package]] 27 | name = "byteorder" 28 | version = "0.5.3" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | 31 | [[package]] 32 | name = "cfg-if" 33 | version = "0.1.0" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | 36 | [[package]] 37 | name = "curl" 38 | version = "0.3.6" 39 | source = "registry+https://github.com/rust-lang/crates.io-index" 40 | dependencies = [ 41 | "curl-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", 42 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 43 | "openssl-sys 0.7.17 (registry+https://github.com/rust-lang/crates.io-index)", 44 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 45 | ] 46 | 47 | [[package]] 48 | name = "curl-sys" 49 | version = "0.2.2" 50 | source = "registry+https://github.com/rust-lang/crates.io-index" 51 | dependencies = [ 52 | "gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", 53 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 54 | "libz-sys 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", 55 | "openssl-sys 0.7.17 (registry+https://github.com/rust-lang/crates.io-index)", 56 | "pkg-config 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 57 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 58 | ] 59 | 60 | [[package]] 61 | name = "env_logger" 62 | version = "0.3.5" 63 | source = "registry+https://github.com/rust-lang/crates.io-index" 64 | dependencies = [ 65 | "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 66 | "regex 0.1.75 (registry+https://github.com/rust-lang/crates.io-index)", 67 | ] 68 | 69 | [[package]] 70 | name = "futures" 71 | version = "0.1.1" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | dependencies = [ 74 | "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 75 | ] 76 | 77 | [[package]] 78 | name = "gcc" 79 | version = "0.3.35" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | 82 | [[package]] 83 | name = "gdi32-sys" 84 | version = "0.2.0" 85 | source = "registry+https://github.com/rust-lang/crates.io-index" 86 | dependencies = [ 87 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 88 | "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 89 | ] 90 | 91 | [[package]] 92 | name = "kernel32-sys" 93 | version = "0.2.2" 94 | source = "registry+https://github.com/rust-lang/crates.io-index" 95 | dependencies = [ 96 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 97 | "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 98 | ] 99 | 100 | [[package]] 101 | name = "lazycell" 102 | version = "0.4.0" 103 | source = "registry+https://github.com/rust-lang/crates.io-index" 104 | 105 | [[package]] 106 | name = "libc" 107 | version = "0.2.15" 108 | source = "registry+https://github.com/rust-lang/crates.io-index" 109 | 110 | [[package]] 111 | name = "libressl-pnacl-sys" 112 | version = "2.1.6" 113 | source = "registry+https://github.com/rust-lang/crates.io-index" 114 | dependencies = [ 115 | "pnacl-build-helper 1.4.10 (registry+https://github.com/rust-lang/crates.io-index)", 116 | ] 117 | 118 | [[package]] 119 | name = "libz-sys" 120 | version = "1.0.6" 121 | source = "registry+https://github.com/rust-lang/crates.io-index" 122 | dependencies = [ 123 | "gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", 124 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 125 | "pkg-config 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 126 | ] 127 | 128 | [[package]] 129 | name = "log" 130 | version = "0.3.6" 131 | source = "registry+https://github.com/rust-lang/crates.io-index" 132 | 133 | [[package]] 134 | name = "memchr" 135 | version = "0.1.11" 136 | source = "registry+https://github.com/rust-lang/crates.io-index" 137 | dependencies = [ 138 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 139 | ] 140 | 141 | [[package]] 142 | name = "mio" 143 | version = "0.6.0" 144 | source = "registry+https://github.com/rust-lang/crates.io-index" 145 | dependencies = [ 146 | "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", 147 | "lazycell 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 148 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 149 | "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 150 | "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", 151 | "net2 0.2.26 (registry+https://github.com/rust-lang/crates.io-index)", 152 | "nix 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", 153 | "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", 154 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 155 | ] 156 | 157 | [[package]] 158 | name = "miow" 159 | version = "0.1.3" 160 | source = "registry+https://github.com/rust-lang/crates.io-index" 161 | dependencies = [ 162 | "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", 163 | "net2 0.2.26 (registry+https://github.com/rust-lang/crates.io-index)", 164 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 165 | "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 166 | ] 167 | 168 | [[package]] 169 | name = "net2" 170 | version = "0.2.26" 171 | source = "registry+https://github.com/rust-lang/crates.io-index" 172 | dependencies = [ 173 | "cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 174 | "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", 175 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 176 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 177 | "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 178 | ] 179 | 180 | [[package]] 181 | name = "nix" 182 | version = "0.6.0" 183 | source = "registry+https://github.com/rust-lang/crates.io-index" 184 | dependencies = [ 185 | "bitflags 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 186 | "cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 187 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 188 | "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 189 | "semver 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)", 190 | "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", 191 | ] 192 | 193 | [[package]] 194 | name = "openssl-sys" 195 | version = "0.7.17" 196 | source = "registry+https://github.com/rust-lang/crates.io-index" 197 | dependencies = [ 198 | "gdi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", 199 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 200 | "libressl-pnacl-sys 2.1.6 (registry+https://github.com/rust-lang/crates.io-index)", 201 | "pkg-config 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 202 | "user32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", 203 | ] 204 | 205 | [[package]] 206 | name = "pkg-config" 207 | version = "0.3.8" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | 210 | [[package]] 211 | name = "pnacl-build-helper" 212 | version = "1.4.10" 213 | source = "registry+https://github.com/rust-lang/crates.io-index" 214 | dependencies = [ 215 | "tempdir 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", 216 | ] 217 | 218 | [[package]] 219 | name = "rand" 220 | version = "0.3.14" 221 | source = "registry+https://github.com/rust-lang/crates.io-index" 222 | dependencies = [ 223 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 224 | ] 225 | 226 | [[package]] 227 | name = "regex" 228 | version = "0.1.75" 229 | source = "registry+https://github.com/rust-lang/crates.io-index" 230 | dependencies = [ 231 | "aho-corasick 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", 232 | "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", 233 | "regex-syntax 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", 234 | "thread_local 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", 235 | "utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", 236 | ] 237 | 238 | [[package]] 239 | name = "regex-syntax" 240 | version = "0.3.5" 241 | source = "registry+https://github.com/rust-lang/crates.io-index" 242 | 243 | [[package]] 244 | name = "rustc_version" 245 | version = "0.1.7" 246 | source = "registry+https://github.com/rust-lang/crates.io-index" 247 | dependencies = [ 248 | "semver 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)", 249 | ] 250 | 251 | [[package]] 252 | name = "scoped-tls" 253 | version = "0.1.0" 254 | source = "registry+https://github.com/rust-lang/crates.io-index" 255 | 256 | [[package]] 257 | name = "semver" 258 | version = "0.1.20" 259 | source = "registry+https://github.com/rust-lang/crates.io-index" 260 | 261 | [[package]] 262 | name = "slab" 263 | version = "0.3.0" 264 | source = "registry+https://github.com/rust-lang/crates.io-index" 265 | 266 | [[package]] 267 | name = "tempdir" 268 | version = "0.3.5" 269 | source = "registry+https://github.com/rust-lang/crates.io-index" 270 | dependencies = [ 271 | "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", 272 | ] 273 | 274 | [[package]] 275 | name = "thread-id" 276 | version = "2.0.0" 277 | source = "registry+https://github.com/rust-lang/crates.io-index" 278 | dependencies = [ 279 | "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", 280 | "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", 281 | ] 282 | 283 | [[package]] 284 | name = "thread_local" 285 | version = "0.2.6" 286 | source = "registry+https://github.com/rust-lang/crates.io-index" 287 | dependencies = [ 288 | "thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", 289 | ] 290 | 291 | [[package]] 292 | name = "tokio-core" 293 | version = "0.1.0" 294 | source = "registry+https://github.com/rust-lang/crates.io-index" 295 | dependencies = [ 296 | "futures 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 297 | "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 298 | "mio 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", 299 | "scoped-tls 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 300 | "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", 301 | ] 302 | 303 | [[package]] 304 | name = "user32-sys" 305 | version = "0.2.0" 306 | source = "registry+https://github.com/rust-lang/crates.io-index" 307 | dependencies = [ 308 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 309 | "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 310 | ] 311 | 312 | [[package]] 313 | name = "utf8-ranges" 314 | version = "0.1.3" 315 | source = "registry+https://github.com/rust-lang/crates.io-index" 316 | 317 | [[package]] 318 | name = "void" 319 | version = "1.0.2" 320 | source = "registry+https://github.com/rust-lang/crates.io-index" 321 | 322 | [[package]] 323 | name = "winapi" 324 | version = "0.2.8" 325 | source = "registry+https://github.com/rust-lang/crates.io-index" 326 | 327 | [[package]] 328 | name = "winapi-build" 329 | version = "0.1.1" 330 | source = "registry+https://github.com/rust-lang/crates.io-index" 331 | 332 | [[package]] 333 | name = "ws2_32-sys" 334 | version = "0.2.1" 335 | source = "registry+https://github.com/rust-lang/crates.io-index" 336 | dependencies = [ 337 | "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", 338 | "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 339 | ] 340 | 341 | [metadata] 342 | "checksum aho-corasick 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "2b3fb52b09c1710b961acb35390d514be82e4ac96a9969a8e38565a29b878dc9" 343 | "checksum bitflags 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8dead7461c1127cf637931a1e50934eb6eee8bff2f74433ac7909e9afcee04a3" 344 | "checksum byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0fc10e8cc6b2580fda3f36eb6dc5316657f812a3df879a44a66fc9f0fdbc4855" 345 | "checksum cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "de1e760d7b6535af4241fca8bd8adf68e2e7edacc6b29f5d399050c5e48cf88c" 346 | "checksum curl 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "38395d4ef95c50a2fee6b1dfe2abd7fe79ade4b3fda1babbbf2d382f2bb7905d" 347 | "checksum curl-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "25f03869ad83edb2b483ff465f07fea06ba7eb2973f52aa23a72b2902744287c" 348 | "checksum env_logger 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "15abd780e45b3ea4f76b4e9a26ff4843258dd8a3eed2775a0e7368c2e7936c2f" 349 | "checksum futures 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "62af3ebbb8916ecf7ebcc4c130aacc33cc7f48d8b6e74fc9ed010bfa4f359794" 350 | "checksum gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)" = "91ecd03771effb0c968fd6950b37e89476a578aaf1c70297d8e92b6516ec3312" 351 | "checksum gdi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0912515a8ff24ba900422ecda800b52f4016a56251922d397c576bf92c690518" 352 | "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" 353 | "checksum lazycell 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ce12306c4739d86ee97c23139f3a34ddf0387bbf181bc7929d287025a8c3ef6b" 354 | "checksum libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)" = "23e3757828fa702a20072c37ff47938e9dd331b92fac6e223d26d4b7a55f7ee2" 355 | "checksum libressl-pnacl-sys 2.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "cbc058951ab6a3ef35ca16462d7642c4867e6403520811f28537a4e2f2db3e71" 356 | "checksum libz-sys 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "40f2df7730b5d29426c3e44ce4d088d8c5def6471c2c93ba98585b89fb201ce6" 357 | "checksum log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ab83497bf8bf4ed2a74259c1c802351fcd67a65baa86394b6ba73c36f4838054" 358 | "checksum memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d8b629fb514376c675b98c1421e80b151d3817ac42d7c667717d282761418d20" 359 | "checksum mio 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2dadd39d4b47343e10513ac2a731c979517a4761224ecb6bbd243602300c9537" 360 | "checksum miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d5bfc6782530ac8ace97af10a540054a37126b63b0702ddaaa243b73b5745b9a" 361 | "checksum net2 0.2.26 (registry+https://github.com/rust-lang/crates.io-index)" = "5edf9cb6be97212423aed9413dd4729d62b370b5e1c571750e882cebbbc1e3e2" 362 | "checksum nix 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a7bb1da2be7da3cbffda73fc681d509ffd9e665af478d2bee1907cee0bc64b2" 363 | "checksum openssl-sys 0.7.17 (registry+https://github.com/rust-lang/crates.io-index)" = "89c47ee94c352eea9ddaf8e364be7f978a3bb6d66d73176572484238dd5a5c3f" 364 | "checksum pkg-config 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8cee804ecc7eaf201a4a207241472cc870e825206f6c031e3ee2a72fa425f2fa" 365 | "checksum pnacl-build-helper 1.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "61c9231d31aea845007443d62fcbb58bb6949ab9c18081ee1e09920e0cf1118b" 366 | "checksum rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "2791d88c6defac799c3f20d74f094ca33b9332612d9aef9078519c82e4fe04a5" 367 | "checksum regex 0.1.75 (registry+https://github.com/rust-lang/crates.io-index)" = "f62414f9d3b0f53e827ac46d6f8ce2ff6a91afd724225a5986e54e81e170693c" 368 | "checksum regex-syntax 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "279401017ae31cf4e15344aa3f085d0e2e5c1e70067289ef906906fdbe92c8fd" 369 | "checksum rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "c5f5376ea5e30ce23c03eb77cbe4962b988deead10910c372b226388b594c084" 370 | "checksum scoped-tls 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f417c22df063e9450888a7561788e9bd46d3bb3c1466435b4eccb903807f147d" 371 | "checksum semver 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)" = "d4f410fedcf71af0345d7607d246e7ad15faaadd49d240ee3b24e5dc21a820ac" 372 | "checksum slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "17b4fcaed89ab08ef143da37bc52adbcc04d4a69014f4c1208d6b51f0c47bc23" 373 | "checksum tempdir 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "87974a6f5c1dfb344d733055601650059a3363de2a6104819293baff662132d6" 374 | "checksum thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a9539db560102d1cef46b8b78ce737ff0bb64e7e18d35b2a5688f7d097d0ff03" 375 | "checksum thread_local 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "55dd963dbaeadc08aa7266bf7f91c3154a7805e32bb94b820b769d2ef3b4744d" 376 | "checksum tokio-core 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "659cbae6c954dee37352853816c6a52180e47feb70be73bbfeec6d58c4da4a71" 377 | "checksum user32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4ef4711d107b21b410a3a974b1204d9accc8b10dad75d8324b5d755de1617d47" 378 | "checksum utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a1ca13c08c41c9c3e04224ed9ff80461d97e121589ff27c753a16cb10830ae0f" 379 | "checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" 380 | "checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" 381 | "checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" 382 | "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" 383 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mysql-proxy" 3 | description = "Extensible MySQL Proxy" 4 | version = "0.2.1" 5 | authors = ["Andy Grove "] 6 | homepage = "https://github.com/AgilData/mysql-proxy-rs" 7 | documentation = "https://github.com/AgilData/mysql-proxy-rs" 8 | repository = "https://github.com/AgilData/mysql-proxy-rs" 9 | license = "Apache-2.0" 10 | 11 | [dependencies] 12 | log = "0.3" 13 | futures = "0.1.1" 14 | tokio-core = "0.1.0" 15 | env_logger = "0.3" 16 | byteorder = "0.5.3" 17 | 18 | [dev-dependencies] 19 | curl = "=0.3.6" 20 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mysql-proxy-rs 2 | 3 | [![CircleCI](https://circleci.com/gh/AgilData/mysql-proxy-rs/tree/master.svg?style=svg)](https://circleci.com/gh/AgilData/mysql-proxy-rs/tree/master) 4 | [![Version](https://img.shields.io/crates/v/mysql-proxy.svg)](https://crates.io/crates/mysql-proxy) 5 | [![Docs](https://docs.rs/mysql-proxy/badge.svg)](https://docs.rs/mysql-proxy) 6 | 7 | An implementation of a MySQL proxy server built on top of `tokio-core`. 8 | 9 | ## Overview 10 | 11 | This crate provides a MySQL proxy server that you can extend with your own custom logic. Here are some examples of use cases for a proxy: 12 | 13 | - Capture a log of SQL queries issued by an application 14 | - Profiling of query execution time 15 | - Monitor query patterns e.g. threat detection 16 | - Record SQL traffic for later playback for automated testing 17 | 18 | ## Usage 19 | 20 | The proxy defines the following trait for defining a packet handler for handling request and response packets: 21 | 22 | ```rust 23 | pub trait PacketHandler { 24 | fn handle_request(&self, p: &Packet) -> Action; 25 | fn handle_response(&self, p: &Packet) -> Action; 26 | } 27 | 28 | /// Handlers return a variant of this enum to indicate how the proxy should handle the packet. 29 | pub enum Action { 30 | /// drop the packet 31 | Drop, 32 | /// forward the packet unmodified 33 | Forward, 34 | /// forward a mutated packet 35 | Mutate(Packet), 36 | /// respond to the packet without forwarding 37 | Respond(Vec), 38 | /// respond with an error packet 39 | Error { code: u16, state: [u8; 5], msg: String }, 40 | } 41 | 42 | ``` 43 | 44 | ## Example 45 | 46 | The example proxy passes all queries to MySQL except for queries containing the word 'avocado'. Use the following command to run the example. 47 | 48 | Note that we have tested the proxy with `rustc 1.13.0-nightly (cbe4de78e 2016-09-05)`. 49 | 50 | ``` 51 | $ cargo run --example proxy 52 | ``` 53 | 54 | Then in a separate window you can test out the proxy. The proxy binds to port 3307 and assumes that a MySQL server is running on port 3306. 55 | 56 | ``` 57 | $ mysql -u root -p -h 127.0.0.1 -P 3307 58 | ``` 59 | 60 | ```sql 61 | mysql> select 'banana'; 62 | +--------+ 63 | | banana | 64 | +--------+ 65 | | banana | 66 | +--------+ 67 | 1 row in set (0.00 sec) 68 | 69 | mysql> select 'avocado'; 70 | ERROR 1064 (12345): Proxy rejecting any avocado-related queries 71 | ``` 72 | 73 | # License 74 | 75 | `mysql-proxy-rs` is distributed under the terms of the Apache License (Version 2.0). 76 | 77 | See LICENSE-APACHE for details. 78 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | dependencies: 2 | override: 3 | - rm -f ~/.gitconfig 4 | - if [ ! -f "/home/ubuntu/rustup.sh" ]; then curl https://sh.rustup.rs -sSf > /home/ubuntu/rustup.sh && chmod ogu+x /home/ubuntu/rustup.sh && /home/ubuntu/rustup.sh -y ; fi 5 | - echo "source $HOME/.cargo/env" >> ~/.bashrc 6 | - /bin/bash scripts/circleci/build.sh 7 | 8 | cache_directories: 9 | - "~/rustup.sh" 10 | - "~/.cargo" 11 | - "~/.multirust" 12 | 13 | test: 14 | override: 15 | - /bin/bash scripts/circleci/test.sh 16 | -------------------------------------------------------------------------------- /examples/passthrough.rs: -------------------------------------------------------------------------------- 1 | //! MySQL Proxy Server 2 | extern crate mysql_proxy; 3 | use mysql_proxy::*; 4 | 5 | #[macro_use] 6 | extern crate log; 7 | extern crate env_logger; 8 | #[macro_use] 9 | extern crate futures; 10 | #[macro_use] 11 | extern crate tokio_core; 12 | extern crate byteorder; 13 | 14 | use std::rc::Rc; 15 | use std::env; 16 | use std::net::{SocketAddr}; 17 | use std::str; 18 | 19 | use futures::{Future}; 20 | use futures::stream::Stream; 21 | use tokio_core::net::{TcpStream, TcpListener}; 22 | use tokio_core::reactor::{Core}; 23 | 24 | fn main() { 25 | env_logger::init().unwrap(); 26 | 27 | // determine address for the proxy to bind to 28 | let bind_addr = env::args().nth(1).unwrap_or("127.0.0.1:3307".to_string()); 29 | let bind_addr = bind_addr.parse::().unwrap(); 30 | 31 | // determine address of the MySQL instance we are proxying for 32 | let mysql_addr = env::args().nth(2).unwrap_or("127.0.0.1:3306".to_string()); 33 | let mysql_addr = mysql_addr.parse::().unwrap(); 34 | 35 | // Create the tokio event loop that will drive this server 36 | let mut l = Core::new().unwrap(); 37 | 38 | // Get a reference to the reactor event loop 39 | let handle = l.handle(); 40 | 41 | // Create a TCP listener which will listen for incoming connections 42 | let socket = TcpListener::bind(&bind_addr, &l.handle()).unwrap(); 43 | println!("Listening on: {}", bind_addr); 44 | 45 | // for each incoming connection 46 | let done = socket.incoming().for_each(move |(socket, _)| { 47 | 48 | // create a future to serve requests 49 | let future = TcpStream::connect(&mysql_addr, &handle) 50 | .and_then(move |mysql| { Ok((socket, mysql)) }) 51 | .and_then(move |(client, server)| 52 | { Pipe::new(Rc::new(client), Rc::new(server), PassthroughHandler {}) 53 | }); 54 | 55 | // tell the tokio reactor to run the future 56 | handle.spawn(future.map_err(|err| { 57 | println!("Failed to spawn future: {:?}", err); 58 | })); 59 | 60 | // everything is great! 61 | Ok(()) 62 | 63 | }); 64 | l.run(done).unwrap(); 65 | } 66 | 67 | struct PassthroughHandler {} 68 | 69 | impl PacketHandler for PassthroughHandler { 70 | 71 | fn handle_request(&mut self, _: &Packet) -> Action { 72 | Action::Forward 73 | } 74 | 75 | fn handle_response(&mut self, _: &Packet) -> Action { 76 | // forward all responses to the client 77 | Action::Forward 78 | } 79 | 80 | } 81 | 82 | #[allow(dead_code)] 83 | pub fn print_packet_chars(buf: &[u8]) { 84 | print!("["); 85 | for i in 0..buf.len() { 86 | print!("{} ", buf[i] as char); 87 | } 88 | println!("]"); 89 | } 90 | 91 | #[allow(dead_code)] 92 | pub fn print_packet_bytes(buf: &[u8]) { 93 | print!("["); 94 | for i in 0..buf.len() { 95 | if i%8==0 { println!(""); } 96 | print!("{:#04x} ",buf[i]); 97 | } 98 | println!("]"); 99 | } 100 | -------------------------------------------------------------------------------- /examples/proxy.rs: -------------------------------------------------------------------------------- 1 | //! MySQL Proxy Server 2 | extern crate mysql_proxy; 3 | use mysql_proxy::*; 4 | 5 | #[macro_use] 6 | extern crate log; 7 | extern crate env_logger; 8 | #[macro_use] 9 | extern crate futures; 10 | #[macro_use] 11 | extern crate tokio_core; 12 | extern crate byteorder; 13 | 14 | use std::rc::Rc; 15 | use std::env; 16 | use std::net::{SocketAddr}; 17 | use std::str; 18 | 19 | use futures::{Future}; 20 | use futures::stream::Stream; 21 | use tokio_core::net::{TcpStream, TcpListener}; 22 | use tokio_core::reactor::{Core}; 23 | 24 | fn main() { 25 | 26 | env_logger::init().unwrap(); 27 | 28 | // determine address for the proxy to bind to 29 | let bind_addr = env::args().nth(1).unwrap_or("127.0.0.1:3307".to_string()); 30 | let bind_addr = bind_addr.parse::().unwrap(); 31 | 32 | // determine address of the MySQL instance we are proxying for 33 | let mysql_addr = env::args().nth(2).unwrap_or("127.0.0.1:3306".to_string()); 34 | let mysql_addr = mysql_addr.parse::().unwrap(); 35 | 36 | // Create the tokio event loop that will drive this server 37 | let mut l = Core::new().unwrap(); 38 | 39 | // Get a reference to the reactor event loop 40 | let handle = l.handle(); 41 | 42 | // Create a TCP listener which will listen for incoming connections 43 | let socket = TcpListener::bind(&bind_addr, &l.handle()).unwrap(); 44 | println!("Listening on: {}", bind_addr); 45 | 46 | // for each incoming connection 47 | let done = socket.incoming().for_each(move |(socket, _)| { 48 | 49 | // create a future to serve requests 50 | let future = TcpStream::connect(&mysql_addr, &handle) 51 | .and_then(move |mysql| { Ok((socket, mysql)) }) 52 | .and_then(move |(client, server)| 53 | { Pipe::new(Rc::new(client), Rc::new(server), DemoHandler {}) 54 | }); 55 | 56 | // tell the tokio reactor to run the future 57 | handle.spawn(future.map_err(|err| { 58 | println!("Failed to spawn future: {:?}", err); 59 | })); 60 | 61 | // everything is great! 62 | Ok(()) 63 | 64 | }); 65 | l.run(done).unwrap(); 66 | } 67 | 68 | struct DemoHandler {} 69 | 70 | impl PacketHandler for DemoHandler { 71 | 72 | fn handle_request(&mut self, p: &Packet) -> Action { 73 | print_packet_chars(&p.bytes); 74 | match p.packet_type() { 75 | Ok(PacketType::ComQuery) => { 76 | // ComQuery packets just contain a SQL string as the payload 77 | let slice = &p.bytes[5..]; 78 | 79 | // convert the slice to a String object 80 | let sql = String::from_utf8(slice.to_vec()).expect("Invalid UTF-8"); 81 | 82 | // log the query 83 | println!("SQL: {}", sql); 84 | 85 | // dumb example of conditional proxy behavior 86 | if sql.contains("avocado") { 87 | // take over processing of this packet and return an error packet 88 | // to the client 89 | Action::Error { 90 | code: 1064, // error code 91 | state: [0x31, 0x32, 0x33, 0x34, 0x35], // sql state 92 | msg: String::from("Proxy rejecting any avocado-related queries") 93 | } 94 | } else { 95 | // pass the packet to MySQL unmodified 96 | Action::Forward 97 | } 98 | }, 99 | _ => Action::Forward 100 | } 101 | } 102 | 103 | fn handle_response(&mut self, _: &Packet) -> Action { 104 | // forward all responses to the client 105 | Action::Forward 106 | } 107 | 108 | } 109 | #[allow(dead_code)] 110 | pub fn print_packet_chars(buf: &[u8]) { 111 | print!("["); 112 | for i in 0..buf.len() { 113 | print!("{} ", buf[i] as char); 114 | } 115 | println!("]"); 116 | } 117 | 118 | #[allow(dead_code)] 119 | pub fn print_packet_bytes(buf: &[u8]) { 120 | print!("["); 121 | for i in 0..buf.len() { 122 | if i%8==0 { println!(""); } 123 | print!("{:#04x} ",buf[i]); 124 | } 125 | println!("]"); 126 | } 127 | 128 | 129 | -------------------------------------------------------------------------------- /scripts/circleci/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Build script to build 4 | 5 | source ~/.cargo/env 6 | 7 | echo 8 | echo "Setting default to nightly build of Rust." 9 | rustup default nightly 10 | rustup override set nightly 11 | 12 | echo 13 | echo "Building Project." 14 | RUST_BACKTRACE=1 cargo build 15 | -------------------------------------------------------------------------------- /scripts/circleci/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Runs the test suite 4 | 5 | source ~/.cargo/env 6 | RUST_BACKTRACE=1 cargo test 7 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! An extensible MySQL Proxy Server based on tokio-core 2 | 3 | #[macro_use] 4 | extern crate log; 5 | extern crate env_logger; 6 | #[macro_use] 7 | extern crate futures; 8 | #[macro_use] 9 | extern crate tokio_core; 10 | extern crate byteorder; 11 | 12 | use std::rc::Rc; 13 | use std::io::{self, Read, Write, Error, ErrorKind}; 14 | use std::net::Shutdown; 15 | 16 | use futures::{Future, Poll, Async}; 17 | use tokio_core::net::{TcpStream}; 18 | use byteorder::*; 19 | 20 | /// Handlers return a variant of this enum to indicate how the proxy should handle the packet. 21 | #[derive(Debug,PartialEq)] 22 | pub enum Action { 23 | /// drop the packet 24 | Drop, 25 | /// forward the packet unmodified 26 | Forward, 27 | /// forward a mutated packet 28 | Mutate(Packet), 29 | /// respond to the packet without forwarding 30 | Respond(Vec), 31 | /// respond with an error packet 32 | Error { code: u16, state: [u8; 5], msg: String }, 33 | } 34 | 35 | /// Packet handlers need to implement this trait 36 | pub trait PacketHandler { 37 | fn handle_request(&mut self, p: &Packet) -> Action; 38 | fn handle_response(&mut self, p: &Packet) -> Action; 39 | } 40 | 41 | /// A packet is just a wrapper for a Vec 42 | #[derive(Debug,PartialEq)] 43 | pub struct Packet { 44 | pub bytes: Vec 45 | } 46 | 47 | impl Packet { 48 | 49 | /// Create an error packet 50 | pub fn error_packet(code: u16, state: [u8; 5], msg: String) -> Self { 51 | 52 | // start building payload 53 | let mut payload: Vec = Vec::with_capacity(9 + msg.len()); 54 | payload.push(0xff); // packet type 55 | payload.write_u16::(code).unwrap(); // error code 56 | payload.extend_from_slice("#".as_bytes()); // sql_state_marker 57 | payload.extend_from_slice(&state); // SQL STATE 58 | payload.extend_from_slice(msg.as_bytes()); 59 | 60 | // create header with length and sequence id 61 | let mut header: Vec = Vec::with_capacity(4 + 9 + msg.len()); 62 | header.write_u32::(payload.len() as u32).unwrap(); 63 | header.pop(); // we need 3 byte length, so discard last byte 64 | header.push(1); // sequence_id 65 | 66 | // combine the vectors 67 | header.extend_from_slice(&payload); 68 | 69 | // now move the vector into the packet 70 | Packet { bytes: header } 71 | } 72 | 73 | pub fn sequence_id(&self) -> u8 { 74 | self.bytes[3] 75 | } 76 | 77 | /// Determine the type of packet 78 | pub fn packet_type(&self) -> Result { 79 | match self.bytes[4] { 80 | 0x00 => Ok(PacketType::ComSleep), 81 | 0x01 => Ok(PacketType::ComQuit), 82 | 0x02 => Ok(PacketType::ComInitDb), 83 | 0x03 => Ok(PacketType::ComQuery), 84 | 0x04 => Ok(PacketType::ComFieldList), 85 | 0x05 => Ok(PacketType::ComCreateDb), 86 | 0x06 => Ok(PacketType::ComDropDb), 87 | 0x07 => Ok(PacketType::ComRefresh), 88 | 0x08 => Ok(PacketType::ComShutdown), 89 | 0x09 => Ok(PacketType::ComStatistics), 90 | 0x0a => Ok(PacketType::ComProcessInfo), 91 | 0x0b => Ok(PacketType::ComConnect), 92 | 0x0c => Ok(PacketType::ComProcessKill), 93 | 0x0d => Ok(PacketType::ComDebug), 94 | 0x0e => Ok(PacketType::ComPing), 95 | 0x0f => Ok(PacketType::ComTime), 96 | 0x10 => Ok(PacketType::ComDelayedInsert), 97 | 0x11 => Ok(PacketType::ComChangeUser), 98 | 0x12 => Ok(PacketType::ComBinlogDump), 99 | 0x13 => Ok(PacketType::ComTableDump), 100 | 0x14 => Ok(PacketType::ComConnectOut), 101 | 0x15 => Ok(PacketType::ComRegisterSlave), 102 | 0x16 => Ok(PacketType::ComStmtPrepare), 103 | 0x17 => Ok(PacketType::ComStmtExecute), 104 | 0x18 => Ok(PacketType::ComStmtSendLongData), 105 | 0x19 => Ok(PacketType::ComStmtClose), 106 | 0x1a => Ok(PacketType::ComStmtReset), 107 | 0x1d => Ok(PacketType::ComDaemon), 108 | 0x1e => Ok(PacketType::ComBinlogDumpGtid), 109 | 0x1f => Ok(PacketType::ComResetConnection), 110 | _ => Err(Error::new(ErrorKind::Other, "Invalid packet type")) 111 | } 112 | } 113 | 114 | } 115 | 116 | #[derive(Copy,Clone)] 117 | pub enum PacketType { 118 | ComSleep = 0x00, 119 | ComQuit = 0x01, 120 | ComInitDb = 0x02, 121 | ComQuery = 0x03, 122 | ComFieldList = 0x04, 123 | ComCreateDb = 0x05, 124 | ComDropDb = 0x06, 125 | ComRefresh = 0x07, 126 | ComShutdown = 0x08, 127 | ComStatistics = 0x09, 128 | ComProcessInfo = 0x0a, 129 | ComConnect = 0x0b, 130 | ComProcessKill= 0x0c, 131 | ComDebug = 0x0d, 132 | ComPing = 0x0e, 133 | ComTime = 0x0f, 134 | ComDelayedInsert = 0x10, 135 | ComChangeUser = 0x11, 136 | ComBinlogDump = 0x12, 137 | ComTableDump = 0x13, 138 | ComConnectOut = 0x14, 139 | ComRegisterSlave = 0x15, 140 | ComStmtPrepare = 0x16, 141 | ComStmtExecute = 0x17, 142 | ComStmtSendLongData = 0x18, 143 | ComStmtClose = 0x19, 144 | ComStmtReset = 0x1a, 145 | ComDaemon= 0x1d, 146 | ComBinlogDumpGtid = 0x1e, 147 | ComResetConnection = 0x1f, 148 | } 149 | 150 | 151 | /// Wrapper for TcpStream with some built-in buffering 152 | struct ConnReader { 153 | stream: Rc, 154 | packet_buf: Vec, 155 | read_buf: Vec, 156 | } 157 | 158 | /// Wrapper for TcpStream with some built-in buffering 159 | struct ConnWriter { 160 | stream: Rc, 161 | write_buf: Vec, 162 | } 163 | 164 | impl ConnReader { 165 | 166 | fn new(stream: Rc) -> Self { 167 | ConnReader { 168 | stream: stream, 169 | packet_buf: Vec::with_capacity(4096), 170 | read_buf: vec![0_u8; 4096] 171 | } 172 | } 173 | 174 | /// Read from the socket until the status is NotReady 175 | fn read(&mut self) -> Poll<(), io::Error> { 176 | debug!("read()"); 177 | loop { 178 | match self.stream.poll_read() { 179 | Async::Ready(_) => { 180 | let n = try_nb!((&*self.stream).read(&mut self.read_buf[..])); 181 | if n == 0 { 182 | return Err(Error::new(ErrorKind::Other, "connection closed")); 183 | } 184 | self.packet_buf.extend_from_slice(&self.read_buf[0..n]); 185 | }, 186 | _ => return Ok(Async::NotReady), 187 | } 188 | } 189 | } 190 | 191 | fn next(&mut self) -> Option { 192 | debug!("next()"); 193 | // do we have a header 194 | if self.packet_buf.len() > 3 { 195 | let l = parse_packet_length(&self.packet_buf); 196 | // do we have the whole packet? 197 | let s = 4 + l; 198 | if self.packet_buf.len() >= s { 199 | let p = Packet { bytes: self.packet_buf.drain(0..s).collect() }; 200 | Some(p) 201 | } else { 202 | None 203 | } 204 | } else { 205 | None 206 | } 207 | } 208 | } 209 | 210 | impl ConnWriter { 211 | 212 | fn new(stream: Rc) -> Self { 213 | ConnWriter{ 214 | stream: stream, 215 | write_buf: Vec::with_capacity(4096), 216 | } 217 | } 218 | 219 | /// Write a packet to the write buffer 220 | fn push(&mut self, p: &Packet) { 221 | // debug!("push() capacity: {} position: {} packet_size: {}", 222 | // self.write_buf.capacity(), self.write_pos, p.bytes.len()); 223 | 224 | self.write_buf.extend_from_slice(&p.bytes); 225 | debug!("end push()"); 226 | } 227 | 228 | /// Writes the contents of the write buffer to the socket 229 | fn write(&mut self) -> Poll<(), io::Error> { 230 | debug!("write()"); 231 | while self.write_buf.len() > 0 { 232 | match self.stream.poll_write() { 233 | Async::Ready(_) => { 234 | let s = try!((&*self.stream).write(&self.write_buf[..])); 235 | let _ : Vec = self.write_buf.drain(0..s).collect(); 236 | }, 237 | _ => return Ok(Async::NotReady) 238 | } 239 | } 240 | return Ok(Async::Ready(())); 241 | } 242 | } 243 | 244 | pub struct Pipe { 245 | client_reader: ConnReader, 246 | client_writer: ConnWriter, 247 | server_reader: ConnReader, 248 | server_writer: ConnWriter, 249 | handler: H, 250 | } 251 | 252 | impl Pipe where H: PacketHandler + 'static { 253 | pub fn new(client: Rc, 254 | server: Rc, 255 | handler: H 256 | ) -> Pipe { 257 | 258 | Pipe { 259 | client_reader: ConnReader::new(client.clone()), 260 | client_writer: ConnWriter::new(client), 261 | server_reader: ConnReader::new(server.clone()), 262 | server_writer: ConnWriter::new(server), 263 | handler: handler, 264 | } 265 | } 266 | } 267 | 268 | impl Future for Pipe where H: PacketHandler + 'static { 269 | type Item = (); 270 | type Error = Error; 271 | 272 | fn poll(&mut self) -> Poll<(), Error> { 273 | loop { 274 | let client_read = self.client_reader.read(); 275 | 276 | // process buffered requests 277 | while let Some(request) = self.client_reader.next() { 278 | match self.handler.handle_request(&request) { 279 | Action::Drop => {}, 280 | Action::Forward => self.server_writer.push(&request), 281 | Action::Mutate(ref p2) => self.server_writer.push(p2), 282 | Action::Respond(ref v) => { 283 | for p in v { 284 | self.client_writer.push(&p); 285 | } 286 | }, 287 | Action::Error { code, state, msg } => { 288 | let error_packet = Packet::error_packet(code, state, msg); 289 | self.client_writer.push(&error_packet); 290 | } 291 | }; 292 | } 293 | 294 | // try reading from server 295 | let server_read = self.server_reader.read(); 296 | 297 | // process buffered responses 298 | while let Some(response) = self.server_reader.next() { 299 | match self.handler.handle_response(&response) { 300 | Action::Drop => {}, 301 | Action::Forward => self.client_writer.push(&response), 302 | Action::Mutate(ref p2) => self.client_writer.push(p2), 303 | Action::Respond(ref v) => { 304 | for p in v { 305 | self.server_writer.push(&p); 306 | } 307 | }, 308 | Action::Error { code, state, msg } => { 309 | let error_packet = Packet::error_packet(code, state, msg); 310 | self.client_writer.push(&error_packet); 311 | } 312 | }; 313 | } 314 | 315 | // perform all of the writes at the end, since the request handlers may have 316 | // queued packets in either, or both directions 317 | 318 | // try writing to client 319 | let client_write = self.client_writer.write(); 320 | 321 | // if the server connection has closed, close the client connection too 322 | match &server_read { 323 | &Err(ref e) => { 324 | debug!("Server closed connection: {}", e); 325 | match self.client_writer.stream.shutdown(Shutdown::Write) { 326 | Ok(_) => {}, 327 | Err(_) => {} 328 | } 329 | }, 330 | _ => {} 331 | } 332 | 333 | // try writing to server 334 | let server_write = self.server_writer.write(); 335 | 336 | // if the client connection has closed, close the server connection too 337 | match &client_read { 338 | &Err(ref e) => { 339 | debug!("Client closed connection: {}", e); 340 | match self.server_writer.stream.shutdown(Shutdown::Write) { 341 | Ok(_) => {}, 342 | Err(_) => {} 343 | } 344 | }, 345 | _ => {} 346 | } 347 | 348 | try_ready!(client_read); 349 | try_ready!(client_write); 350 | try_ready!(server_read); 351 | try_ready!(server_write); 352 | } 353 | 354 | } 355 | 356 | } 357 | 358 | /// Parse the MySQL packet length (3 byte little-endian) 359 | fn parse_packet_length(header: &[u8]) -> usize { 360 | (((header[2] as u32) << 16) | 361 | ((header[1] as u32) << 8) | 362 | header[0] as u32) as usize 363 | } 364 | --------------------------------------------------------------------------------