1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#![deny(missing_docs)]
extern crate byteorder;
extern crate chrono;
extern crate mysql_common as myc;
#[macro_use]
extern crate nom;
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
use std::iter;
use std::net;
pub use myc::constants::{ColumnFlags, ColumnType, StatusFlags};
mod commands;
mod errorcodes;
mod packet;
mod params;
mod resultset;
mod value;
mod writers;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Column {
pub table: String,
pub column: String,
pub coltype: ColumnType,
pub colflags: ColumnFlags,
}
pub use errorcodes::ErrorKind;
pub use params::{ParamParser, ParamValue, Params};
pub use resultset::{QueryResultWriter, RowWriter, StatementMetaWriter};
pub use value::{ToMysqlValue, Value, ValueInner};
pub trait MysqlShim<W: Write> {
type Error: From<io::Error>;
fn on_prepare(&mut self, query: &str, info: StatementMetaWriter<W>) -> Result<(), Self::Error>;
fn on_execute(
&mut self,
id: u32,
params: ParamParser,
results: QueryResultWriter<W>,
) -> Result<(), Self::Error>;
fn on_close(&mut self, stmt: u32);
fn on_query(&mut self, query: &str, results: QueryResultWriter<W>) -> Result<(), Self::Error>;
}
pub struct MysqlIntermediary<B, R: Read, W: Write> {
shim: B,
reader: packet::PacketReader<R>,
writer: packet::PacketWriter<W>,
}
impl<B: MysqlShim<net::TcpStream>> MysqlIntermediary<B, net::TcpStream, net::TcpStream> {
pub fn run_on_tcp(shim: B, stream: net::TcpStream) -> Result<(), B::Error> {
let w = stream.try_clone()?;
MysqlIntermediary::run_on(shim, stream, w)
}
}
impl<B: MysqlShim<S>, S: Read + Write + Clone> MysqlIntermediary<B, S, S> {
pub fn run_on_stream(shim: B, stream: S) -> Result<(), B::Error> {
MysqlIntermediary::run_on(shim, stream.clone(), stream)
}
}
#[derive(Default)]
struct StatementData {
long_data: HashMap<u16, Vec<u8>>,
bound_types: Vec<(myc::constants::ColumnType, bool)>,
params: u16,
}
impl<B: MysqlShim<W>, R: Read, W: Write> MysqlIntermediary<B, R, W> {
pub fn run_on(shim: B, reader: R, writer: W) -> Result<(), B::Error> {
let r = packet::PacketReader::new(reader);
let w = packet::PacketWriter::new(writer);
let mut mi = MysqlIntermediary {
shim,
reader: r,
writer: w,
};
mi.init()?;
mi.run()
}
fn init(&mut self) -> Result<(), B::Error> {
self.writer.write_all(&[10])?;
self.writer.write_all(&b"5.1.10-alpha-msql-proxy\0"[..])?;
self.writer.write_all(&[0x08, 0x00, 0x00, 0x00])?;
self.writer.write_all(&b";X,po_k}\0"[..])?;
self.writer.write_all(&[0x00, 0x42])?;
self.writer.write_all(&[0x21])?;
self.writer.write_all(&[0x00, 0x00])?;
self.writer.write_all(&[0x00, 0x00])?;
self.writer.write_all(&[0x00])?;
self.writer.write_all(&[0x00; 6][..])?;
self.writer.write_all(&[0x00; 4][..])?;
self.writer.write_all(&b">o6^Wz!/kM}N\0"[..])?;
self.writer.flush()?;
{
let (seq, handshake) = self.reader.next()?.unwrap();
let _handshake = commands::client_handshake(&handshake).unwrap().1;
self.writer.set_seq(seq + 1);
}
writers::write_ok_packet(&mut self.writer, 0, 0, StatusFlags::empty())?;
self.writer.flush()?;
Ok(())
}
fn run(mut self) -> Result<(), B::Error> {
use commands::Command;
let mut stmts: HashMap<u32, _> = HashMap::new();
while let Some((seq, packet)) = self.reader.next()? {
self.writer.set_seq(seq + 1);
let cmd = commands::parse(&packet).unwrap().1;
match cmd {
Command::Query(q) => {
let w = QueryResultWriter::new(&mut self.writer, false);
if q.starts_with(b"SELECT @@") || q.starts_with(b"select @@") {
let var = &q[b"SELECT @@".len()..];
match var {
b"max_allowed_packet" => {
let cols = &[Column {
table: String::new(),
column: "@@max_allowed_packet".to_owned(),
coltype: myc::constants::ColumnType::MYSQL_TYPE_SHORT,
colflags: myc::constants::ColumnFlags::UNSIGNED_FLAG,
}];
let mut w = w.start(cols)?;
w.write_row(iter::once(1024u16))?;
w.finish()?;
}
_ => {
w.completed(0, 0)?;
}
}
} else {
self.shim.on_query(
::std::str::from_utf8(q)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
w,
)?;
}
}
Command::Prepare(q) => {
let w = StatementMetaWriter {
writer: &mut self.writer,
stmts: &mut stmts,
};
self.shim.on_prepare(
::std::str::from_utf8(q)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
w,
)?;
}
Command::Execute { stmt, params } => {
let state = stmts.get_mut(&stmt).ok_or(io::Error::new(
io::ErrorKind::InvalidData,
format!("asked to execute unknown statement {}", stmt),
))?;
{
let params = params::ParamParser::new(params, state);
let w = QueryResultWriter::new(&mut self.writer, true);
self.shim.on_execute(stmt, params, w)?;
}
state.long_data.clear();
}
Command::SendLongData { stmt, param, data } => {
stmts
.get_mut(&stmt)
.ok_or(io::Error::new(
io::ErrorKind::InvalidData,
format!("got long data packet for unknown statement {}", stmt),
))?
.long_data
.entry(param)
.or_insert_with(Vec::new)
.extend(data);
}
Command::Close(stmt) => {
self.shim.on_close(stmt);
stmts.remove(&stmt);
}
Command::Init(_) | Command::Ping => {
writers::write_ok_packet(&mut self.writer, 0, 0, StatusFlags::empty())?;
}
Command::Quit => {
break;
}
}
self.writer.flush()?;
}
Ok(())
}
}