oracledb-protocol 0.5.1

Sans-I/O Oracle TNS/TTC protocol core for the oracledb crate.
Documentation
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use super::builders::{parse_bool, parse_duration, parse_uint};
use super::*;

/// Private sentinel keys used to stash `https_proxy` host/port until the
/// address lists are assembled (these never reach the public `extra` list).
const PROXY_HOST_KEY: &str = "\0https_proxy_host";
const PROXY_PORT_KEY: &str = "\0https_proxy_port";

/// Common EZConnect-Plus parameters recognised by all drivers (reference
/// `COMMON_PARAM_NAMES`); the value is the canonical name.
fn is_common_param(name: &str) -> bool {
    matches!(
        name,
        "expire_time"
            | "failover"
            | "https_proxy"
            | "https_proxy_port"
            | "load_balance"
            | "pool_boundary"
            | "pool_name"
            | "pool_connection_class"
            | "pool_purity"
            | "retry_count"
            | "retry_delay"
            | "sdu"
            | "source_route"
            | "ssl_server_cert_dn"
            | "ssl_server_dn_match"
            | "transport_connect_timeout"
            | "use_sni"
            | "wallet_location"
    )
}

/// Extra DESCRIPTION params passed through when seen in an easy connect
/// string (reference `EXTRA_DESCRIPTION_PARAM_NAMES`).
fn is_extra_description_param(name: &str) -> bool {
    matches!(name, "enable" | "recv_buf_size" | "send_buf_size")
}

fn is_host_or_service_char(ch: char) -> bool {
    ch.is_alphanumeric() || matches!(ch, '-' | '_' | '.')
}

/// Parser state for an EZConnect string.
struct Ez<'a> {
    chars: &'a [char],
    pos: usize,
    temp_pos: usize,
}

impl<'a> Ez<'a> {
    fn current(&self) -> char {
        self.chars[self.temp_pos]
    }

    fn skip_spaces(&mut self) {
        while self.temp_pos < self.chars.len() && self.chars[self.temp_pos].is_whitespace() {
            self.temp_pos += 1;
        }
    }

    fn parse_keyword(&mut self) {
        while self.temp_pos < self.chars.len() {
            let ch = self.current();
            if !ch.is_alphanumeric() && ch != '_' && ch != '.' {
                break;
            }
            self.temp_pos += 1;
        }
    }

    /// Parses an optional `proto://` prefix. Returns the protocol keyword
    /// (lower-cased) if one was found, advancing `pos` past the `//`.
    /// Mirrors `_parse_easy_connect_protocol`.
    fn parse_protocol(&mut self) -> Option<String> {
        let mut start_sep_pos = self.pos;
        let mut num_sep_chars = 0i32;
        let mut protocol: Option<String> = None;
        self.temp_pos = self.pos;
        while self.temp_pos < self.chars.len() {
            let ch = self.current();
            if ch == ':' {
                protocol = Some(
                    self.chars[self.pos..self.temp_pos]
                        .iter()
                        .collect::<String>()
                        .to_ascii_lowercase(),
                );
                start_sep_pos = self.temp_pos + 1;
            } else if ch == '/' && (self.temp_pos - start_sep_pos) as i32 == num_sep_chars {
                num_sep_chars += 1;
                if num_sep_chars == 2 {
                    self.temp_pos += 1;
                    self.pos = self.temp_pos;
                    break;
                }
            } else if !ch.is_alphabetic() && ch != '-' && ch != '_' {
                break;
            }
            self.temp_pos += 1;
        }
        if protocol.is_some() && num_sep_chars == 2 {
            protocol
        } else {
            None
        }
    }

    /// Parses one host (optionally bracketed IPv6). Mirrors
    /// `_parse_easy_connect_host`.
    fn parse_host(&mut self, address: &mut Address) {
        let mut found_bracket = false;
        let mut found_host = false;
        let mut start_pos = self.temp_pos;
        while self.temp_pos < self.chars.len() {
            let ch = self.current();
            if !found_bracket && !found_host && ch == '[' {
                found_bracket = true;
                start_pos = self.temp_pos + 1;
            } else if found_bracket && ch == ']' {
                address.host = Some(self.chars[start_pos..self.temp_pos].iter().collect());
                self.temp_pos += 1;
                self.pos = self.temp_pos;
                break;
            } else if found_bracket || is_host_or_service_char(ch) {
                self.temp_pos += 1;
                found_host = true;
            } else {
                if found_host {
                    address.host = Some(self.chars[start_pos..self.temp_pos].iter().collect());
                    self.pos = self.temp_pos;
                }
                break;
            }
        }
        // Handle a host that runs to end-of-string.
        if found_host && self.temp_pos == self.chars.len() && address.host.is_none() {
            address.host = Some(self.chars[start_pos..self.temp_pos].iter().collect());
            self.pos = self.temp_pos;
        }
    }

    /// Parses a port number. Mirrors `_parse_easy_connect_port`.
    fn parse_port(&mut self, address: &mut Address) {
        let start = self.temp_pos;
        let mut found = false;
        while self.temp_pos < self.chars.len() && self.current().is_ascii_digit() {
            found = true;
            self.temp_pos += 1;
        }
        if found {
            let digits: String = self.chars[start..self.temp_pos].iter().collect();
            if let Ok(port) = digits.parse::<u16>() {
                address.port = port;
            }
        }
    }
}

/// Builds the host/address-list portion of an EZConnect string into a list
/// of address lists, plus the description that owns them. Mirrors
/// `_parse_easy_connect_hosts`.
#[allow(clippy::too_many_lines)]
pub(super) fn parse(chars: &[char], connect_string: &str) -> Result<Option<Descriptor>> {
    let mut ez = Ez {
        chars,
        pos: 0,
        temp_pos: 0,
    };

    // protocol prefix
    let template_protocol = match ez.parse_protocol() {
        Some(protocol) => Protocol::from_keyword(&protocol)?,
        None => Protocol::Tcp,
    };

    // Hosts: a series of host names separated by commas (same list) or
    // semicolons (new list).
    let mut address_lists: Vec<Vec<Address>> = Vec::new();
    let mut current_list: Vec<Address> = Vec::new();
    ez.temp_pos = ez.pos;
    let mut port_index = 0usize;
    loop {
        let mut address = Address {
            protocol: template_protocol,
            port: template_protocol.default_port(),
            ..Address::default()
        };
        ez.parse_host(&mut address);
        // No host consumed and not at end: stop (no more hosts).
        if ez.temp_pos != ez.pos || ez.pos >= chars.len() {
            // If a host was parsed and we're at end, it was committed by
            // parse_host setting pos == temp_pos == len.
            if ez.pos >= chars.len() && address.host.is_some() {
                current_list.push(address);
            }
            break;
        }
        ez.pos = ez.temp_pos;
        current_list.push(address);
        if ez.temp_pos >= chars.len() {
            break;
        }
        let mut ch = ez.current();
        if ch == ':' {
            ez.temp_pos += 1;
            if let Some(last) = current_list.last_mut() {
                ez.parse_port(last);
                let port = last.port;
                ez.pos = ez.temp_pos;
                if ez.pos >= chars.len() {
                    break;
                }
                // Back-fill the port onto earlier hosts in this list that
                // had no explicit port (reference port_index loop).
                let upper = current_list.len() - 1;
                for addr in current_list.iter_mut().take(upper).skip(port_index) {
                    addr.port = port;
                }
                port_index = current_list.len();
            }
            ch = ez.current();
        }
        if ch == ';' {
            address_lists.push(std::mem::take(&mut current_list));
            port_index = 0;
        } else if ch != ',' {
            break;
        }
        ez.temp_pos += 1;
    }
    address_lists.push(current_list);

    // service name / server type, then instance name, then parameters.
    let mut description = Description::default();
    let mut found_service_section = false;
    parse_service_name(&mut ez, chars, &mut description, &mut found_service_section);
    if found_service_section {
        parse_instance_name(&mut ez, chars, &mut description);
    }

    // If no `/` was ever seen, this is not a valid EZConnect string — it is
    // a tnsnames.ora alias to resolve separately (reference returns None).
    if !found_service_section {
        return Ok(None);
    }

    parse_parameters(&mut ez, chars, connect_string, &mut description)?;

    // Trailing data after a successful parse is an error.
    if ez.pos != chars.len() {
        if ez.pos > 0 {
            return Err(err_cannot_parse(connect_string));
        }
        return Ok(None);
    }

    // Assemble the descriptor: each non-empty host group becomes an address
    // list; a lone single list collapses into the description directly.
    let mut lists: Vec<AddressList> = Vec::new();
    for hosts in address_lists {
        if hosts.is_empty() {
            continue;
        }
        lists.push(AddressList {
            addresses: hosts,
            failover: true,
            ..AddressList::default()
        });
    }
    if lists.is_empty() {
        return Ok(None);
    }
    description.address_lists = lists;

    // Apply any stashed https_proxy host/port onto every address, then drop
    // the sentinel entries from `extra`.
    let proxy_host = description
        .extra
        .iter()
        .find(|(k, _)| k == PROXY_HOST_KEY)
        .map(|(_, v)| v.clone());
    let proxy_port = description
        .extra
        .iter()
        .find(|(k, _)| k == PROXY_PORT_KEY)
        .and_then(|(_, v)| v.parse::<u16>().ok());
    description
        .extra
        .retain(|(k, _)| k != PROXY_HOST_KEY && k != PROXY_PORT_KEY);
    if proxy_host.is_some() || proxy_port.is_some() {
        for list in &mut description.address_lists {
            for addr in &mut list.addresses {
                if let Some(host) = &proxy_host {
                    addr.https_proxy = Some(host.clone());
                }
                if let Some(port) = proxy_port {
                    addr.https_proxy_port = port;
                }
            }
        }
    }

    Ok(Some(Descriptor {
        descriptions: vec![description],
        load_balance: false,
        failover: true,
        source_route: false,
    }))
}

/// Mirrors `_parse_easy_connect_service_name`.
fn parse_service_name(
    ez: &mut Ez,
    chars: &[char],
    description: &mut Description,
    found_slash_out: &mut bool,
) {
    let mut found_service_name = false;
    let mut found_server_type = false;
    let mut found_slash = false;
    let mut found_colon = false;
    let mut service_name_end_pos = 0usize;
    ez.temp_pos = ez.pos;
    while ez.temp_pos < chars.len() {
        let ch = ez.current();
        if !found_slash && ch == '/' {
            found_slash = true;
        } else if found_service_name && !found_colon && ch == ':' {
            found_colon = true;
        } else if found_slash && !found_colon && is_host_or_service_char(ch) {
            found_service_name = true;
            service_name_end_pos = ez.temp_pos + 1;
        } else if found_colon && ch.is_alphabetic() {
            found_server_type = true;
        } else {
            break;
        }
        ez.temp_pos += 1;
    }
    if found_service_name {
        description.connect_data.service_name =
            Some(chars[ez.pos + 1..service_name_end_pos].iter().collect());
    }
    if found_slash {
        ez.pos = ez.temp_pos;
        *found_slash_out = true;
    }
    if found_server_type {
        let value: String = chars[service_name_end_pos + 1..ez.temp_pos]
            .iter()
            .collect();
        if let Ok(server_type) = ServerType::from_keyword(&value) {
            description.connect_data.server_type = Some(server_type);
        }
    }
}

/// Mirrors `_parse_easy_connect_instance_name`.
fn parse_instance_name(ez: &mut Ez, chars: &[char], description: &mut Description) {
    let mut found_instance_name = false;
    let mut found_slash = false;
    let mut instance_name_end_pos = 0usize;
    ez.temp_pos = ez.pos;
    while ez.temp_pos < chars.len() {
        let ch = ez.current();
        if !found_slash && ch == '/' {
            found_slash = true;
        } else if found_slash && is_host_or_service_char(ch) {
            found_instance_name = true;
            instance_name_end_pos = ez.temp_pos + 1;
        } else {
            break;
        }
        ez.temp_pos += 1;
    }
    if found_instance_name {
        description.connect_data.instance_name =
            Some(chars[ez.pos + 1..instance_name_end_pos].iter().collect());
        ez.pos = ez.temp_pos;
    }
}

/// Mirrors `_parse_easy_connect_parameters` + `_parse_easy_connect_parameter`.
fn parse_parameters(
    ez: &mut Ez,
    chars: &[char],
    connect_string: &str,
    description: &mut Description,
) -> Result<()> {
    let mut expected_sep = '?';
    ez.temp_pos = ez.pos;
    while ez.temp_pos < chars.len() {
        let ch = ez.current();
        if ch != expected_sep {
            break;
        }
        expected_sep = '&';
        ez.temp_pos += 1;
        parse_one_parameter(ez, chars, connect_string, description)?;
    }
    Ok(())
}

fn parse_one_parameter(
    ez: &mut Ez,
    chars: &[char],
    connect_string: &str,
    description: &mut Description,
) -> Result<()> {
    // parameter name
    ez.skip_spaces();
    let start = ez.temp_pos;
    ez.parse_keyword();
    if ez.temp_pos == start || ez.temp_pos >= chars.len() {
        return Ok(());
    }
    let raw_name: String = chars[start..ez.temp_pos]
        .iter()
        .collect::<String>()
        .to_ascii_lowercase();
    let (name, keep) = if let Some(stripped) = raw_name.strip_prefix("pyo.") {
        (stripped.to_string(), true)
    } else {
        let keep = is_common_param(&raw_name) || is_extra_description_param(&raw_name);
        (canonical_param_name(&raw_name).to_string(), keep)
    };

    // equals sign
    ez.skip_spaces();
    if ez.temp_pos >= chars.len() {
        return Ok(());
    }
    if ez.current() != '=' {
        return Ok(());
    }
    ez.temp_pos += 1;

    // value
    ez.skip_spaces();
    let mut start_pos = ez.temp_pos;
    let mut end_pos = ez.temp_pos;
    while ez.temp_pos < chars.len() {
        let ch = ez.current();
        if ch == '"' {
            if ez.temp_pos > start_pos {
                return Ok(());
            }
            ez.temp_pos += 1;
            start_pos = ez.temp_pos;
            // parse quoted string
            let mut closed = false;
            while ez.temp_pos < chars.len() {
                let qc = ez.current();
                ez.temp_pos += 1;
                if qc == '"' {
                    closed = true;
                    break;
                }
            }
            if !closed {
                return Err(err_descriptor(
                    connect_string,
                    ez.temp_pos,
                    "missing ending quote (\")",
                ));
            }
            end_pos = ez.temp_pos - 1;
            break;
        } else if ch == '&' {
            end_pos = ez.temp_pos;
            break;
        }
        ez.temp_pos += 1;
        end_pos = ez.temp_pos;
    }
    if end_pos > start_pos && keep {
        let value: String = chars[start_pos..end_pos].iter().collect();
        apply_easy_param(connect_string, description, &name, &value)?;
    }
    ez.skip_spaces();
    ez.pos = ez.temp_pos;
    Ok(())
}

/// Applies a recognised EZConnect-Plus parameter onto the description.
fn apply_easy_param(
    connect_string: &str,
    description: &mut Description,
    name: &str,
    value: &str,
) -> Result<()> {
    match name {
        "expire_time" => {
            description.expire_time = parse_uint(connect_string, "EXPIRE_TIME", value)?
        }
        "retry_count" => {
            description.retry_count = parse_uint(connect_string, "RETRY_COUNT", value)?
        }
        "retry_delay" => {
            description.retry_delay = parse_uint(connect_string, "RETRY_DELAY", value)?
        }
        "sdu" => {
            description.sdu = parse_uint(connect_string, "SDU", value)?.clamp(MIN_SDU, MAX_SDU);
        }
        "tcp_connect_timeout" => {
            description.tcp_connect_timeout =
                parse_duration(connect_string, "TRANSPORT_CONNECT_TIMEOUT", value)?;
        }
        "failover" => description.failover = parse_bool(value),
        "load_balance" => description.load_balance = parse_bool(value),
        "source_route" => description.source_route = parse_bool(value),
        "use_sni" => description.use_sni = parse_bool(value),
        "ssl_server_dn_match" => description.security.ssl_server_dn_match = parse_bool(value),
        "ssl_server_cert_dn" => {
            description.security.ssl_server_cert_dn = Some(value.to_string());
        }
        "wallet_location" => description.security.wallet_location = Some(value.to_string()),
        // https_proxy / https_proxy_port are applied to every address after
        // the address lists are assembled; they are stashed in `extra` under
        // a private sentinel key and consumed in `parse`.
        "https_proxy" => description
            .extra
            .push((PROXY_HOST_KEY.to_string(), value.to_string())),
        "https_proxy_port" => description
            .extra
            .push((PROXY_PORT_KEY.to_string(), value.to_string())),
        "pool_boundary" => description.connect_data.pool_boundary = Some(value.to_string()),
        "pool_name" => description.connect_data.pool_name = Some(value.to_string()),
        "cclass" => {
            if !value.is_empty() {
                description.connect_data.cclass = Some(value.to_string());
            }
        }
        "purity" => {
            description.connect_data.purity = Some(Purity::from_keyword(value)?);
        }
        "enable" | "recv_buf_size" | "send_buf_size" => {
            description
                .extra
                .push((name.to_ascii_uppercase(), value.to_string()));
        }
        // Extended (`pyo.`) params not affecting the descriptor topology are
        // accepted but not modelled here (e.g. stmtcachesize, edition).
        _ => {}
    }
    Ok(())
}