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
//! Connection parameters
use secstr::SecStr;
use std::env;
use std::fmt;
use std::fs;
use std::mem;
use std::path::Path;
use url::Url;
use {HdbError, HdbResult};

/// An immutable struct with all information necessary to open a new connection
/// to a HANA database.
///
/// An instance of `ConnectParams` can be created from a url (represented as `String` or as `Url`)
/// either using the trait `IntoConnectParams` and its implementations, or with the shortcut
/// `ConnectParams::from_file`.
///
/// The URL is supposed to have the form
///
/// ```text
/// <scheme>://<username>:<password>@<host>:<port>[<options>]
/// ```
/// where
/// > `<scheme>` = `hdbsql` | `hdbsqls`  
/// > `<username>` = the name of the DB user to log on  
/// > `<password>` = the password of the DB user  
/// > `<host>` = the host where HANA can be found  
/// > `<port>` = the port at which HANA can be found on `<host>`  
/// > `<options>` = `?<key> = <value> [{&<key> = <value>}]`
///
/// Special option keys are:
/// > `client_locale`: `<value>` is used to specify the client's locale  
/// > `client_locale_from_env`: if `<value>` is 1, the client's locale is read
///   from the environment variabe LANG  
/// > `tls_trust_anchor_dir`: the `<value>` points to a folder with pem files that contain
///   the server's certificates; all pem files in that folder are evaluated
///
/// The client locale is used in language-dependent handling within the SAP HANA
/// database calculation engine.
///
/// # Example
///
/// ```
/// use hdbconnect::IntoConnectParams;
/// let conn_params = "hdbsql://my_user:my_passwd@the_host:2222"
///     .into_connect_params()
///     .unwrap();
/// ```
#[derive(Clone)]
pub struct ConnectParams {
    #[cfg(feature = "alpha_tls")]
    use_tls: bool,
    host: String,
    addr: String,
    dbuser: String,
    password: SecStr,
    clientlocale: Option<String>,
    #[cfg(feature = "alpha_tls")]
    trust_anchor_dir: Option<String>,
    options: Vec<(String, String)>,
}
impl ConnectParams {
    /// Returns a new builder for ConnectParams.
    pub fn builder() -> ConnectParamsBuilder {
        ConnectParamsBuilder::new()
    }

    /// Reads a url from the given file and converts it into `ConnectParams`.
    pub fn from_file<P: AsRef<Path>>(path: P) -> HdbResult<ConnectParams> {
        fs::read_to_string(path)?.into_connect_params()
    }

    /// The trust_anchor_dir.
    #[cfg(feature = "alpha_tls")]
    pub fn trust_anchor_dir(&self) -> Option<&str> {
        self.trust_anchor_dir.as_ref().map(|s| s.as_ref())
    }

    /// The host.
    pub fn host(&self) -> &str {
        &self.host
    }

    /// The socket address.
    pub fn addr(&self) -> &str {
        &self.addr
    }

    /// Whether TLS or a plain TCP connection is to be used.
    pub fn use_tls(&self) -> bool {
        #[cfg(feature = "alpha_tls")]
        return self.use_tls;

        #[cfg(not(feature = "alpha_tls"))]
        return false;
    }

    /// The database user.
    pub fn dbuser(&self) -> &String {
        &self.dbuser
    }

    /// The password.
    pub fn password(&self) -> &SecStr {
        &self.password
    }

    /// The client locale.
    pub fn clientlocale(&self) -> &Option<String> {
        &self.clientlocale
    }

    /// Options to be passed to HANA.
    pub fn options(&self) -> &[(String, String)] {
        &self.options
    }
}

impl fmt::Debug for ConnectParams {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "ConnectParams {{ addr: {}, dbuser: {}, clientlocale: {:?} }}",
            self.addr, self.dbuser, self.clientlocale,
        )
    }
}

/// A trait implemented by types that can be converted into a `ConnectParams`.
pub trait IntoConnectParams {
    /// Converts the value of `self` into a `ConnectParams`.
    fn into_connect_params(self) -> HdbResult<ConnectParams>;
}

impl IntoConnectParams for ConnectParams {
    fn into_connect_params(self) -> HdbResult<ConnectParams> {
        Ok(self)
    }
}

impl<'a> IntoConnectParams for &'a str {
    fn into_connect_params(self) -> HdbResult<ConnectParams> {
        match Url::parse(self) {
            Ok(url) => url.into_connect_params(),
            Err(_) => Err(HdbError::Usage("url parse error".to_owned())),
        }
    }
}

impl IntoConnectParams for String {
    fn into_connect_params(self) -> HdbResult<ConnectParams> {
        self.as_str().into_connect_params()
    }
}

impl IntoConnectParams for Url {
    fn into_connect_params(self) -> HdbResult<ConnectParams> {
        let host: String = match self.host_str() {
            Some("") | None => return Err(HdbError::Usage("host is missing".to_owned())),
            Some(host) => host.to_string(),
        };

        let port: u16 = match self.port() {
            Some(p) => p,
            None => return Err(HdbError::Usage("port is missing".to_owned())),
        };

        let dbuser: String = match self.username() {
            "" => return Err(HdbError::Usage("dbuser is missing".to_owned())),
            s => s.to_string(),
        };

        let password = SecStr::from(match self.password() {
            None => return Err(HdbError::Usage("password is missing".to_owned())),
            Some(s) => s.to_string(),
        });

        #[cfg(feature = "alpha_tls")]
        let use_tls = match self.scheme() {
            "hdbsql" => false,
            "hdbsqls" => true,
            s => {
                return Err(HdbError::Usage(format!(
                    "Unknown protocol '{}'; only 'hdbsql' and 'hdbsqls' are supported",
                    s
                )))
            }
        };

        #[cfg(not(feature = "alpha_tls"))]
        {
            if self.scheme() != "hdbsql" {
                return Err(HdbError::Usage(format!(
                    "Unknown protocol '{}'; only 'hdbsql' is supported; \
                     for 'hdbsqls' the feature 'tls' must be used when compiling hdbconnect",
                    self.scheme()
                )));
            }
        }

        #[cfg(feature = "alpha_tls")]
        let mut trust_anchor_dir = None;
        let mut clientlocale = None;
        let mut options = Vec::<(String, String)>::new();
        for (name, value) in self.query_pairs() {
            match name.as_ref() {
                "client_locale" => clientlocale = Some(value.to_string()),
                "client_locale_from_env" => {
                    clientlocale = match env::var("LANG") {
                        Ok(l) => Some(l),
                        Err(_) => None,
                    };
                }
                #[cfg(feature = "alpha_tls")]
                "tls_trust_anchor_dir" => trust_anchor_dir = Some(value.to_string()),
                _ => options.push((name.to_string(), value.to_string())),
            }
        }

        Ok(ConnectParams {
            #[cfg(feature = "alpha_tls")]
            use_tls,
            addr: format!("{}:{}", host, port),
            host,
            dbuser,
            password,
            clientlocale,
            #[cfg(feature = "alpha_tls")]
            trust_anchor_dir,
            options,
        })
    }
}

/// A builder for `ConnectParams`.
///
/// # Example
///
/// ```
/// use hdbconnect::ConnectParams;
/// let connect_params = ConnectParams::builder()
///     .hostname("abcd123")
///     .port(2222)
///     .dbuser("MEIER")
///     .password("schlau")
///     .build()
///     .unwrap();
/// ```
#[derive(Clone, Debug, Default)]
pub struct ConnectParamsBuilder {
    hostname: Option<String>,
    port: Option<u16>,
    dbuser: Option<String>,
    password: Option<String>,
    clientlocale: Option<String>,
    #[cfg(feature = "alpha_tls")]
    trust_anchor_dir: Option<String>,
    options: Vec<(String, String)>,
}

impl ConnectParamsBuilder {
    /// Creates a new builder.
    pub fn new() -> ConnectParamsBuilder {
        ConnectParamsBuilder {
            hostname: None,
            port: None,
            dbuser: None,
            password: None,
            clientlocale: None,
            #[cfg(feature = "alpha_tls")]
            trust_anchor_dir: None,
            options: vec![],
        }
    }

    /// Sets the hostname.
    pub fn hostname<H: AsRef<str>>(&mut self, hostname: H) -> &mut ConnectParamsBuilder {
        self.hostname = Some(hostname.as_ref().to_owned());
        self
    }

    /// Sets the port.
    pub fn port(&mut self, port: u16) -> &mut ConnectParamsBuilder {
        self.port = Some(port);
        self
    }

    /// Sets the database user.
    pub fn dbuser<D: AsRef<str>>(&mut self, dbuser: D) -> &mut ConnectParamsBuilder {
        self.dbuser = Some(dbuser.as_ref().to_owned());
        self
    }

    /// Sets the password.
    pub fn password<P: AsRef<str>>(&mut self, pw: P) -> &mut ConnectParamsBuilder {
        self.password = Some(pw.as_ref().to_owned());
        self
    }

    /// Sets the client locale.
    pub fn clientlocale<P: AsRef<str>>(&mut self, cl: P) -> &mut ConnectParamsBuilder {
        self.clientlocale = Some(cl.as_ref().to_owned());
        self
    }

    /// Sets the client locale from the value of the environment variable LANG
    pub fn clientlocale_from_env_lang(&mut self) -> &mut ConnectParamsBuilder {
        self.clientlocale = match env::var("LANG") {
            Ok(l) => Some(l),
            Err(_) => None,
        };

        self
    }

    /// Enforces the usage of TLS for the connection to the database and requires a
    /// filesystem folder with pem files to validate the server.
    #[cfg(feature = "alpha_tls")]
    pub fn use_tls(&mut self, trust_anchor_dir: String) -> &mut ConnectParamsBuilder {
        self.trust_anchor_dir = Some(trust_anchor_dir);
        self
    }

    /// Adds a runtime parameter.
    pub fn option<'a>(&'a mut self, name: &str, value: &str) -> &'a mut ConnectParamsBuilder {
        self.options.push((name.to_string(), value.to_string()));
        self
    }

    /// Constructs a `ConnectParams` from the builder.
    pub fn build(&mut self) -> HdbResult<ConnectParams> {
        Ok(ConnectParams {
            host: match self.hostname {
                Some(ref s) => s.clone(),
                None => return Err(HdbError::Usage("hostname is missing".to_owned())),
            },
            addr: format!(
                "{}:{}",
                match self.hostname {
                    Some(ref s) => s,
                    None => return Err(HdbError::Usage("hostname is missing".to_owned())),
                },
                match self.port {
                    Some(ref p) => *p,
                    None => return Err(HdbError::Usage("port is missing".to_owned())),
                }
            ),
            dbuser: match self.dbuser {
                Some(_) => self.dbuser.take().unwrap(),
                None => return Err(HdbError::Usage("dbuser is missing".to_owned())),
            },
            password: match self.password {
                Some(_) => SecStr::from(self.password.take().unwrap()),
                None => return Err(HdbError::Usage("password is missing".to_owned())),
            },
            clientlocale: match self.clientlocale {
                Some(_) => Some(self.clientlocale.take().unwrap()),
                None => None,
            },
            options: mem::replace(&mut self.options, vec![]),

            #[cfg(feature = "alpha_tls")]
            use_tls: self.trust_anchor_dir.is_some(),

            #[cfg(feature = "alpha_tls")]
            trust_anchor_dir: match self.trust_anchor_dir {
                Some(ref s) => Some(s.clone()),
                None => None,
            },
        })
    }
}

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

    #[test]
    fn test_params_from_url() {
        let params = "hdbsql://meier:schLau@abcd123:2222"
            .into_connect_params()
            .unwrap();

        assert_eq!("meier", params.dbuser());
        assert_eq!(b"schLau", params.password().unsecure());
        assert_eq!("abcd123:2222", params.addr());
    }

    #[test]
    fn test_errors() {
        assert!(
            "hdbsql://schLau@abcd123:2222"
                .into_connect_params()
                .is_err()
        );
        assert!("hdbsql://meier@abcd123:2222".into_connect_params().is_err());
        assert!("hdbsql://meier:schLau@:2222".into_connect_params().is_err());
        assert!(
            "hdbsql://meier:schLau@abcd123"
                .into_connect_params()
                .is_err()
        );
    }
}