forked from rust-postgres/rust-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.rs
More file actions
416 lines (382 loc) · 11.8 KB
/
Copy pathmessage.rs
File metadata and controls
416 lines (382 loc) · 11.8 KB
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::io::{IoResult, IoError, OtherIoError, MemWriter, MemReader};
use std::mem;
use types::Oid;
pub const PROTOCOL_VERSION: u32 = 0x0003_0000;
pub const CANCEL_CODE: u32 = 80877102;
pub const SSL_CODE: u32 = 80877103;
pub enum BackendMessage {
AuthenticationCleartextPassword,
AuthenticationGSS,
AuthenticationKerberosV5,
AuthenticationMD5Password {
pub salt: [u8, ..4]
},
AuthenticationOk,
AuthenticationSCMCredential,
AuthenticationSSPI,
BackendKeyData {
pub process_id: u32,
pub secret_key: u32
},
BindComplete,
CloseComplete,
CommandComplete {
pub tag: String,
},
CopyInResponse {
pub format: u8,
pub column_formats: Vec<u16>,
},
DataRow {
pub row: Vec<Option<Vec<u8>>>
},
EmptyQueryResponse,
ErrorResponse {
pub fields: Vec<(u8, String)>
},
NoData,
NoticeResponse {
pub fields: Vec<(u8, String)>
},
NotificationResponse {
pub pid: u32,
pub channel: String,
pub payload: String,
},
ParameterDescription {
pub types: Vec<Oid>
},
ParameterStatus {
pub parameter: String,
pub value: String,
},
ParseComplete,
PortalSuspended,
ReadyForQuery {
pub _state: u8
},
RowDescription {
pub descriptions: Vec<RowDescriptionEntry>
}
}
pub struct RowDescriptionEntry {
pub name: String,
pub table_oid: Oid,
pub column_id: i16,
pub type_oid: Oid,
pub type_size: i16,
pub type_modifier: i32,
pub format: i16
}
pub enum FrontendMessage<'a> {
Bind {
pub portal: &'a str,
pub statement: &'a str,
pub formats: &'a [i16],
pub values: &'a [Option<Vec<u8>>],
pub result_formats: &'a [i16]
},
CancelRequest {
pub code: u32,
pub process_id: u32,
pub secret_key: u32,
},
Close {
pub variant: u8,
pub name: &'a str
},
CopyData {
pub data: &'a [u8],
},
CopyDone,
CopyFail {
pub message: &'a str
},
Describe {
pub variant: u8,
pub name: &'a str
},
Execute {
pub portal: &'a str,
pub max_rows: i32
},
Parse {
pub name: &'a str,
pub query: &'a str,
pub param_types: &'a [Oid]
},
PasswordMessage {
pub password: &'a str
},
Query {
pub query: &'a str
},
SslRequest {
pub code: u32
},
StartupMessage {
pub version: u32,
pub parameters: &'a [(String, String)]
},
Sync,
Terminate
}
#[doc(hidden)]
trait WriteCStr {
fn write_cstr(&mut self, s: &str) -> IoResult<()>;
}
impl<W: Writer> WriteCStr for W {
fn write_cstr(&mut self, s: &str) -> IoResult<()> {
try!(self.write(s.as_bytes()));
self.write_u8(0)
}
}
#[doc(hidden)]
pub trait WriteMessage {
fn write_message(&mut self, &FrontendMessage) -> IoResult<()> ;
}
impl<W: Writer> WriteMessage for W {
fn write_message(&mut self, message: &FrontendMessage) -> IoResult<()> {
let mut buf = MemWriter::new();
let mut ident = None;
match *message {
Bind { portal, statement, formats, values, result_formats } => {
ident = Some(b'B');
try!(buf.write_cstr(portal));
try!(buf.write_cstr(statement));
try!(buf.write_be_i16(formats.len() as i16));
for format in formats.iter() {
try!(buf.write_be_i16(*format));
}
try!(buf.write_be_i16(values.len() as i16));
for value in values.iter() {
match *value {
None => {
try!(buf.write_be_i32(-1));
}
Some(ref value) => {
try!(buf.write_be_i32(value.len() as i32));
try!(buf.write(value[]));
}
}
}
try!(buf.write_be_i16(result_formats.len() as i16));
for format in result_formats.iter() {
try!(buf.write_be_i16(*format));
}
}
CancelRequest { code, process_id, secret_key } => {
try!(buf.write_be_u32(code));
try!(buf.write_be_u32(process_id));
try!(buf.write_be_u32(secret_key));
}
Close { variant, name } => {
ident = Some(b'C');
try!(buf.write_u8(variant));
try!(buf.write_cstr(name));
}
CopyData { data } => {
ident = Some(b'd');
try!(buf.write(data));
}
CopyDone => {
ident = Some(b'c');
}
CopyFail { message } => {
ident = Some(b'f');
try!(buf.write_cstr(message));
}
Describe { variant, name } => {
ident = Some(b'D');
try!(buf.write_u8(variant));
try!(buf.write_cstr(name));
}
Execute { portal, max_rows } => {
ident = Some(b'E');
try!(buf.write_cstr(portal));
try!(buf.write_be_i32(max_rows));
}
Parse { name, query, param_types } => {
ident = Some(b'P');
try!(buf.write_cstr(name));
try!(buf.write_cstr(query));
try!(buf.write_be_i16(param_types.len() as i16));
for ty in param_types.iter() {
try!(buf.write_be_u32(*ty));
}
}
PasswordMessage { password } => {
ident = Some(b'p');
try!(buf.write_cstr(password));
}
Query { query } => {
ident = Some(b'Q');
try!(buf.write_cstr(query));
}
StartupMessage { version, parameters } => {
try!(buf.write_be_u32(version));
for &(ref k, ref v) in parameters.iter() {
try!(buf.write_cstr(k[]));
try!(buf.write_cstr(v[]));
}
try!(buf.write_u8(0));
}
SslRequest { code } => try!(buf.write_be_u32(code)),
Sync => {
ident = Some(b'S');
}
Terminate => {
ident = Some(b'X');
}
}
match ident {
Some(ident) => try!(self.write_u8(ident)),
None => ()
}
let buf = buf.unwrap();
// add size of length value
try!(self.write_be_i32((buf.len() + mem::size_of::<i32>()) as i32));
try!(self.write(buf[]));
Ok(())
}
}
#[doc(hidden)]
trait ReadCStr {
fn read_cstr(&mut self) -> IoResult<String>;
}
impl<R: Buffer> ReadCStr for R {
fn read_cstr(&mut self) -> IoResult<String> {
let mut buf = try!(self.read_until(0));
buf.pop();
String::from_utf8(buf).map_err(|_| IoError {
kind: OtherIoError,
desc: "Received a non-utf8 string from server",
detail: None
})
}
}
#[doc(hidden)]
pub trait ReadMessage {
fn read_message(&mut self) -> IoResult<BackendMessage>;
}
impl<R: Reader> ReadMessage for R {
fn read_message(&mut self) -> IoResult<BackendMessage> {
let ident = try!(self.read_u8());
// subtract size of length value
let len = try!(self.read_be_u32()) as uint - mem::size_of::<i32>();
let mut buf = MemReader::new(try!(self.read_exact(len)));
let ret = match ident {
b'1' => ParseComplete,
b'2' => BindComplete,
b'3' => CloseComplete,
b'A' => NotificationResponse {
pid: try!(buf.read_be_u32()),
channel: try!(buf.read_cstr()),
payload: try!(buf.read_cstr())
},
b'C' => CommandComplete { tag: try!(buf.read_cstr()) },
b'D' => try!(read_data_row(&mut buf)),
b'E' => ErrorResponse { fields: try!(read_fields(&mut buf)) },
b'G' => {
let format = try!(buf.read_u8());
let mut column_formats = vec![];
for _ in range(0, try!(buf.read_be_u16())) {
column_formats.push(try!(buf.read_be_u16()));
}
CopyInResponse {
format: format,
column_formats: column_formats,
}
}
b'I' => EmptyQueryResponse,
b'K' => BackendKeyData {
process_id: try!(buf.read_be_u32()),
secret_key: try!(buf.read_be_u32())
},
b'n' => NoData,
b'N' => NoticeResponse { fields: try!(read_fields(&mut buf)) },
b'R' => try!(read_auth_message(&mut buf)),
b's' => PortalSuspended,
b'S' => ParameterStatus {
parameter: try!(buf.read_cstr()),
value: try!(buf.read_cstr())
},
b't' => try!(read_parameter_description(&mut buf)),
b'T' => try!(read_row_description(&mut buf)),
b'Z' => ReadyForQuery { _state: try!(buf.read_u8()) },
ident => return Err(IoError {
kind: OtherIoError,
desc: "Unexpected message tag",
detail: Some(format!("got {}", ident)),
})
};
Ok(ret)
}
}
fn read_fields(buf: &mut MemReader) -> IoResult<Vec<(u8, String)>> {
let mut fields = vec![];
loop {
let ty = try!(buf.read_u8());
if ty == 0 {
break;
}
fields.push((ty, try!(buf.read_cstr())));
}
Ok(fields)
}
fn read_data_row(buf: &mut MemReader) -> IoResult<BackendMessage> {
let len = try!(buf.read_be_i16()) as uint;
let mut values = Vec::with_capacity(len);
for _ in range(0, len) {
let val = match try!(buf.read_be_i32()) {
-1 => None,
len => Some(try!(buf.read_exact(len as uint)))
};
values.push(val);
}
Ok(DataRow { row: values })
}
fn read_auth_message(buf: &mut MemReader) -> IoResult<BackendMessage> {
Ok(match try!(buf.read_be_i32()) {
0 => AuthenticationOk,
2 => AuthenticationKerberosV5,
3 => AuthenticationCleartextPassword,
5 => {
let mut salt = [0, ..4];
try!(buf.read_at_least(salt.len(), salt));
AuthenticationMD5Password { salt: salt }
},
6 => AuthenticationSCMCredential,
7 => AuthenticationGSS,
9 => AuthenticationSSPI,
val => return Err(IoError {
kind: OtherIoError,
desc: "Unexpected authentication tag",
detail: Some(format!("got {}", val)),
})
})
}
fn read_parameter_description(buf: &mut MemReader) -> IoResult<BackendMessage> {
let len = try!(buf.read_be_i16()) as uint;
let mut types = Vec::with_capacity(len);
for _ in range(0, len) {
types.push(try!(buf.read_be_u32()));
}
Ok(ParameterDescription { types: types })
}
fn read_row_description(buf: &mut MemReader) -> IoResult<BackendMessage> {
let len = try!(buf.read_be_i16()) as uint;
let mut types = Vec::with_capacity(len);
for _ in range(0, len) {
types.push(RowDescriptionEntry {
name: try!(buf.read_cstr()),
table_oid: try!(buf.read_be_u32()),
column_id: try!(buf.read_be_i16()),
type_oid: try!(buf.read_be_u32()),
type_size: try!(buf.read_be_i16()),
type_modifier: try!(buf.read_be_i32()),
format: try!(buf.read_be_i16())
})
}
Ok(RowDescription { descriptions: types })
}