firebirust 0.6.3

Firebird client library
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
// MIT License
//
// Copyright (c) 2021 Hajime Nakagami<nakagami@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#![allow(dead_code)]

use std::io::prelude::*;
use std::str;

use chrono;
use chrono::TimeZone;
use chrono_tz;
use crypto::digest::Digest;
use crypto::sha1::Sha1;
use hex;
use num_bigint::{BigInt, BigUint, Sign};

use super::tz_map;

pub fn int32_to_bytes(i: i32) -> [u8; 4] {
    // little endian i32 to Vec<u8>
    i32::to_ne_bytes(i.to_le())
}

pub fn uint32_to_bytes(i: u32) -> [u8; 4] {
    // little endian u32 to Vec<u8>
    u32::to_ne_bytes(i.to_le())
}

pub fn bint128_to_bytes(i: i128) -> [u8; 16] {
    // big endian i128 to Vec<u8>
    i128::to_ne_bytes(i.to_be())
}

pub fn bint64_to_bytes(i: i64) -> [u8; 8] {
    // big endian i64 to Vec<u8>
    i64::to_ne_bytes(i.to_be())
}

pub fn bint32_to_bytes(i: i32) -> [u8; 4] {
    // big endian i32 to Vec<u8>
    i32::to_ne_bytes(i.to_be())
}

pub fn ubint32_to_bytes(i: u32) -> [u8; 4] {
    // big endian u32 to Vec<u8>
    u32::to_ne_bytes(i.to_be())
}

pub fn int16_to_bytes(i: u16) -> [u8; 2] {
    // little endian u16 to Vec<u8>
    u16::to_ne_bytes(i.to_le())
}

pub fn f32_to_bytes(f: f32) -> [u8; 4] {
    f.to_le_bytes()
}

pub fn f64_to_bytes(f: f64) -> [u8; 8] {
    f.to_le_bytes()
}

pub fn bytes_to_str(b: &[u8]) -> String {
    str::from_utf8(b).unwrap().to_string()
}

pub fn bytes_to_rtrim_str(b: &[u8]) -> String {
    str::from_utf8(b).unwrap().trim_end().to_string()
}

pub fn bytes_to_int32(b: &[u8]) -> i32 {
    let tmp: [u8; 4] = [b[0], b[1], b[2], b[3]];
    i32::from_ne_bytes(tmp)
}

pub fn bytes_to_bint32(b: &[u8]) -> i32 {
    let tmp: [u8; 4] = [b[3], b[2], b[1], b[0]];
    i32::from_ne_bytes(tmp)
}

pub fn bytes_to_uint32(b: &[u8]) -> u32 {
    // little endian u32
    ((b[0] as u32) << 0) + ((b[1] as u32) << 8) + ((b[2] as u32) << 16) + ((b[3] as u32) << 24)
}

pub fn bytes_to_buint32(b: &[u8]) -> u32 {
    // big endian u32
    ((b[0] as u32) << 24) + ((b[1] as u32) << 16) + ((b[2] as u32) << 8) + ((b[3] as u32) << 0)
}

pub fn bytes_to_int16(b: &[u8]) -> i16 {
    let tmp: [u8; 2] = [b[0], b[1]];
    i16::from_ne_bytes(tmp)
}

pub fn bytes_to_bint16(b: &[u8]) -> i16 {
    let tmp: [u8; 2] = [b[1], b[0]];
    i16::from_ne_bytes(tmp)
}

pub fn bytes_to_uint16(b: &[u8]) -> u16 {
    // little endian u16
    ((b[0] as u16) << 0) + ((b[1] as u16) << 8)
}

pub fn bytes_to_buint16(b: &[u8]) -> u16 {
    // big endian u16
    ((b[0] as u16) << 8) + ((b[1] as u16) << 0)
}

pub fn bytes_to_int64(b: &[u8]) -> i64 {
    let tmp: [u8; 8] = [b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]];
    i64::from_ne_bytes(tmp)
}

pub fn bytes_to_bint64(b: &[u8]) -> i64 {
    let tmp: [u8; 8] = [b[7], b[6], b[5], b[4], b[3], b[2], b[1], b[0]];
    i64::from_ne_bytes(tmp)
}

pub fn bytes_to_uint128(b: &[u8]) -> u128 {
    let tmp: [u8; 16] = [
        b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13],
        b[14], b[15],
    ];
    u128::from_ne_bytes(tmp)
}

pub fn bytes_to_int128(b: &[u8]) -> i128 {
    let tmp: [u8; 16] = [
        b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13],
        b[14], b[15],
    ];
    i128::from_ne_bytes(tmp)
}

pub fn bytes_to_bint128(b: &[u8]) -> i128 {
    let tmp: [u8; 16] = [
        b[15], b[14], b[13], b[12], b[11], b[10], b[9], b[8], b[7], b[6], b[5], b[4], b[3], b[2],
        b[1], b[0],
    ];
    i128::from_ne_bytes(tmp)
}

pub fn bytes_to_uint64(b: &[u8]) -> u64 {
    // little endian u64
    ((b[0] as u64) << 0)
        + ((b[1] as u64) << 8)
        + ((b[2] as u64) << 16)
        + ((b[3] as u64) << 24)
        + ((b[4] as u64) << 32)
        + ((b[5] as u64) << 40)
        + ((b[6] as u64) << 48)
        + ((b[7] as u64) << 56)
}

pub fn bytes_to_buint64(b: &[u8]) -> u64 {
    // big endian u64
    ((b[0] as u64) << 56)
        + ((b[1] as u64) << 48)
        + ((b[2] as u64) << 40)
        + ((b[3] as u64) << 32)
        + ((b[4] as u64) << 24)
        + ((b[5] as u64) << 16)
        + ((b[6] as u64) << 8)
        + ((b[7] as u64) << 0)
}

pub fn bytes_to_f32(b: &[u8]) -> f32 {
    let tmp: [u8; 4] = [b[3], b[2], b[1], b[0]];
    f32::from_ne_bytes(tmp)
}

pub fn bytes_to_f64(b: &[u8]) -> f64 {
    let tmp: [u8; 8] = [b[7], b[6], b[5], b[4], b[3], b[2], b[1], b[0]];
    f64::from_ne_bytes(tmp)
}

pub fn bytes_to_naive_date(b: &[u8]) -> chrono::NaiveDate {
    let mut nday = bytes_to_buint32(b) + 678882;
    let century = (4 * nday - 1) / 146097;
    nday = 4 * nday - 1 - 146097 * century;
    let mut day = nday / 4;

    nday = (4 * day + 3) / 1461;
    day = 4 * day + 3 - 1461 * nday;
    day = (day + 4) / 4;

    let mut month = (5 * day - 3) / 153;
    day = 5 * day - 3 - 153 * month;
    day = (day + 5) / 5;
    let mut year = (100 * century + nday) as i32;
    if month < 10 {
        month += 3;
    } else {
        month -= 9;
        year += 1;
    }

    chrono::NaiveDate::from_ymd_opt(year, month, day).unwrap()
}

pub fn bytes_to_naive_time(b: &[u8]) -> chrono::NaiveTime {
    let n = bytes_to_buint32(b);
    let mut s = n / 10000;
    let mut m = s / 60;
    let h = m / 60;
    m = m % 60;
    s = s % 60;
    chrono::NaiveTime::from_hms_micro_opt(h, m, s, (n % 10000) * 100000).unwrap()
}

pub fn bytes_to_time_tz(b: &[u8]) -> (chrono::NaiveTime, chrono_tz::Tz) {
    // https://stackoverflow.com/questions/56050292/is-there-a-way-to-parse-a-timezone-abbreviation-into-a-timezone-offset-in-rust
    let time = bytes_to_naive_time(&b[..4]);
    let timezone: chrono_tz::Tz;
    let offset: chrono_tz::Tz;
    if &b[4..6] == b"\x00\x00" {
        timezone = "UTC".parse().unwrap();
        offset = timezone;
    } else {
        timezone = tz_map::timezone_name_by_id(bytes_to_buint16(&b[4..6]))
            .parse()
            .unwrap();
        offset = tz_map::timezone_name_by_id(bytes_to_buint16(&b[6..8]))
            .parse()
            .unwrap();
    }
    let date = chrono::Utc::now().date_naive();
    let dt = chrono::NaiveDateTime::new(date, time);
    let tz_aware = timezone
        .from_local_datetime(&dt)
        .unwrap()
        .with_timezone(&offset);
    (tz_aware.time(), offset)
}

pub fn bytes_to_naive_date_time(b: &[u8]) -> chrono::NaiveDateTime {
    let date = bytes_to_naive_date(&b[..4]);
    let time = bytes_to_naive_time(&b[4..]);

    chrono::NaiveDateTime::new(date, time)
}

pub fn bytes_to_date_time_tz(b: &[u8]) -> chrono::DateTime<chrono_tz::Tz> {
    let dt = bytes_to_naive_date_time(&b[..8]);
    if &b[8..10] == b"\x00\x00" {
        let timezone: chrono_tz::Tz = "UTC".parse().unwrap();
        return timezone.from_local_datetime(&dt).unwrap();
    }
    let timezone: chrono_tz::Tz = tz_map::timezone_name_by_id(bytes_to_buint16(&b[8..10]))
        .parse()
        .unwrap();
    let offset: chrono_tz::Tz = tz_map::timezone_name_by_id(bytes_to_buint16(&b[10..12]))
        .parse()
        .unwrap();

    timezone
        .from_local_datetime(&dt)
        .unwrap()
        .with_timezone(&offset)
}

pub fn big_int_from_hex_string(s: &[u8]) -> BigInt {
    BigInt::parse_bytes(s, 16).unwrap()
}

pub fn big_int_from_string(s: &[u8]) -> BigInt {
    BigInt::parse_bytes(s, 10).unwrap()
}

pub fn big_uint_from_string(s: &[u8]) -> BigUint {
    BigUint::parse_bytes(s, 10).unwrap()
}

pub fn big_int_to_bytes(i: &BigInt) -> Vec<u8> {
    assert_eq!(i.sign(), Sign::Plus);
    let (_, v) = i.to_bytes_be();
    v
}

pub fn bytes_to_big_int(b: &[u8]) -> BigInt {
    BigInt::from_bytes_be(Sign::Plus, b)
}

pub fn big_int_to_sha1_hex(i: &BigInt) -> String {
    let mut hasher = Sha1::new();
    hasher.input(&big_int_to_bytes(i));
    hasher.result_str()
}

pub fn big_int_to_sha1(i: &BigInt) -> Vec<u8> {
    hex::decode(big_int_to_sha1_hex(i)).unwrap()
}

pub fn xdr_bytes(b: &[u8]) -> Vec<u8> {
    let mut write_buf: Vec<u8> = Vec::new();
    let n: usize = b.len();
    write_buf.write(&(n as u32).to_be_bytes()).unwrap();
    write_buf.write(b).unwrap();
    let mut padding: usize = 0;
    if n % 4 != 0 {
        padding = 4 - n % 4;
    }
    for _ in 0..padding {
        write_buf.push(0);
    }
    write_buf
}

pub fn bytes_to_blr(b: &[u8]) -> (Vec<u8>, Vec<u8>) {
    let n = b.len();
    let mut v: Vec<u8> = Vec::new();
    v.write(b).unwrap();
    let mut padding: usize = 0;
    if n % 4 != 0 {
        padding = 4 - n % 4;
    }
    for _ in 0..padding {
        v.push(0u8);
    }
    let blr: Vec<u8> = vec![14, (n & 255) as u8, (n >> 8) as u8];
    (blr, v)
}

pub fn convert_date(year: i32, month: u32, day: u32) -> [u8; 4] {
    // Convert date to BLR format data
    let i = month + 9;
    let jy = year as u32 + (i / 12) - 1;
    let jm = i % 12;
    let c = jy / 100;
    let j = (146097 * c) / 4 + (1461 * (jy - 100 * c)) / 4 + (153 * jm + 2) / 5 + day - 678882;
    bint32_to_bytes(j as i32)
}

pub fn convert_time(hour: u32, minute: u32, second: u32, nanosecond: u32) -> [u8; 4] {
    // Convert time to BLR format time
    let n = (hour * 3600 + minute * 60 + second) * 10000 + nanosecond * 10;
    bint32_to_bytes(n as i32)
}

pub fn guess_wire_crypt(buf: &[u8]) -> (Vec<u8>, Vec<u8>) {
    let mut available_plugins = vec![];
    let mut plugin_nonce = vec![];

    let mut i: usize = 0;
    while i < buf.len() {
        let k = buf[i];
        i += 1;
        let ln = buf[i] as usize;
        i += 1;
        let v = &buf[i..i + ln];
        i += ln;
        if k == 1 {
            let s = str::from_utf8(v).unwrap();
            available_plugins = s.split(' ').collect();
        } else if k == 3 {
            plugin_nonce.push(v);
        }
    }
    if available_plugins.contains(&"ChaCha64") {
        for nonce in &plugin_nonce {
            if &nonce[0..9] == b"ChaCha64\x00" {
                return (b"ChaCha64".to_vec(), nonce[9..].to_vec());
            }
        }
    } else if available_plugins.contains(&"ChaCha") {
        for nonce in &plugin_nonce {
            if &nonce[0..7] == b"ChaCha\x00" {
                return (b"ChaCha".to_vec(), nonce[7..(7 + 12)].to_vec());
            }
        }
    } else if available_plugins.contains(&"Arc4") {
        return (b"Arc4".to_vec(), vec![]);
    }
    return (vec![], vec![]);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bint32_roundtrip() {
        for v in [0i32, 1, -1, 127, -128, 255, 256, 32767, -32768, i32::MAX, i32::MIN] {
            let bytes = bint32_to_bytes(v);
            assert_eq!(bytes_to_bint32(&bytes), v, "bint32 roundtrip failed for {}", v);
        }
    }

    #[test]
    fn test_bint64_roundtrip() {
        for v in [0i64, 1, -1, i64::MAX, i64::MIN] {
            let bytes = bint64_to_bytes(v);
            assert_eq!(bytes_to_bint64(&bytes), v, "bint64 roundtrip failed for {}", v);
        }
    }

    #[test]
    fn test_bint128_roundtrip() {
        for v in [0i128, 1, -1, i128::MAX, i128::MIN] {
            let bytes = bint128_to_bytes(v);
            assert_eq!(bytes_to_bint128(&bytes), v, "bint128 roundtrip failed for {}", v);
        }
    }

    /// SQL_TYPE_SHORT is sent as 4-byte big-endian i32 on the wire.
    /// bytes_to_bint32 should be used (then truncated to i16),
    /// NOT bytes_to_bint16 which only reads the first 2 bytes.
    #[test]
    fn test_smallint_wire_format() {
        // Firebird sends SMALLINT as 4-byte big-endian i32 (io_length=4).
        for v in [0i16, 1, -1, 127, -128, 255, 256, 32767, -32768] {
            let wire_bytes = bint32_to_bytes(v as i32);

            // Correct: read as bint32, truncate to i16
            let correct = bytes_to_bint32(&wire_bytes) as i16;
            assert_eq!(correct, v, "bint32-to-i16 failed for {}", v);

            // Bug: bytes_to_bint16 reads only first 2 bytes (high bytes of big-endian i32)
            let buggy = bytes_to_bint16(&wire_bytes);
            // For values where high 2 bytes differ from the i16 value, this is wrong
            if v != 0 && v != -1 {
                assert_ne!(
                    buggy, v,
                    "bytes_to_bint16 unexpectedly correct for {} - \
                     it reads high bytes of big-endian i32",
                    v
                );
            }
        }
    }
}