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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use super::{connection::*, AuthMethod};
use crate::{tds::Context, Client, EncryptionLevel};
use std::collections::HashMap;

#[derive(Clone)]
/// A builder for creating a new [`Client`].
///
/// [`Client`]: struct.Client.html
pub struct ClientBuilder {
    host: Option<String>,
    port: Option<u16>,
    database: Option<String>,
    #[cfg(windows)]
    instance_name: Option<String>,
    encryption: EncryptionLevel,
    trust_cert: bool,
    auth: AuthMethod,
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self {
            host: None,
            port: None,
            database: None,
            #[cfg(windows)]
            instance_name: None,
            #[cfg(feature = "tls")]
            encryption: EncryptionLevel::Required,
            #[cfg(not(feature = "tls"))]
            encryption: EncryptionLevel::NotSupported,
            trust_cert: false,
            auth: AuthMethod::None,
        }
    }
}

impl ClientBuilder {
    /// A host or ip address to connect to.
    ///
    /// - Defaults to `localhost`.
    pub fn host(&mut self, host: impl ToString) {
        self.host = Some(host.to_string());
    }

    /// The server port.
    ///
    /// - Defaults to `1433`.
    pub fn port(&mut self, port: u16) {
        self.port = Some(port);
    }

    /// The database to connect to.
    ///
    /// - Defaults to `master`.
    pub fn database(&mut self, database: impl ToString) {
        self.database = Some(database.to_string())
    }

    /// The instance name as defined in the SQL Browser. Only available on
    /// Windows platforms.
    ///
    /// If specified, the port is replaced with the value returned from the
    /// browser.
    #[cfg(any(windows, doc))]
    pub fn instance_name(&mut self, name: impl ToString) {
        self.instance_name = Some(name.to_string());
    }

    /// Set the preferred encryption level.
    pub fn encryption(&mut self, encryption: EncryptionLevel) {
        self.encryption = encryption;
    }

    /// If set, the server certificate will not be validated and it is accepted
    /// as-is.
    ///
    /// On production setting, the certificate should be added to the local key
    /// storage, using this setting is potentially dangerous.
    pub fn trust_cert(&mut self) {
        self.trust_cert = true;
    }

    /// Sets the authentication method.
    pub fn authentication(&mut self, auth: AuthMethod) {
        self.auth = auth;
    }

    fn get_host(&self) -> &str {
        self.host
            .as_ref()
            .map(|s| s.as_str())
            .unwrap_or("localhost")
    }

    fn get_port(&self) -> u16 {
        self.port.unwrap_or(1433)
    }

    #[cfg(windows)]
    fn create_context(&self) -> Context {
        let mut context = Context::new();
        context.set_spn(self.get_host(), self.get_port());
        context
    }

    #[cfg(not(windows))]
    fn create_context(&self) -> Context {
        Context::new()
    }

    /// Creates a new client and connects to the server.
    pub async fn build(self) -> crate::Result<Client> {
        let context = self.create_context();
        let addr = format!("{}:{}", self.get_host(), self.get_port());

        let opts = ConnectOpts {
            encryption: self.encryption,
            trust_cert: self.trust_cert,
            auth: self.auth,
            database: self.database,
            #[cfg(windows)]
            instance_name: self.instance_name,
            #[cfg(not(windows))]
            instance_name: None,
        };

        let connection = Connection::connect_tcp(addr, context, opts).await?;

        Ok(Client { connection })
    }

    /// Creates a new `ClientBuilder` from an [ADO.NET connection
    /// string](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings).
    ///
    /// # Supported parameters
    ///
    /// |Parameters|Description|
    /// |--------|--------|
    /// |`server`|The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name. The correct form of this parameter is either `tcp:host,port` or `tcp:host\\instance`|
    /// |`IntegratedSecurity`|Toggle between Windows authentication and SQL authentication.|
    /// |`uid`, `username`, `user`|The SQL Server login account.|
    /// |`password`, `pwd`|The password for the SQL Server account logging on.|
    /// |`database`|The name of the database.|
    /// |`TrustServerCertificate`|Specifies whether the driver trusts the server certificate when connecting using TLS.|
    /// |`encrypt`|Specifies whether the driver uses TLS to encrypt communication.|
    pub fn from_ado_string(s: &str) -> crate::Result<Self> {
        let ado = AdoNetString::parse(s)?;
        let mut builder = Self::default();

        let server = ado.server()?;

        if let Some(host) = server.host {
            builder.host(host);
        }

        if let Some(port) = server.port {
            builder.port(port);
        }

        if let Some(_instance) = server.instance {
            #[cfg(windows)]
            builder.instance_name(_instance);
        }

        builder.authentication(ado.authentication()?);

        if let Some(database) = ado.database() {
            builder.database(database);
        }

        if ado.trust_cert()? {
            builder.trust_cert();
        }

        builder.encryption(ado.encrypt()?);

        Ok(builder)
    }
}

pub(crate) struct AdoNetString {
    dict: HashMap<String, String>,
}

impl AdoNetString {
    pub fn parse(s: &str) -> crate::Result<Self> {
        let dict: crate::Result<HashMap<String, String>> = s
            .split(";")
            .filter(|kv| kv != &"")
            .map(|kv| {
                let mut splitted = kv.split("=");

                let key = splitted
                    .next()
                    .ok_or_else(|| {
                        crate::Error::Conversion(
                            "Missing a valid key in connection string parameters.".into(),
                        )
                    })?
                    .trim()
                    .to_lowercase();

                let value = splitted
                    .next()
                    .ok_or_else(|| {
                        crate::Error::Conversion(
                            "Missing a valid key in connection string parameters.".into(),
                        )
                    })?
                    .trim()
                    .to_string();

                Ok((key, value))
            })
            .collect();

        Ok(Self { dict: dict? })
    }

    pub fn server(&self) -> crate::Result<ServerDefinition> {
        fn parse_server(parts: Vec<&str>) -> crate::Result<ServerDefinition> {
            if parts.is_empty() || parts.len() >= 3 {
                return Err(crate::Error::Conversion("Server value faulty.".into()));
            }

            let definition = if parts[0].contains('\\') {
                let port = if parts.len() == 1 {
                    1434
                } else {
                    parts[1].parse::<u16>()?
                };

                let parts: Vec<&str> = parts[0].split('\\').collect();

                ServerDefinition {
                    host: Some(parts[0].into()),
                    port: Some(port),
                    instance: Some(parts[1].into()),
                }
            } else {
                // Connect using a TCP target
                let (host, port) = (parts[0], parts[1].parse::<u16>()?);

                ServerDefinition {
                    host: Some(host.into()),
                    port: Some(port),
                    instance: None,
                }
            };

            Ok(definition)
        }

        match self.dict.get("server") {
            Some(value) if value.starts_with("tcp:") => {
                parse_server(value[4..].split(',').collect())
            }
            Some(value) => parse_server(value.split(',').collect()),
            None => Ok(ServerDefinition {
                host: None,
                port: None,
                instance: None,
            }),
        }
    }

    pub fn authentication(&self) -> crate::Result<AuthMethod> {
        let user = self
            .dict
            .get("uid")
            .or_else(|| self.dict.get("username"))
            .or_else(|| self.dict.get("user"))
            .map(|s| s.as_str());

        let pw = self
            .dict
            .get("password")
            .or_else(|| self.dict.get("pwd"))
            .map(|s| s.as_str());

        match self.dict.get("integratedsecurity") {
            #[cfg(windows)]
            Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => match (user, pw)
            {
                (None, None) => Ok(AuthMethod::WindowsIntegrated),
                _ => Ok(AuthMethod::windows(user.unwrap_or(""), pw.unwrap_or(""))),
            },
            _ => Ok(AuthMethod::sql_server(user.unwrap_or(""), pw.unwrap_or(""))),
        }
    }

    pub fn database(&self) -> Option<String> {
        self.dict.get("database").map(|db| db.to_string())
    }

    pub fn trust_cert(&self) -> crate::Result<bool> {
        self.dict
            .get("trustservercertificate")
            .map(|val| Self::parse_bool(val))
            .unwrap_or(Ok(false))
    }

    #[cfg(feature = "tls")]
    pub fn encrypt(&self) -> crate::Result<EncryptionLevel> {
        self.dict
            .get("encrypt")
            .map(|val| {
                if Self::parse_bool(val)? {
                    Ok(EncryptionLevel::Required)
                } else {
                    Ok(EncryptionLevel::Off)
                }
            })
            .unwrap_or(Ok(EncryptionLevel::Off))
    }

    #[cfg(not(feature = "tls"))]
    pub fn encrypt(&self) -> crate::Result<EncryptionLevel> {
        Ok(EncryptionLevel::NotSupported)
    }

    fn parse_bool<T: AsRef<str>>(v: T) -> crate::Result<bool> {
        match v.as_ref().trim().to_lowercase().as_str() {
            "true" | "yes" => Ok(true),
            "false" | "no" => Ok(false),
            _ => Err(crate::Error::Conversion(
                "Connection string: Not a valid boolean".into(),
            )),
        }
    }
}

pub(crate) struct ServerDefinition {
    host: Option<String>,
    port: Option<u16>,
    instance: Option<String>,
}

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

    #[test]
    fn server_parsing_no_browser() -> crate::Result<()> {
        let test_str = "server=tcp:my-server.com,4200";
        let ado = AdoNetString::parse(test_str)?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_no_tcp() -> crate::Result<()> {
        let test_str = "server=my-server.com,4200";
        let ado = AdoNetString::parse(test_str)?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(4200), server.port);
        assert_eq!(None, server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_with_browser() -> crate::Result<()> {
        let test_str = "server=tcp:my-server.com\\TIBERIUS";
        let ado = AdoNetString::parse(test_str)?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(1434), server.port);
        assert_eq!(Some("TIBERIUS".to_string()), server.instance);

        Ok(())
    }

    #[test]
    fn server_parsing_with_browser_and_port() -> crate::Result<()> {
        let test_str = "server=tcp:my-server.com\\TIBERIUS,666";
        let ado = AdoNetString::parse(test_str)?;
        let server = ado.server()?;

        assert_eq!(Some("my-server.com".to_string()), server.host);
        assert_eq!(Some(666), server.port);
        assert_eq!(Some("TIBERIUS".to_string()), server.instance);

        Ok(())
    }

    #[test]
    fn database_parsing() -> crate::Result<()> {
        let test_str = "database=Foo";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(Some("Foo".to_string()), ado.database());

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_true() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=true";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(true, ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_false() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=false";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(false, ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_yes() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=yes";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(true, ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_no() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=no";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(false, ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_missing() -> crate::Result<()> {
        let test_str = "Something=foo;";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(false, ado.trust_cert()?);

        Ok(())
    }

    #[test]
    fn trust_cert_parsing_faulty() -> crate::Result<()> {
        let test_str = "TrustServerCertificate=musti;";
        let ado = AdoNetString::parse(test_str)?;

        assert!(ado.trust_cert().is_err());

        Ok(())
    }

    #[test]
    fn parsing_sql_server_authentication() -> crate::Result<()> {
        let test_str = "uid=Musti; pwd=Naukio;";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(
            AuthMethod::sql_server("Musti", "Naukio"),
            ado.authentication()?
        );

        Ok(())
    }

    #[test]
    #[cfg(windows)]
    fn parsing_sspi_authentication() -> crate::Result<()> {
        let test_str = "IntegratedSecurity=SSPI";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(AuthMethod::WindowsIntegrated, ado.authentication()?);

        Ok(())
    }

    #[test]
    #[cfg(windows)]
    fn parsing_windows_authentication() -> crate::Result<()> {
        let test_str = "uid=Musti;pwd=Naukio; IntegratedSecurity=SSPI;";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(
            AuthMethod::windows("Musti", "Naukio"),
            ado.authentication()?
        );

        Ok(())
    }

    #[test]
    fn parsing_database() -> crate::Result<()> {
        let test_str = "database=Cats";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(Some("Cats".to_string()), ado.database());

        Ok(())
    }

    #[test]
    #[cfg(feature = "tls")]
    fn encryption_parsing_on() -> crate::Result<()> {
        let test_str = "encrypt=true";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(EncryptionLevel::Required, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(feature = "tls")]
    fn encryption_parsing_off() -> crate::Result<()> {
        let test_str = "encrypt=false";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(EncryptionLevel::Off, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(feature = "tls")]
    fn encryption_parsing_missing() -> crate::Result<()> {
        let test_str = "";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(EncryptionLevel::Off, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(not(feature = "tls"))]
    fn encryption_parsing_on() -> crate::Result<()> {
        let test_str = "encrypt=true";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(EncryptionLevel::NotSupported, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(not(feature = "tls"))]
    fn encryption_parsing_off() -> crate::Result<()> {
        let test_str = "encrypt=false";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(EncryptionLevel::NotSupported, ado.encrypt()?);

        Ok(())
    }

    #[test]
    #[cfg(not(feature = "tls"))]
    fn encryption_parsing_missing() -> crate::Result<()> {
        let test_str = "";
        let ado = AdoNetString::parse(test_str)?;

        assert_eq!(EncryptionLevel::NotSupported, ado.encrypt()?);

        Ok(())
    }
}