enqueue-email 0.1.0

Send a bookmark via email, enqueuing it with MSMTP queue
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
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
//! This crate provides a collection of functions to establish a HTTPS
//! connection to a remote URL, retrieve the HTML content and extract
//! its title.
#![warn(rust_2018_idioms)]
#![warn(missing_docs, missing_debug_implementations)]
#![warn(anonymous_parameters, bare_trait_objects, unreachable_pub)]
#![deny(unused)]
#![deny(unused_variables)]
#![forbid(unsafe_code)]
// #![deny(missing_docs)]

use async_std::io;
use async_std::net::TcpStream;
use async_tls::TlsConnector;
use futures::io::AsyncWriteExt;
use httparse::Header;
use httparse::Response;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_until;
use nom::error::ErrorKind;
use nom::sequence::tuple;
use nom::IResult;
use rustls::ClientConfig;
use std::boxed::Box;
use std::convert::TryFrom;
use std::error::Error;
use std::io::Cursor;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use std::path::Path;
use std::path::PathBuf;
use std::str::from_utf8;
use std::sync::Arc;
use std::time::Duration;
use structopt::StructOpt;
use url::Host;
use url::ParseError;
use url::Url;
use x11_clipboard::Clipboard;

#[macro_use]
extern crate log;

// Lint And Attributes Documentation References
//
// https://doc.rust-lang.org/reference/attributes.html
// https://doc.rust-lang.org/rustc/lints/listing/index.html
// https://doc.rust-lang.org/rustc/lints/groups.html

#[allow(trivial_casts)]

const TITLE_TAG_OPEN: &str = "<title>";
const TITLE_TAG_CLOSE: &str = "</title>";

/// Options contains the CLI available options offered to the binary tool.
///
/// This struct maps all the options that are available to the CLI user.
/// of the binary `enqueue-email`.
#[derive(Debug, StructOpt)]
pub struct Options {
    /// The URL to bookmark and enqueue. This excludes scheme, host, port
    /// and domain. This option has the priority over the Clipboard.
    #[structopt(short = "u", long = "url")]
    pub url: Option<String>,

    /// Use the URL currently on the top of the Clipboard.
    /// This option disables all the other defined options.
    #[structopt(short = "c", long = "clipboard")]
    pub clipboard: bool,

    /// The host to connect to.
    #[structopt(short = "h", long = "host")]
    pub host: Option<String>,

    /// The port to connect to.
    #[structopt(short = "p", long = "port", default_value = "443")]
    pub port: u16,

    /// The scheme protocol of the URI.
    #[structopt(short = "s", long = "scheme", default_value = "https")]
    pub scheme: String,

    /// The path component in the URI. This follows the definitions of
    /// RFC2396 and RFC3986
    /// (https://en.wikipedia.org/wiki/Uniform_Resource_Identifier).
    #[structopt(short = "t", long = "path", default_value = "/")]
    pub path: String,

    /// An optional query component preceded by a question mark (?),
    /// containing a query string of non-hierarchical data.
    #[structopt(short = "q", long = "query")]
    pub query: Option<String>,

    /// An optional fragment component preceded by a hash (#).
    #[structopt(short = "f", long = "fragment")]
    pub fragment: Option<String>,

    /// The domain to connect to. This may be different from the host!
    #[structopt(short = "d", long = "domain")]
    pub domain: Option<String>,

    /// A file with a certificate authority chain, allows to connect
    /// to certificate authories not included in the default set.
    #[structopt(short = "", long = "cafile", parse(from_os_str))]
    pub cafile: Option<PathBuf>,

    /// Run msmt-queue and flush all mail currently in queue.
    /// This wraps the command 'msmtp-queue -r'.
    #[structopt(short = "r", long = "run")]
    pub run: bool,
}

/// Creates a TLSConnector with a specific CA file if provided.
pub async fn connector(cafile: &Option<PathBuf>) -> Result<TlsConnector, Box<dyn Error>> {
    if let Some(cafile) = cafile {
        connector_for_ca_file(cafile).await.map_err(|ioerr| {
            let e: Box<dyn Error> = Box::new(ioerr);
            e
        })
    } else {
        Ok(TlsConnector::default())
    }
}

async fn connector_for_ca_file(cafile: &Path) -> Result<TlsConnector, io::Error> {
    let mut config = ClientConfig::new();
    let file = async_std::fs::read(cafile).await?;
    let mut pem = Cursor::new(file);
    config
        .root_store
        .add_pem_file(&mut pem)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid cert"))?;
    Ok(TlsConnector::from(Arc::new(config)))
}

/// Extract the page title tag content from a raw but well formed HTML content.
///
/// The implementation of this functions is a Nom parser.
///
/// Type Definition [nom::IResult](https://docs.rs/nom/5.1.2/nom/type.IResult.html).
///
/// Holds the result of parsing functions
/// type IResult<I, O, E = (I, ErrorKind)> = Result<(I, O), Err<E>>;
/// It depends on I, the input type, O, the output type, and E, the error type
/// (by default u32).
///
/// The Ok side is a pair containing the remainder of the input (the part of the
/// data that was not parsed) and the produced value. The Err side contains an
/// instance of nom::Err.
/// let (_, (_, _, title)) = match tuple::<_, _, VerboseError<_>, _>(...
///
/// Function
/// [nom::bytes::complete::take_until](https://docs.rs/nom/5.1.2/nom/bytes/complete/fn.take_until.html)
///
/// Returns the longest input slice till it matches the pattern.
///
/// It doesn't consume the pattern. It will return
/// Err(Err::Error((_rest, ErrorKind::TakeUntil)))
/// if the pattern wasn't met.
///
/// Function std::str::from_utf8
/// Converts a vector of bytes to a String.
///
/// A string (String) is made of bytes (u8), and a vector of bytes (Vec<u8>) is
/// made of bytes, so this function converts between the two. Not all byte
/// slices are valid Strings, however: String requires that it is valid UTF-8.
/// from_utf8() checks to ensure that the bytes are valid UTF-8, and then does
/// the conversion.
///
/// Also uses
/// [from_utft8](https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8).
pub fn page_title_from_html(content: &[u8]) -> Result<Option<String>, Box<dyn Error>> {
    let content: &str = match from_utf8(&content) {
        Ok(v) => v,
        Err(e) => {
            let e: Box<dyn Error> = From::from(format!("Invalid UTF-8 sequence: {}", e));
            return Err(e);
        }
    };

    let has_tag: Result<(&str, &str), nom::Err<(&str, ErrorKind)>> = until_open_title_tag(content);
    if let Ok((content, _before_tag)) = has_tag {
        let parsed: IResult<&str, (_, _, &str), (&str, ErrorKind)> = tuple((
            take_until(TITLE_TAG_OPEN),
            tag(TITLE_TAG_OPEN),
            take_until(TITLE_TAG_CLOSE),
        ))(content);
        let (_, (_, _, title)) = match parsed {
            Ok(r) => r,
            Err(_) => {
                let e: Box<dyn Error> = From::from("parsing error");
                return Err(e);
            }
        };

        return Ok(Some(String::from(title.trim())));
    }
    Ok(None)
}

fn until_open_title_tag(s: &str) -> IResult<&str, &str> {
    take_until(TITLE_TAG_OPEN)(s)
}

/// Read the "redirect location" from a HTTP response.
///
/// The Ok variant of the Results, if Some, includes the Location of the
/// redirect, read from the response headers, otherwise is Ok<None>.
pub fn has_redirect(
    response: &Response<'_, '_>,
    origin: &Url,
) -> Result<Option<Url>, Box<dyn Error>> {
    match &response.code {
        None => {
            let e: Box<dyn Error> =
                From::from("HTTP response parsing error: could not find StatusCode");
            Err(e)
        }
        Some(c @ 300..=308) => {
            for Header { name, value } in response.headers.iter() {
                if name == &"Location" {
                    let dest: &str = from_utf8(&value).unwrap();
                    let dest: Url = match Url::parse(dest) {
                        Ok(url) => url,
                        Err(ParseError::RelativeUrlWithoutBase) => origin
                            .join(dest)
                            .expect("unparseable relative redirect destination"),
                        Err(_) => {
                            // Due to the handling above, this path seems unreachable.
                            unreachable!();
                        }
                    };
                    debug!("HTTP redirect: {} -> {}", c, dest);
                    return Ok(Some(dest));
                }
            }
            let e: Box<dyn Error> = From::from(format!("HTTP redirect without location: {}", c));
            Err(e)
        }
        Some(c) => {
            debug!("HTTP StatusCode: {}", c);
            Ok(None)
        }
    }
}

/// Jump is the result of a connection.
///
/// A redirect can direct to the Next URL, othewise
/// Landing has the page content as Vec<u8>.
#[derive(Debug)]
pub enum Jump {
    /// The redirect location as Url.
    Next(Url),
    /// The content of the destination URL, as vector of chars.
    Landing(Vec<u8>),
}

/// Uses the given TLS connector and the URL parts to retrieve the
/// HTML page content or the next location in case of a redirect.
///
/// HTTP URL conforms to the syntax of a generic URI.
/// The URI generic syntax consists of a hierarchical sequence of five
/// components:
///
/// URI = scheme:[//authority]path[?query][#fragment]
/// authority = [userinfo@]host[:port]
/// HTTP URL = URI
///
/// The TCP stream, HTTP stream, and TLS stream each expect a different subset
/// of a URL. TCP takes localhost:8080, HTTP takes http://localhost:8080/foo/bar,
/// TLS takes localhost.
pub async fn page_content(connector: &TlsConnector, parts: &Parts) -> Result<Jump, Box<dyn Error>> {
    let socket_addr: &SocketAddr = &parts.addr;
    let domain: &str = &parts.domain;

    // Open a normal TCP connection, just as you are used to.
    let tcp_stream: TcpStream = match TcpStream::connect(&socket_addr).await {
        Ok(t) => t,
        Err(e) => {
            let e: Box<dyn Error> = From::from(format!("TCPStream error: {}", e));
            return Err(e);
        }
    };

    // Use the connector to start the handshake process. This
    // consumes the TCP stream to ensure you are not reusing it.
    // Awaiting the handshake gives you an encrypted stream back
    // which you can use like any other.
    let mut tls_stream = match connector.connect(&domain, tcp_stream).await {
        Ok(ts) => ts,
        Err(e) => {
            let e: Box<dyn Error> = From::from(format!("TLSStream error: {}", e));
            return Err(e);
        }
    };

    // We write our crafted HTTP request to it.
    tls_stream
        .write_all(parts.http_request().as_bytes())
        .await?;

    // And write the content in the content variable.
    let mut response_content: Vec<u8> = Vec::with_capacity(1024);
    io::copy(&mut tls_stream, &mut response_content).await?;

    let mut headers: [Header<'_>; 32] = [httparse::EMPTY_HEADER; 32];
    let mut response: Response<'_, '_> = Response::new(&mut headers);
    response.parse(&response_content)?;

    match has_redirect(&response, &parts.url)? {
        Some(url) => Ok(Jump::Next(url)),
        None => Ok(Jump::Landing(response_content)),
    }
}

fn clipboard_content() -> Result<String, Box<dyn Error>> {
    let clipboard = Clipboard::new().unwrap();
    let clipboard_content = clipboard.load(
        clipboard.setter.atoms.clipboard,
        clipboard.setter.atoms.utf8_string,
        clipboard.setter.atoms.property,
        Duration::from_secs(3),
    )?;
    let clipboard_content = String::from_utf8(clipboard_content).expect("UTF-8 content");
    debug!("clipboard content: {}", &clipboard_content);
    Ok(clipboard_content)
}

/// The hierarchical sequence of components of a URI.
///
/// Each URI begins with a scheme name that refers to a specification
/// for assigning identifiers within that scheme. As such, the URI
/// syntax is a federated and extensible naming system wherein each
/// scheme's specification may further restrict the syntax and
/// semantics of identifiers using that scheme. The URI generic syntax
/// is a superset of the syntax of all URI schemes. It was first
/// defined in RFC 2396, published in August 1998, and finalized in
/// RFC 3986, published in January 2005.
///
/// [URI syntax](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Generic_syntax)
#[derive(Clone, Debug)]
pub struct Parts {
    /// A Uniform Resource Locator (URL), colloquially termed a web
    /// address, is a reference to a web resource that specifies
    /// its location on a computer network and a mechanism for
    /// retrieving it. A URL is a specific type of Uniform Resource
    /// Identifier (URI).
    pub url: Url,
    /// The registered host name of an URL.
    pub host: Host<String>,
    /// The port number of the URL.
    pub port: u16,
    /// An internet socket address, either IPv4 or IPv6.
    pub addr: SocketAddr,
    /// The domain name (not an IP address) of the given host.
    pub domain: String,
    /// the path for this URL, as a percent-encoded ASCII string. For
    /// cannot-be-a-base URLs, this is an arbitrary string that
    /// doesn’t start with '/'. For other URLs, this starts with a '/'
    /// slash and continues with slash-separated path segments.
    pub path: String,
    /// The URL's query string, if any, as a percent-encoded ASCII string.
    pub query: String,
    /// A fragment is the part of the URL after the # symbol. The
    /// fragment is optional and, if present, contains a fragment
    /// identifier that identifies a secondary resource, such as a
    /// section heading of a document.
    ///
    /// In HTML, the fragment identifier is usually the id attribute
    /// of a an element that is scrolled to on load. Browsers
    /// typically will not send the fragment portion of a URL to the
    /// server.
    pub fragment: String,
}

impl Parts {
    /// Create a bare bones HTTP GET request.
    ///
    /// The reference is the
    /// [RFC7230](https://tools.ietf.org/rfcmarkup?doc=7230)
    pub fn http_request(&self) -> String {
        let query = if self.query != "" && !self.query.starts_with('?') {
            format!("?{}", self.query)
        } else {
            self.query.clone()
        };
        let fragment = if self.fragment != "" && !self.fragment.starts_with('#') {
            format!("#{}", self.fragment)
        } else {
            self.fragment.clone()
        };
        let http_request: String = format!(
            "GET {}{}{} HTTP/1.0\r\nHost: {}\r\n\r\n",
            self.path, query, fragment, self.domain,
        );
        debug!("HTTP request: {}", &http_request);
        http_request
    }
}

impl TryFrom<&Options> for Parts {
    // type Error = &'static str;
    type Error = Box<dyn Error>;

    fn try_from(options: &Options) -> Result<Self, Self::Error> {
        // The options --clipboard, --url and --host are mutually exclusive.
        let mutex_opts: [bool; 3] = [
            options.clipboard,
            options.url.is_some(),
            options.host.is_some(),
        ];
        match mutex_opts {
            [true, false, false] | [false, true, false] | [false, false, true] => {}
            [false, false, false]
            | [true, true, false]
            | [true, false, true]
            | [false, true, true]
            | [true, true, true] => {
                let e: Box<dyn Error> =
                    From::from("use one and only one of --clipboard, --url or --host");
                return Err(e);
            }
        }

        let url: Url = if options.clipboard {
            Url::parse(&clipboard_content().expect("clipboard is not readable"))
                .expect("Clipboard is not a URL")
        } else if let Some(u) = &options.url {
            Url::parse(&u).expect("Unparseable URL")
        } else if let Some(h) = &options.host {
            Url::parse(&format!("{}://{}", options.scheme, h)).expect("Unparseable scheme and host")
        } else {
            unreachable!("use only one of --clipboard, --url or --host")
        };

        let host: Host<String> = if let Some(h) = &options.host {
            Host::parse(&h).expect("Unparseable Host")
        } else {
            url.host().expect("URL without host").to_owned()
        };
        debug!("host name: {}", &host);

        let port: u16 = match options.port {
            0 => match url.scheme() {
                "https" => 443,
                "http" => {
                    let e: Box<dyn Error> =
                        From::from("HTTP standard ports is not yet suported".to_string());
                    return Err(e);
                }
                s => {
                    let e: Box<dyn Error> = From::from(format!(
                        "Only HTTP(S) standard ports are suported. {} given",
                        s
                    ));
                    return Err(e);
                }
            },
            p => p,
        };
        debug!("port number: {}", &port);

        // Check if the provided host exists.
        // *Note*: this conversion will attemp the network resolution of the
        // given host!
        //
        // Using:
        // - https://docs.rs/async-std/1.6.2/async_std/net/enum.SocketAddr.html
        //   The implementation of to_socket_addrs: Converts this
        //   object to an iterator of resolved SocketAddrs.
        //   The returned iterator may not actually yield any values
        //   depending on the outcome of any resolution performed.
        //   Note that this function may block the current thread
        //   while resolution is performed.
        //   https://doc.rust-lang.org/nightly/src/std/net/addr.rs.html#921-923
        let addr: SocketAddr = (host.to_string().as_str(), options.port)
            .to_socket_addrs()?
            .next()
            .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?;
        debug!("socket address: {}", &addr);

        // If no domain was passed, the host is also the domain to connect to.
        let domain: String = if let Some(d) = &options.domain {
            d.to_owned()
        } else {
            host.to_string()
        };
        debug!("domain {}", &domain);

        let path: String = match &options.host {
            None => (&url.path()).to_string(),
            _ => options.path.to_string(),
        };

        let query: String = match &options.query {
            Some(q) => q.to_owned(),
            None => url.query().unwrap_or("").to_string(),
        };

        let fragment: String = match &options.fragment {
            Some(f) => f.to_owned(),
            None => url.fragment().unwrap_or("").to_string(),
        };

        Ok(Parts {
            url,
            host,
            port,
            addr,
            query,
            fragment,
            domain,
            path,
        })
    }
}

impl TryFrom<&str> for Parts {
    type Error = Box<dyn Error>;

    fn try_from(url: &str) -> Result<Self, Self::Error> {
        let url: Url = Url::parse(&url).expect("Unparseable URL");
        Self::try_from(&url)
    }
}

impl TryFrom<&Url> for Parts {
    type Error = Box<dyn Error>;

    fn try_from(url: &Url) -> Result<Self, Self::Error> {
        let host: Host<String> = url.host().expect("URL without host").to_owned();
        let port: u16 = match url.scheme() {
            "https" => 443,
            "http" => 80,
            s => {
                let e: Box<dyn Error> = From::from(format!(
                    "Only HTTP(S) standard ports are suported. {} given",
                    s
                ));
                return Err(e);
            }
        };
        let addr: SocketAddr = (host.to_string().as_str(), port)
            .to_socket_addrs()?
            .next()
            .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?;
        // On the assumption that host and domain are the same in this case.
        let domain: String = host.to_string();
        let path: String = (&url.path()).to_string();
        let query: String = url.query().unwrap_or("").to_string();
        let fragment: String = url.fragment().unwrap_or("").to_string();

        Ok(Parts {
            url: url.clone(),
            host,
            port,
            addr,
            query,
            fragment,
            domain,
            path,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_std::task;
    use std::fs;
    use std::time::Instant;

    #[allow(dead_code)]
    fn init() {
        let _ = env_logger::builder().is_test(true).try_init();
    }

    #[test]
    fn test_connector_passes_without_cafile() -> Result<(), String> {
        match task::block_on(async { connector(&None).await }) {
            Ok(_) => Ok(()),
            Err(_) => Err(String::from("connector should use the system CA files")),
        }
    }

    #[test]
    fn test_connector_fails_with_nonexisting_cafile() -> Result<(), String> {
        let cafile: &Option<PathBuf> = &Some(PathBuf::from("/nope"));
        match task::block_on(async { connector(cafile).await }) {
            Ok(_) => Err(String::from(
                "connector should fail when the CA file does not exist",
            )),
            Err(_) => Ok(()),
        }
    }

    #[test]
    #[should_panic(expected = "No such file or directory")]
    fn test_connector_fails_with_nonexisting_cafile_with_failure_message() {
        let cafile: &Option<PathBuf> = &Some(PathBuf::from("/nope"));
        task::block_on(async { connector(cafile).await }).unwrap();
    }

    #[test]
    fn test_connector_for_ca_file_passes() -> Result<(), String> {
        // Considering the Cargo.toml path as "crate root"
        // https://doc.rust-lang.org/cargo/reference/config.html#environment-variables
        let cafile: &Path =
            &Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/files/doc_rust-lang_org.crt");
        match task::block_on(async { connector_for_ca_file(cafile).await }) {
            Ok(_) => Ok(()),
            Err(_) => Err(String::from("could not load the test PEM certificate")),
        }
    }

    #[test]
    fn test_page_title_from_html_passes_with_valid_html() -> Result<(), String> {
        let page: &Path =
            &Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/files/home_with_title.html");
        match page_title_from_html(
            &fs::read(page).map_err(|_| String::from("could not open HTML test page"))?,
        ) {
            Ok(Some(title)) if title == String::from("Rust Programming Language") => Ok(()),
            Ok(Some(title)) => Err(format!("unexpected title: \"{}\"", title)),
            Ok(None) => Err(From::from("could not find a title in the page")),

            _ => Err(String::from(
                "could not extract the title from the HTML page content",
            )),
        }
    }

    #[test]
    fn test_page_title_from_html_passes_with_valid_html_without_title() -> Result<(), String> {
        let page: &Path =
            &Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/files/home_without_title.html");
        match page_title_from_html(
            &fs::read(page).map_err(|_| String::from("could not open HTML test page"))?,
        ) {
            Ok(Some(title)) => Err(format!("unexpected title: \"{}\"", title)),
            Ok(None) => Ok(()),
            Err(e) => Err(format!("unexpected error: {}", e)),
        }
    }

    #[test]
    fn test_page_title_from_html_fails_with_non_utf8_characters() -> Result<(), String> {
        match page_title_from_html(&vec![0, 159, 146, 150]) {
            Ok(_) => Err(format!(
                "unexpected success extracting the title from non UTF8 characters"
            )),
            Err(e)
                if (*e).to_string()
                    == "Invalid UTF-8 sequence: invalid utf-8 sequence of 1 bytes from index 1" =>
            {
                Ok(())
            }
            Err(e) => Err(format!("unexpected error: {}", e)),
        }
    }

    #[test]
    #[ignore]
    fn test_page_title_from_html_with_attributes() -> Result<(), String> {
        unimplemented!()
    }

    #[test]
    fn test_has_redirect() -> Result<(), String> {
        let origin: Url = Url::parse("https://doc.rust-lang.org/std")
            .map_err(|e| format!("could not parse origin URL: {}", e))?;
        let destination: Url = Url::parse("https://doc.rust-lang.org/stable/std/")
            .map_err(|e| format!("could not parse destination URL: {}", e))?;
        let mut headers: Vec<Header<'_>> = Vec::new();
        let redirect_header = Header {
            name: "Location",
            value: destination.as_str().as_bytes(),
        };
        headers.push(redirect_header);
        let mut response = Response::new(&mut headers);
        response.code = Some(301);
        match has_redirect(&response, &origin) {
            Ok(Some(u)) if u == destination => Ok(()),
            Ok(Some(u)) => Err(format!("unexpected redirect location: \"{}\"", u)),
            Ok(None) => Err(format!("could not find HTTP redirect location")),
            Err(e) => Err(format!("could not parse HTTP Response: {}", e)),
        }
    }

    #[test]
    fn test_has_no_redirect() -> Result<(), String> {
        let origin: Url = Url::parse("https://doc.rust-lang.org/std")
            .map_err(|e| format!("could not parse origin URL: {}", e))?;
        let mut headers: Vec<Header<'_>> = Vec::new();
        let mut response = Response::new(&mut headers);
        response.code = Some(200);
        match has_redirect(&response, &origin) {
            Ok(None) => Ok(()),
            Ok(Some(u)) => Err(format!("unexpected redirect location: \"{}\"", u)),
            Err(e) => Err(format!("could not parse HTTP Response: {}", e)),
        }
    }

    #[test]
    fn test_has_redirect_fails_without_status_code() -> Result<(), String> {
        let origin: Url = Url::parse("https://doc.rust-lang.org/std")
            .map_err(|e| format!("could not parse origin URL: {}", e))?;
        let mut headers: Vec<Header<'_>> = Vec::new();
        let mut response = Response::new(&mut headers);
        response.code = None;
        match has_redirect(&response, &origin) {
            Ok(_) => Err(From::from("unexpected success in redirect detection")),
            Err(e)
                if (*e).to_string() == "HTTP response parsing error: could not find StatusCode" =>
            {
                Ok(())
            }
            Err(e) => Err(format!("unexpected error message: {}", e)),
        }
    }

    #[test]
    #[ignore]
    fn test_has_redirect_fails_with_unparseable_redirect_location() -> Result<(), String> {
        let origin: Url = Url::parse("https://doc.rust-lang.org/std")
            .map_err(|e| format!("could not parse origin URL: {}", e))?;
        let mut headers: Vec<Header<'_>> = Vec::new();
        let redirect_header = Header {
            name: "Location",
            value: "unreachable".as_bytes(),
        };
        headers.push(redirect_header);
        let mut response = Response::new(&mut headers);
        response.code = Some(301);
        match has_redirect(&response, &origin) {
            Ok(l) => Err(format!("unexpected success in redirect detection: {:?}", l)),
            Err(e)
                if (*e).to_string() == "HTTP response parsing error: could not find StatusCode" =>
            {
                Ok(())
            }
            Err(e) => Err(format!("unexpected error message: {}", e)),
        }
    }

    #[test]
    fn test_has_redirect_fails_without_redirect_location() -> Result<(), String> {
        let origin: Url = Url::parse("https://doc.rust-lang.org/std")
            .map_err(|e| format!("could not parse origin URL: {}", e))?;
        let mut headers: Vec<Header<'_>> = Vec::new();
        let mut response = Response::new(&mut headers);
        response.code = Some(301);
        match has_redirect(&response, &origin) {
            Ok(l) => Err(format!("unexpected success in redirect detection: {:?}", l)),
            Err(e) if (*e).to_string() == "HTTP redirect without location: 301" => Ok(()),
            Err(e) => Err(format!("unexpected error message: {}", e)),
        }
    }

    #[test]
    fn test_has_redirect_passes_with_a_relative_redirect() -> Result<(), String> {
        let origin: Url = Url::parse("https://doc.rust-lang.org/stable")
            .map_err(|e| format!("could not parse origin URL: {}", e))?;
        let mut headers: Vec<Header<'_>> = Vec::new();
        let redirect_header = Header {
            name: "Location",
            value: "/stable/std/".as_bytes(),
        };
        headers.push(redirect_header);
        let mut response = Response::new(&mut headers);
        response.code = Some(301);
        match has_redirect(&response, &origin) {
            Ok(None) => Err(From::from("missing redirect detection")),
            Ok(Some(l)) if l.to_string() == "https://doc.rust-lang.org/stable/std/" => Ok(()),
            Ok(Some(l)) => Err(format!("unexpected redirect location: {}", l.to_string())),
            Err(e) => Err(format!("could not detect redirection: {}", e)),
        }
    }

    #[cfg(feature = "live-tests")]
    mod livetests {
        use super::*;
        use std::net::IpAddr;
        use std::net::Ipv4Addr;

        #[test]
        fn test_page_content_fails_with_http_only_url() -> Result<(), String> {
            let connector: TlsConnector = TlsConnector::default();
            let url: Url = Url::parse("http://example.org")
                .map_err(|e| format!("could not parse URL: {}", e))?;
            let parts: Parts = Parts::try_from(&url)
                .map_err(|e| format!("could not parse parts from URL: {}", e))?;
            match task::block_on(async { page_content(&connector, &parts).await }) {
                Ok(_) => Err(format!("unexpected OK connection: HTTP should fail")),
                Err(e) if (*e).to_string() == "TLSStream error: received corrupt message" => Ok(()),
                Err(e) => Err(format!("unexpected error message: {}", e)),
            }
        }

        #[test]
        fn test_page_content_fails_with_broken_address() -> Result<(), String> {
            let connector: TlsConnector = TlsConnector::default();
            let parts: Parts = Parts {
                url: Url::parse("http://example.org").unwrap(),
                host: Host::parse("example.org").unwrap(),
                port: 443,
                addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080),
                domain: String::new(),
                path: String::new(),
                query: String::new(),
                fragment: String::new(),
            };
            match task::block_on(async { page_content(&connector, &parts).await }) {
                Ok(_) => Err(format!("unexpected OK connection: HTTP should fail")),
                Err(e)
                    if (*e).to_string() == "TCPStream error: Connection refused (os error 111)" =>
                {
                    Ok(())
                }
                Err(e) => Err(format!("unexpected error message: {}", e)),
            }
        }

        #[test]
        fn test_page_content_from_url_with_jump_next() -> Result<(), String> {
            let connector: TlsConnector = TlsConnector::default();
            let url: Url = Url::parse("https://wikipedia.org")
                .map_err(|e| format!("could not parse URL: {}", e))?;
            let next: Url = Url::parse("https://www.wikipedia.org")
                .map_err(|e| format!("could not parse URL: {}", e))?;
            let parts: Parts = Parts::try_from(&url)
                .map_err(|e| format!("could not parse parts from URL: {}", e))?;
            match task::block_on(async { page_content(&connector, &parts).await }) {
                Ok(Jump::Next(n)) if n == next => Ok(()),
                Ok(Jump::Next(n)) => Err(format!("unexpected Jump::Next URL: {}", n)),
                Ok(Jump::Landing(_)) => Err(format!("unexpected Jump::Landing")),
                Err(e) => Err(format!("could not run live test: {}", e)),
            }
        }

        #[test]
        fn test_page_content_from_url_with_jump_landing() -> Result<(), String> {
            let connector: TlsConnector = TlsConnector::default();
            let url: Url = Url::parse("https://example.org")
                .map_err(|e| format!("could not parse URL: {}", e))?;
            let parts: Parts = Parts::try_from(&url)
                .map_err(|e| format!("could not parse parts from URL: {}", e))?;
            let http_ok_header: &str = "HTTP/1.0 200 OK";
            match task::block_on(async { page_content(&connector, &parts).await }) {
                Ok(Jump::Landing(content))
                    if from_utf8(&content[0..http_ok_header.len()]) == Ok(http_ok_header) =>
                {
                    Ok(())
                }
                Ok(Jump::Landing(content)) => Err(format!(
                    "unexpected HTTP header: {:?}",
                    from_utf8(&content[0..http_ok_header.len()])
                )),
                Ok(Jump::Next(n)) => Err(format!("unexpected Jump::Next: {}", n)),
                Err(e) => Err(format!("could not run live test: {}", e)),
            }
        }

        mod parts {
            use super::*;

            #[test]
            fn test_parts_try_from_options_fails_when_empty() -> Result<(), String> {
                let options: Options = Options {
                    url: None,              // Option<String>
                    clipboard: false,       // bool
                    host: None,             // Option<String>
                    port: 0u16,             // u16
                    scheme: "".to_string(), // String
                    path: "".to_string(),   // String
                    query: None,            // Option<String>
                    fragment: None,         // Option<String>
                    domain: None,           // Option<String>
                    cafile: None,           // Option<PathBuf>
                    run: false,             // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if (*e).to_string()
                            == "use one and only one of --clipboard, --url or --host" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_options_fails_with_both_url_and_host() -> Result<(), String> {
                let options: Options = Options {
                    url: Some("url".to_string()),   // Option<String>
                    clipboard: false,               // bool
                    host: Some("host".to_string()), // Option<String>
                    port: 0u16,                     // u16
                    scheme: "".to_string(),         // String
                    path: "".to_string(),           // String
                    query: None,                    // Option<String>
                    fragment: None,                 // Option<String>
                    domain: None,                   // Option<String>
                    cafile: None,                   // Option<PathBuf>
                    run: false,                     // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if (*e).to_string()
                            == "use one and only one of --clipboard, --url or --host" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_options_fails_with_both_clipboard_and_host() -> Result<(), String>
            {
                let options: Options = Options {
                    url: None,                      // Option<String>
                    clipboard: true,                // bool
                    host: Some("host".to_string()), // Option<String>
                    port: 0u16,                     // u16
                    scheme: "".to_string(),         // String
                    path: "".to_string(),           // String
                    query: None,                    // Option<String>
                    fragment: None,                 // Option<String>
                    domain: None,                   // Option<String>
                    cafile: None,                   // Option<PathBuf>
                    run: false,                     // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if (*e).to_string()
                            == "use one and only one of --clipboard, --url or --host" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_options_fails_with_both_clipboard_and_url() -> Result<(), String>
            {
                let options: Options = Options {
                    url: Some("url".to_string()), // Option<String>
                    clipboard: true,              // bool
                    host: None,                   // Option<String>
                    port: 0u16,                   // u16
                    scheme: "".to_string(),       // String
                    path: "".to_string(),         // String
                    query: None,                  // Option<String>
                    fragment: None,               // Option<String>
                    domain: None,                 // Option<String>
                    cafile: None,                 // Option<PathBuf>
                    run: false,                   // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if (*e).to_string()
                            == "use one and only one of --clipboard, --url or --host" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_options_fails_with_both_clipboard_and_host_and_url()
            -> Result<(), String> {
                let options: Options = Options {
                    url: Some("url".to_string()),   // Option<String>
                    clipboard: true,                // bool
                    host: Some("host".to_string()), // Option<String>
                    port: 0u16,                     // u16
                    scheme: "".to_string(),         // String
                    path: "".to_string(),           // String
                    query: None,                    // Option<String>
                    fragment: None,                 // Option<String>
                    domain: None,                   // Option<String>
                    cafile: None,                   // Option<PathBuf>
                    run: false,                     // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if (*e).to_string()
                            == "use one and only one of --clipboard, --url or --host" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_options_fails_with_non_existing_url() -> Result<(), String> {
                let options: Options = Options {
                    url: Some("https://unresolvable.example.org".to_string()), // Option<String>
                    clipboard: false,                                          // bool
                    host: None,                                                // Option<String>
                    port: 0u16,                                                // u16
                    scheme: "".to_string(),                                    // String
                    path: "".to_string(),                                      // String
                    query: None,                                               // Option<String>
                    fragment: None,                                            // Option<String>
                    domain: None,                                              // Option<String>
                    cafile: None,                                              // Option<PathBuf>
                    run: false,                                                // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if e.to_string()
                            == "failed to lookup address information: Name or service not known" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!(
                        "unexpected error creating Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }

            #[test]
            fn test_parts_try_from_options_fails_with_non_supported_scheme() -> Result<(), String> {
                let options: Options = Options {
                    url: Some("news://example.org".to_string()), // Option<String>
                    clipboard: false,                            // bool
                    host: None,                                  // Option<String>
                    port: 0u16,                                  // u16
                    scheme: "".to_string(),                      // String
                    path: "".to_string(),                        // String
                    query: None,                                 // Option<String>
                    fragment: None,                              // Option<String>
                    domain: None,                                // Option<String>
                    cafile: None,                                // Option<PathBuf>
                    run: false,                                  // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if e.to_string()
                            == "Only HTTP(S) standard ports are suported. news given" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!(
                        "unexpected error creating Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }

            fn validate_parts_and_url(parts: Parts, url: Option<String>) -> Result<(), String> {
                if let Some(url) = url {
                    if parts.url != Url::parse(&url).unwrap() {
                        return Err(format!(
                            "could not create Options with the correct URL, got: {}",
                            parts.url
                        ));
                    }
                }
                if parts.host != Host::parse("example.org").unwrap() {
                    return Err(format!(
                        "could not create Options with the correct Host, got: {}",
                        parts.host
                    ));
                }
                if parts.port != 443 {
                    return Err(format!(
                        "could not create Options with the correct port, got: {}",
                        parts.port
                    ));
                }
                if parts.path != "/news/today.html".to_string() {
                    return Err(format!(
                        "could not create Options with the correct URL path, got: {}",
                        parts.path
                    ));
                }
                if parts.query != "tag=top".to_string() {
                    return Err(format!(
                        "could not create Options with the correct query, got: {}",
                        parts.query
                    ));
                }
                if parts.fragment != "headline".to_string() {
                    return Err(format!(
                        "could not create Options with the correct fragment, got: {}",
                        parts.fragment
                    ));
                }
                if parts.domain != "example.org".to_string() {
                    return Err(format!(
                        "could not create Options with the correct domain, got: {}",
                        parts.domain
                    ));
                }

                Ok(())
            }

            #[test]
            fn test_parts_try_from_options_passes_with_existing_url() -> Result<(), String> {
                let url: String =
                    "https://example.org/news/today.html?tag=top#headline".to_string();
                let options: Options = Options {
                    url: Some(url.clone()), // Option<String>
                    clipboard: false,       // bool
                    host: None,             // Option<String>
                    port: 0u16,             // u16
                    scheme: "".to_string(), // String
                    path: "".to_string(),   // String
                    query: None,            // Option<String>
                    fragment: None,         // Option<String>
                    domain: None,           // Option<String>
                    cafile: None,           // Option<PathBuf>
                    run: false,             // bool
                };
                match Parts::try_from(&options) {
                    Ok(parts) => validate_parts_and_url(parts, options.url),
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_options_fails_with_http_url() -> Result<(), String> {
                let url: String = "http://example.org".to_string();
                let options: Options = Options {
                    url: Some(url.clone()), // Option<String>
                    clipboard: false,       // bool
                    host: None,             // Option<String>
                    port: 0u16,             // u16
                    scheme: "".to_string(), // String
                    path: "".to_string(),   // String
                    query: None,            // Option<String>
                    fragment: None,         // Option<String>
                    domain: None,           // Option<String>
                    cafile: None,           // Option<PathBuf>
                    run: false,             // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e) if e.to_string() == "HTTP standard ports is not yet suported" => Ok(()),
                    Err(e) => Err(format!(
                        "unexpected error creating Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }

            #[test]
            fn test_parts_try_from_options_passes_ignoring_non_https_port_when_given()
            -> Result<(), String> {
                let url: String = "http://example.org".to_string();
                let options: Options = Options {
                    url: Some(url.clone()), // Option<String>
                    clipboard: false,       // bool
                    host: None,             // Option<String>
                    port: 8080u16,          // u16
                    scheme: "".to_string(), // String
                    path: "".to_string(),   // String
                    query: None,            // Option<String>
                    fragment: None,         // Option<String>
                    domain: None,           // Option<String>
                    cafile: None,           // Option<PathBuf>
                    run: false,             // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Ok(()),
                    Err(e) => Err(format!(
                        "could not create Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }

            #[test]
            fn test_parts_try_from_options_passes_with_another_domain() -> Result<(), String> {
                let url: String = "https://example.com".to_string();
                let options: Options = Options {
                    url: Some(url.clone()),                   // Option<String>
                    clipboard: false,                         // bool
                    host: None,                               // Option<String>
                    port: 0u16,                               // u16
                    scheme: "".to_string(),                   // String
                    path: "".to_string(),                     // String
                    query: None,                              // Option<String>
                    fragment: None,                           // Option<String>
                    domain: Some("unresolvable".to_string()), // Option<String>
                    cafile: None,                             // Option<PathBuf>
                    run: false,                               // bool
                };
                match Parts::try_from(&options) {
                    Ok(_) => Ok(()),
                    Err(e) => Err(format!(
                        "could not create Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }

            #[test]
            fn test_parts_try_from_options_passes_with_existing_clipboard() -> Result<(), String> {
                let url: String =
                    "https://example.org/news/today.html?tag=top#headline".to_string();
                let clipboard = Clipboard::new().unwrap();
                let atom_clipboard = clipboard.setter.atoms.clipboard;
                let atom_utf8string = clipboard.setter.atoms.utf8_string;
                clipboard
                    .store(atom_clipboard, atom_utf8string, url.as_bytes())
                    .map_err(|e| format!("could not store a value in the clipboard: {}", e))?;

                let options: Options = Options {
                    url: None,              // Option<String>
                    clipboard: true,        // bool
                    host: None,             // Option<String>
                    port: 0u16,             // u16
                    scheme: "".to_string(), // String
                    path: "".to_string(),   // String
                    query: None,            // Option<String>
                    fragment: None,         // Option<String>
                    domain: None,           // Option<String>
                    cafile: None,           // Option<PathBuf>
                    run: false,             // bool
                };
                match Parts::try_from(&options) {
                    Ok(parts) => validate_parts_and_url(parts, options.url),
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_options_passes_with_existing_host() -> Result<(), String> {
                let options: Options = Options {
                    url: None,                              // Option<String>
                    clipboard: false,                       // bool
                    host: Some("example.org".to_string()),  // Option<String>
                    port: 0u16,                             // u16
                    scheme: "https".to_string(),            // String
                    path: "/news/today.html".to_string(),   // String
                    query: Some("tag=top".to_string()),     // Option<String>
                    fragment: Some("headline".to_string()), // Option<String>
                    domain: None,                           // Option<String>
                    cafile: None,                           // Option<PathBuf>
                    run: false,                             // bool
                };
                match Parts::try_from(&options) {
                    Ok(parts) => validate_parts_and_url(parts, options.url),
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_str_passes_with_existing_url() -> Result<(), String> {
                let url: &str = "https://example.org/news/today.html?tag=top#headline";
                match Parts::try_from(url) {
                    Ok(parts) => validate_parts_and_url(parts, Some(url.to_string())),
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_str_fails_with_non_existing_url() -> Result<(), String> {
                let url: &str = "https://unresolvable.example.org/news/today.html?tag=top#headline";
                let parts: Result<Parts, Box<dyn Error>> = TryFrom::<&str>::try_from(url);
                match parts {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if e.to_string()
                            == "failed to lookup address information: Name or service not known" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!(
                        "unexpected error creating Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }

            #[test]
            fn test_parts_try_from_str_fails_with_non_supported_scheme() -> Result<(), String> {
                let url: &str = "news://example.org/news/today";
                let parts: Result<Parts, Box<dyn Error>> = TryFrom::<&str>::try_from(url);
                match parts {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if e.to_string()
                            == "Only HTTP(S) standard ports are suported. news given" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!(
                        "unexpected error creating Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }

            #[test]
            fn test_parts_try_from_url_passes_with_existing_url() -> Result<(), String> {
                let url: &str = "https://example.org/news/today.html?tag=top#headline";
                let url: Url = Url::parse(url).expect("cannot parse test URL");
                let parts: Result<Parts, Box<dyn Error>> = TryFrom::<&Url>::try_from(&url);
                match parts {
                    Ok(parts) => validate_parts_and_url(parts, Some(url.to_string())),
                    Err(e) => Err(format!("could not create Options: {}", e)),
                }
            }

            #[test]
            fn test_parts_try_from_url_fails_with_non_existing_url() -> Result<(), String> {
                let url: &str = "https://unresolvable.example.org/news/today.html?tag=top#headline";
                let url: Url = Url::parse(url).expect("cannot parse test URL");
                let parts: Result<Parts, Box<dyn Error>> = TryFrom::<&Url>::try_from(&url);
                match parts {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if e.to_string()
                            == "failed to lookup address information: Name or service not known" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!(
                        "unexpected error creating Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }

            #[test]
            fn test_parts_try_from_url_fails_with_non_supported_scheme() -> Result<(), String> {
                let url: &str = "news://example.org/news/today";
                let url: Url = Url::parse(url).expect("cannot parse test URL");
                let parts: Result<Parts, Box<dyn Error>> = TryFrom::<&Url>::try_from(&url);
                match parts {
                    Ok(_) => Err(format!("unexpected successful conversion into Parts")),
                    Err(e)
                        if e.to_string()
                            == "Only HTTP(S) standard ports are suported. news given" =>
                    {
                        Ok(())
                    }
                    Err(e) => Err(format!(
                        "unexpected error creating Parts from a URL: {}",
                        e.to_string()
                    )),
                }
            }
        }
    }

    #[test]
    fn test_clipboard_content_passes_trivially() -> Result<(), String> {
        // Note: this test reduces to testing an external dependency and it
        // doesn't have much raison d'ĂȘtre. This test would / will be more
        // meaningful when a direct implementation of the clipboard will
        // replace the dependency from x11_clipboard::Clipboard.

        let expected = format!("{:?}", Instant::now());
        let clipboard = Clipboard::new().unwrap();
        let atom_clipboard = clipboard.setter.atoms.clipboard;
        let atom_utf8string = clipboard.setter.atoms.utf8_string;
        clipboard
            .store(atom_clipboard, atom_utf8string, expected.as_bytes())
            .map_err(|e| format!("could not store a value in the clipboard: {}", e))?;
        match clipboard_content()
            .map_err(|e| format!("could not get a value from the cliboard: {}", e))
        {
            Ok(content) if content == expected => Ok(()),
            Ok(content) => Err(format!("unexpected paste content: {}", content)),
            Err(e) => Err(format!("could not read the clipboard: {}", e)),
        }
    }

    #[test]
    fn test_parts_http_request_passes_without_url_query() -> Result<(), String> {
        let parts: Parts = Parts::try_from("https://example.org/resource")
            .map_err(|e| format!("could not create a Parts structure from a str: {}", e))?;
        let expected: String = format!("GET /resource HTTP/1.0\r\nHost: example.org\r\n\r\n",);
        match parts.http_request() {
            req if req == expected => Ok(()),
            req => Err(format!("unexpected HTTP request: {}", req)),
        }
    }

    #[test]
    fn test_parts_http_request_passes_with_url_query_and_fragment() -> Result<(), String> {
        let parts: Parts =
            Parts::try_from("https://example.org/resource.html?tag=news#headline")
                .map_err(|e| format!("could not create a Parts structure from a str: {}", e))?;
        let expected: String =
            format!("GET /resource.html?tag=news#headline HTTP/1.0\r\nHost: example.org\r\n\r\n",);
        match parts.http_request() {
            req if req == expected => Ok(()),
            req => Err(format!("unexpected HTTP request: {}", req)),
        }
    }

    #[test]
    fn test_parts_http_request_passes_with_url_query() -> Result<(), String> {
        let parts: Parts = Parts::try_from("https://www.example.org/resource.html?tag=news")
            .map_err(|e| format!("could not create a Parts structure from a str: {}", e))?;
        let expected: String =
            format!("GET /resource.html?tag=news HTTP/1.0\r\nHost: www.example.org\r\n\r\n",);
        match parts.http_request() {
            req if req == expected => Ok(()),
            req => Err(format!("unexpected HTTP request: {}", req)),
        }
    }

    #[test]
    fn test_parts_http_request_passes_with_url_fragment() -> Result<(), String> {
        let parts: Parts = Parts::try_from("https://www.example.org/resource.html#headline")
            .map_err(|e| format!("could not create a Parts structure from a str: {}", e))?;
        let expected: String =
            format!("GET /resource.html#headline HTTP/1.0\r\nHost: www.example.org\r\n\r\n",);
        match parts.http_request() {
            req if req == expected => Ok(()),
            req => Err(format!("unexpected HTTP request: {}", req)),
        }
    }
}