       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
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    1470
    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    1480
    1481
    1482
    1483
    1484
    1485
    1486
    1487
    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505
    1506
    1507
    1508
    1509
    1510
    1511
    1512
    1513
    1514
    1515
    1516
    1517
    1518
    1519
    1520
    1521
    1522
    1523
    1524
    1525
    1526
    1527
    1528
    1529
    1530
    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    1539
    1540
    1541
    1542
    1543
    1544
    1545
    1546
    1547
    1548
    1549
    1550
    1551
    1552
    1553
    1554
    1555
    1556
    1557
    1558
    1559
    1560
    1561
    1562
    1563
    1564
    1565
    1566
    1567
    1568
    1569
    1570
    1571
    1572
    1573
    1574
    1575
    1576
    1577
    1578
    1579
    1580
    1581
    1582
    1583
    1584
    1585
    1586
    1587
    1588
    1589
    1590
    1591
    1592
    1593
    1594
    1595
    1596
    1597
    1598
    1599
    1600
    1601
    1602
    1603
    1604
    1605
    1606
    1607
    1608
    1609
    1610
    1611
    1612
    1613
    1614
    1615
    1616
    1617
    1618
    1619
    1620
    1621
    1622
    1623
    1624
    1625
    1626
    1627
    1628
    1629
    1630
    1631
    1632
    1633
    1634
    1635
    1636
    1637
    1638
    1639
    1640
    1641
    1642
    1643
    1644
    1645
    1646
    1647
    1648
    1649
    1650
    1651
    1652
    1653
    1654
    1655
    1656
    1657
    1658
    1659
    1660
    1661
    1662
    1663
    1664
    1665
    1666
    1667
    1668
    1669
    1670
    1671
    1672
    1673
    1674
    1675
    1676
    1677
    1678
    1679
    1680
    1681
    1682
    1683
    1684
    1685
    1686
    1687
    1688
    1689
    1690
    1691
    1692
    1693
    1694
    1695
    1696
    1697
    1698
    1699
    1700
    1701
    1702
    1703
    1704
    1705
    1706
    1707
    1708
    1709
    1710
    1711
    1712
    1713
    1714
    1715
    1716
    1717
    1718
    1719
    1720
    1721
    1722
    1723
    1724
    1725
    1726
    1727
    1728
    1729
    1730
    1731
    1732
    1733
    1734
    1735
    1736
    1737
    1738
    1739
    1740
    1741
    1742
    1743
    1744
    1745
    1746
    1747
    1748
    1749
    1750
    1751
    1752
    1753
    1754
    1755
    1756
    1757
    1758
    1759
    1760
    1761
    1762
    1763
    1764
    1765
    1766
    1767
    1768
    1769
    1770
    1771
    1772
    1773
    1774
    1775
    1776
    1777
    1778
    1779
    1780
    1781
    1782
    1783
    1784
    1785
    1786
    1787
    1788
    1789
    1790
    1791
    1792
    1793

    //! Static files support
    use std::fmt::Write;
    use std::fs::{DirEntry, File, Metadata};
    use std::io::{Read, Seek};
    use std::ops::{Deref, DerefMut};
    use std::path::{Path, PathBuf};
    use std::time::{SystemTime, UNIX_EPOCH};
    use std::{cmp, io};
    use std::marker::PhantomData;

    #[cfg(unix)]
    use std::os::unix::fs::MetadataExt;

    use bytes::Bytes;
    use futures::{Async, Future, Poll, Stream};
    use futures_cpupool::{CpuFuture, CpuPool};
    use htmlescape::encode_minimal as escape_html_entity;
    use mime;
    use mime_guess::{get_mime_type, guess_mime_type};
    use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};

    use error::{Error, StaticFileError};
    use handler::{AsyncResult, Handler, Responder, RouteHandler, WrapHandler};
    use header;
    use http::{ContentEncoding, Method, StatusCode};
    use httpmessage::HttpMessage;
    use httprequest::HttpRequest;
    use httpresponse::HttpResponse;
    use param::FromParam;
    use server::settings::DEFAULT_CPUPOOL;
    use header::{ContentDisposition, DispositionParam, DispositionType};

    ///Describes `StaticFiles` configiration
    ///
    ///To configure actix's static resources you need
    ///to define own configiration type and implement any method
    ///you wish to customize.
    ///As trait implements reasonable defaults for Actix.
    ///
    ///## Example
    ///
    ///```rust
    /// extern crate mime;
    /// extern crate actix_web;
    /// use actix_web::http::header::DispositionType;
    /// use actix_web::fs::{StaticFileConfig, NamedFile};
    ///
    /// #[derive(Default)]
    /// struct MyConfig;
    ///
    /// impl StaticFileConfig for MyConfig {
    ///     fn content_disposition_map(typ: mime::Name) -> DispositionType {
    ///         DispositionType::Attachment
    ///     }
    /// }
    ///
    /// let file = NamedFile::open_with_config("foo.txt", MyConfig);
    ///```
    pub trait StaticFileConfig: Default {
        ///Describes mapping for mime type to content disposition header
        ///
        ///By default `IMAGE`, `TEXT` and `VIDEO` are mapped to Inline.
        ///Others are mapped to Attachment
        fn content_disposition_map(typ: mime::Name) -> DispositionType {
            match typ {
                mime::IMAGE | mime::TEXT | mime::VIDEO => DispositionType::Inline,
                _ => DispositionType::Attachment,
            }
        }

        ///Describes whether Actix should attempt to calculate `ETag`
        ///
        ///Defaults to `true`
        fn is_use_etag() -> bool {
            true
        }

        ///Describes whether Actix should use last modified date of file.
        ///
        ///Defaults to `true`
        fn is_use_last_modifier() -> bool {
            true
        }

        ///Describes allowed methods to access static resources.
        ///
        ///By default all methods are allowed
        fn is_method_allowed(_method: &Method) -> bool {
            true
        }
    }

    ///Default content disposition as described in
    ///[StaticFileConfig](trait.StaticFileConfig.html)
    #[derive(Default)]
    pub struct DefaultConfig;
    impl StaticFileConfig for DefaultConfig {}

    /// Return the MIME type associated with a filename extension (case-insensitive).
    /// If `ext` is empty or no associated type for the extension was found, returns
    /// the type `application/octet-stream`.
    #[inline]
    pub fn file_extension_to_mime(ext: &str) -> mime::Mime {
        get_mime_type(ext)
    }

    /// A file with an associated name.
    #[derive(Debug)]
    pub struct NamedFile<C=DefaultConfig> {
        path: PathBuf,
        file: File,
        content_type: mime::Mime,
        content_disposition: header::ContentDisposition,
        md: Metadata,
        modified: Option<SystemTime>,
        cpu_pool: Option<CpuPool>,
        encoding: Option<ContentEncoding>,
        status_code: StatusCode,
        _cd_map: PhantomData<C>,
    }

    impl NamedFile {
        /// Attempts to open a file in read-only mode.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use actix_web::fs::NamedFile;
        ///
        /// let file = NamedFile::open("foo.txt");
        /// ```
        pub fn open<P: AsRef<Path>>(path: P) -> io::Result<NamedFile> {
            Self::open_with_config(path, DefaultConfig)
        }
    }

    impl<C: StaticFileConfig> NamedFile<C> {
        /// Attempts to open a file in read-only mode using provided configiration.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use actix_web::fs::{DefaultConfig, NamedFile};
        ///
        /// let file = NamedFile::open_with_config("foo.txt", DefaultConfig);
        /// ```
        pub fn open_with_config<P: AsRef<Path>>(path: P, _: C) -> io::Result<NamedFile<C>> {
            let path = path.as_ref().to_path_buf();

            // Get the name of the file and use it to construct default Content-Type
            // and Content-Disposition values
            let (content_type, content_disposition) = {
                let filename = match path.file_name() {
                    Some(name) => name.to_string_lossy(),
                    None => {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            "Provided path has no filename",
                        ))
                    }
                };

                let ct = guess_mime_type(&path);
                let disposition_type = C::content_disposition_map(ct.type_());
                let cd = ContentDisposition {
                    disposition: disposition_type,
                    parameters: vec![DispositionParam::Filename(
                        header::Charset::Ext("UTF-8".to_owned()),
                        None,
                        filename.as_bytes().to_vec(),
                    )],
                };
                (ct, cd)
            };

            let file = File::open(&path)?;
            let md = file.metadata()?;
            let modified = md.modified().ok();
            let cpu_pool = None;
            let encoding = None;
            Ok(NamedFile {
                path,
                file,
                content_type,
                content_disposition,
                md,
                modified,
                cpu_pool,
                encoding,
                status_code: StatusCode::OK,
                _cd_map: PhantomData
            })
        }

        /// Returns reference to the underlying `File` object.
        #[inline]
        pub fn file(&self) -> &File {
            &self.file
        }

        /// Retrieve the path of this file.
        ///
        /// # Examples
        ///
        /// ```rust
        /// # use std::io;
        /// use actix_web::fs::NamedFile;
        ///
        /// # fn path() -> io::Result<()> {
        /// let file = NamedFile::open("test.txt")?;
        /// assert_eq!(file.path().as_os_str(), "foo.txt");
        /// # Ok(())
        /// # }
        /// ```
        #[inline]
        pub fn path(&self) -> &Path {
            self.path.as_path()
        }

        /// Set `CpuPool` to use
        #[inline]
        pub fn set_cpu_pool(mut self, cpu_pool: CpuPool) -> Self {
            self.cpu_pool = Some(cpu_pool);
            self
        }

        /// Set response **Status Code**
        pub fn set_status_code(mut self, status: StatusCode) -> Self {
            self.status_code = status;
            self
        }

        /// Set the MIME Content-Type for serving this file. By default
        /// the Content-Type is inferred from the filename extension.
        #[inline]
        pub fn set_content_type(mut self, mime_type: mime::Mime) -> Self {
            self.content_type = mime_type;
            self
        }

        /// Set the Content-Disposition for serving this file. This allows
        /// changing the inline/attachment disposition as well as the filename
        /// sent to the peer. By default the disposition is `inline` for text,
        /// image, and video content types, and `attachment` otherwise, and
        /// the filename is taken from the path provided in the `open` method
        /// after converting it to UTF-8 using
        /// [to_string_lossy](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_string_lossy).
        #[inline]
        pub fn set_content_disposition(mut self, cd: header::ContentDisposition) -> Self {
            self.content_disposition = cd;
            self
        }

        /// Set content encoding for serving this file
        #[inline]
        pub fn set_content_encoding(mut self, enc: ContentEncoding) -> Self {
            self.encoding = Some(enc);
            self
        }

        fn etag(&self) -> Option<header::EntityTag> {
            // This etag format is similar to Apache's.
            self.modified.as_ref().map(|mtime| {
                let ino = {
                    #[cfg(unix)]
                    {
                        self.md.ino()
                    }
                    #[cfg(not(unix))]
                    {
                        0
                    }
                };

                let dur = mtime
                    .duration_since(UNIX_EPOCH)
                    .expect("modification time must be after epoch");
                header::EntityTag::strong(format!(
                    "{:x}:{:x}:{:x}:{:x}",
                    ino,
                    self.md.len(),
                    dur.as_secs(),
                    dur.subsec_nanos()
                ))
            })
        }

        fn last_modified(&self) -> Option<header::HttpDate> {
            self.modified.map(|mtime| mtime.into())
        }
    }

    impl<C> Deref for NamedFile<C> {
        type Target = File;

        fn deref(&self) -> &File {
            &self.file
        }
    }

    impl<C> DerefMut for NamedFile<C> {
        fn deref_mut(&mut self) -> &mut File {
            &mut self.file
        }
    }

    /// Returns true if `req` has no `If-Match` header or one which matches `etag`.
    fn any_match<S>(etag: Option<&header::EntityTag>, req: &HttpRequest<S>) -> bool {
        match req.get_header::<header::IfMatch>() {
            None | Some(header::IfMatch::Any) => true,
            Some(header::IfMatch::Items(ref items)) => {
                if let Some(some_etag) = etag {
                    for item in items {
                        if item.strong_eq(some_etag) {
                            return true;
                        }
                    }
                }
                false
            }
        }
    }

    /// Returns true if `req` doesn't have an `If-None-Match` header matching `req`.
    fn none_match<S>(etag: Option<&header::EntityTag>, req: &HttpRequest<S>) -> bool {
        match req.get_header::<header::IfNoneMatch>() {
            Some(header::IfNoneMatch::Any) => false,
            Some(header::IfNoneMatch::Items(ref items)) => {
                if let Some(some_etag) = etag {
                    for item in items {
                        if item.weak_eq(some_etag) {
                            return false;
                        }
                    }
                }
                true
            }
            None => true,
        }
    }

    impl<C: StaticFileConfig> Responder for NamedFile<C> {
        type Item = HttpResponse;
        type Error = io::Error;

        fn respond_to<S>(self, req: &HttpRequest<S>) -> Result<HttpResponse, io::Error> {
            if self.status_code != StatusCode::OK {
                let mut resp = HttpResponse::build(self.status_code);
                resp.set(header::ContentType(self.content_type.clone()))
                    .header(
                        header::CONTENT_DISPOSITION,
                        self.content_disposition.to_string(),
                    );

                if let Some(current_encoding) = self.encoding {
                    resp.content_encoding(current_encoding);
                }
                let reader = ChunkedReadFile {
                    size: self.md.len(),
                    offset: 0,
                    cpu_pool: self.cpu_pool.unwrap_or_else(|| req.cpu_pool().clone()),
                    file: Some(self.file),
                    fut: None,
                    counter: 0,
                };
                return Ok(resp.streaming(reader));
            }

            if !C::is_method_allowed(req.method())
            {
                return Ok(HttpResponse::MethodNotAllowed()
                    .header(header::CONTENT_TYPE, "text/plain")
                    .header(header::ALLOW, "GET, HEAD")
                    .body("This resource only supports GET and HEAD."));
            }

            let etag = match C::is_use_etag() {
                true => self.etag(),
                false => None,
            };
            let last_modified = match C::is_use_last_modifier() {
                true => self.last_modified(),
                false => None,
            };

            // check preconditions
            let precondition_failed = if !any_match(etag.as_ref(), req) {
                true
            } else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
                (last_modified, req.get_header())
            {
                m > since
            } else {
                false
            };

            // check last modified
            let not_modified = if !none_match(etag.as_ref(), req) {
                true
            } else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
                (last_modified, req.get_header())
            {
                m <= since
            } else {
                false
            };

            let mut resp = HttpResponse::build(self.status_code);
            resp.set(header::ContentType(self.content_type.clone()))
                .header(
                    header::CONTENT_DISPOSITION,
                    self.content_disposition.to_string(),
                );

            if let Some(current_encoding) = self.encoding {
                resp.content_encoding(current_encoding);
            }

            resp.if_some(last_modified, |lm, resp| {
                resp.set(header::LastModified(lm));
            }).if_some(etag, |etag, resp| {
                resp.set(header::ETag(etag));
            });

            resp.header(header::ACCEPT_RANGES, "bytes");

            let mut length = self.md.len();
            let mut offset = 0;

            // check for range header
            if let Some(ranges) = req.headers().get(header::RANGE) {
                if let Ok(rangesheader) = ranges.to_str() {
                    if let Ok(rangesvec) = HttpRange::parse(rangesheader, length) {
                        length = rangesvec[0].length;
                        offset = rangesvec[0].start;
                        resp.content_encoding(ContentEncoding::Identity);
                        resp.header(
                            header::CONTENT_RANGE,
                            format!(
                                "bytes {}-{}/{}",
                                offset,
                                offset + length - 1,
                                self.md.len()
                            ),
                        );
                    } else {
                        resp.header(header::CONTENT_RANGE, format!("bytes */{}", length));
                        return Ok(resp.status(StatusCode::RANGE_NOT_SATISFIABLE).finish());
                    };
                } else {
                    return Ok(resp.status(StatusCode::BAD_REQUEST).finish());
                };
            };

            resp.header(header::CONTENT_LENGTH, format!("{}", length));

            if precondition_failed {
                return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish());
            } else if not_modified {
                return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
            }

            if *req.method() == Method::HEAD {
                Ok(resp.finish())
            } else {
                let reader = ChunkedReadFile {
                    offset,
                    size: length,
                    cpu_pool: self.cpu_pool.unwrap_or_else(|| req.cpu_pool().clone()),
                    file: Some(self.file),
                    fut: None,
                    counter: 0,
                };
                if offset != 0 || length != self.md.len() {
                    return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
                };
                Ok(resp.streaming(reader))
            }
        }
    }

    /// A helper created from a `std::fs::File` which reads the file
    /// chunk-by-chunk on a `CpuPool`.
    pub struct ChunkedReadFile {
        size: u64,
        offset: u64,
        cpu_pool: CpuPool,
        file: Option<File>,
        fut: Option<CpuFuture<(File, Bytes), io::Error>>,
        counter: u64,
    }

    impl Stream for ChunkedReadFile {
        type Item = Bytes;
        type Error = Error;

        fn poll(&mut self) -> Poll<Option<Bytes>, Error> {
            if self.fut.is_some() {
                return match self.fut.as_mut().unwrap().poll()? {
                    Async::Ready((file, bytes)) => {
                        self.fut.take();
                        self.file = Some(file);
                        self.offset += bytes.len() as u64;
                        self.counter += bytes.len() as u64;
                        Ok(Async::Ready(Some(bytes)))
                    }
                    Async::NotReady => Ok(Async::NotReady),
                };
            }

            let size = self.size;
            let offset = self.offset;
            let counter = self.counter;

            if size == counter {
                Ok(Async::Ready(None))
            } else {
                let mut file = self.file.take().expect("Use after completion");
                self.fut = Some(self.cpu_pool.spawn_fn(move || {
                    let max_bytes: usize;
                    max_bytes = cmp::min(size.saturating_sub(counter), 65_536) as usize;
                    let mut buf = Vec::with_capacity(max_bytes);
                    file.seek(io::SeekFrom::Start(offset))?;
                    let nbytes = file.by_ref().take(max_bytes as u64).read_to_end(&mut buf)?;
                    if nbytes == 0 {
                        return Err(io::ErrorKind::UnexpectedEof.into());
                    }
                    Ok((file, Bytes::from(buf)))
                }));
                self.poll()
            }
        }
    }

    type DirectoryRenderer<S> =
        Fn(&Directory, &HttpRequest<S>) -> Result<HttpResponse, io::Error>;

    /// A directory; responds with the generated directory listing.
    #[derive(Debug)]
    pub struct Directory {
        /// Base directory
        pub base: PathBuf,
        /// Path of subdirectory to generate listing for
        pub path: PathBuf,
    }

    impl Directory {
        /// Create a new directory
        pub fn new(base: PathBuf, path: PathBuf) -> Directory {
            Directory { base, path }
        }

        /// Is this entry visible from this directory?
        pub fn is_visible(&self, entry: &io::Result<DirEntry>) -> bool {
            if let Ok(ref entry) = *entry {
                if let Some(name) = entry.file_name().to_str() {
                    if name.starts_with('.') {
                        return false;
                    }
                }
                if let Ok(ref md) = entry.metadata() {
                    let ft = md.file_type();
                    return ft.is_dir() || ft.is_file() || ft.is_symlink();
                }
            }
            false
        }
    }

    fn directory_listing<S>(
        dir: &Directory, req: &HttpRequest<S>,
    ) -> Result<HttpResponse, io::Error> {
        let index_of = format!("Index of {}", req.path());
        let mut body = String::new();
        let base = Path::new(req.path());

        for entry in dir.path.read_dir()? {
            if dir.is_visible(&entry) {
                let entry = entry.unwrap();
                let p = match entry.path().strip_prefix(&dir.path) {
                    Ok(p) => base.join(p),
                    Err(_) => continue,
                };
                // show file url as relative to static path
                let file_url = utf8_percent_encode(&p.to_string_lossy(), DEFAULT_ENCODE_SET)
                    .to_string();
                // " -- &quot;  & -- &amp;  ' -- &#x27;  < -- &lt;  > -- &gt;
                let file_name = escape_html_entity(&entry.file_name().to_string_lossy());

                // if file is a directory, add '/' to the end of the name
                if let Ok(metadata) = entry.metadata() {
                    if metadata.is_dir() {
                        let _ = write!(
                            body,
                            "<li><a href=\"{}\">{}/</a></li>",
                            file_url, file_name
                        );
                    } else {
                        let _ = write!(
                            body,
                            "<li><a href=\"{}\">{}</a></li>",
                            file_url, file_name
                        );
                    }
                } else {
                    continue;
                }
            }
        }

        let html = format!(
            "<html>\
             <head><title>{}</title></head>\
             <body><h1>{}</h1>\
             <ul>\
             {}\
             </ul></body>\n</html>",
            index_of, index_of, body
        );
        Ok(HttpResponse::Ok()
            .content_type("text/html; charset=utf-8")
            .body(html))
    }

    /// Static files handling
    ///
    /// `StaticFile` handler must be registered with `App::handler()` method,
    /// because `StaticFile` handler requires access sub-path information.
    ///
    /// ```rust
    /// # extern crate actix_web;
    /// use actix_web::{fs, App};
    ///
    /// fn main() {
    ///     let app = App::new()
    ///         .handler("/static", fs::StaticFiles::new(".").unwrap())
    ///         .finish();
    /// }
    /// ```
    pub struct StaticFiles<S, C=DefaultConfig> {
        directory: PathBuf,
        index: Option<String>,
        show_index: bool,
        cpu_pool: CpuPool,
        default: Box<RouteHandler<S>>,
        renderer: Box<DirectoryRenderer<S>>,
        _chunk_size: usize,
        _follow_symlinks: bool,
        _cd_map: PhantomData<C>,
    }

    impl<S: 'static> StaticFiles<S> {
        /// Create new `StaticFiles` instance for specified base directory.
        ///
        /// `StaticFile` uses `CpuPool` for blocking filesystem operations.
        /// By default pool with 20 threads is used.
        /// Pool size can be changed by setting ACTIX_CPU_POOL environment variable.
        pub fn new<T: Into<PathBuf>>(dir: T) -> Result<StaticFiles<S>, Error> {
            Self::with_config(dir, DefaultConfig)
        }

        /// Create new `StaticFiles` instance for specified base directory and
        /// `CpuPool`.
        pub fn with_pool<T: Into<PathBuf>>(
            dir: T, pool: CpuPool,
        ) -> Result<StaticFiles<S>, Error> {
            Self::with_config_pool(dir, pool, DefaultConfig)
        }
    }

    impl<S: 'static, C: StaticFileConfig> StaticFiles<S, C> {
        /// Create new `StaticFiles` instance for specified base directory.
        ///
        /// Identical with `new` but allows to specify configiration to use.
        pub fn with_config<T: Into<PathBuf>>(dir: T, config: C) -> Result<StaticFiles<S, C>, Error> {
            // use default CpuPool
            let pool = { DEFAULT_CPUPOOL.lock().clone() };

            StaticFiles::with_config_pool(dir, pool, config)
        }

        /// Create new `StaticFiles` instance for specified base directory with config and
        /// `CpuPool`.
        pub fn with_config_pool<T: Into<PathBuf>>(
            dir: T, pool: CpuPool, _: C
        ) -> Result<StaticFiles<S, C>, Error> {
            let dir = dir.into().canonicalize()?;

            if !dir.is_dir() {
                return Err(StaticFileError::IsNotDirectory.into());
            }

            Ok(StaticFiles {
                directory: dir,
                index: None,
                show_index: false,
                cpu_pool: pool,
                default: Box::new(WrapHandler::new(|_: &_| {
                    HttpResponse::new(StatusCode::NOT_FOUND)
                })),
                renderer: Box::new(directory_listing),
                _chunk_size: 0,
                _follow_symlinks: false,
                _cd_map: PhantomData
            })
        }

        /// Show files listing for directories.
        ///
        /// By default show files listing is disabled.
        pub fn show_files_listing(mut self) -> Self {
            self.show_index = true;
            self
        }

        /// Set custom directory renderer
        pub fn files_listing_renderer<F>(mut self, f: F) -> Self
        where
            for<'r, 's> F: Fn(&'r Directory, &'s HttpRequest<S>)
                    -> Result<HttpResponse, io::Error>
                + 'static,
        {
            self.renderer = Box::new(f);
            self
        }

        /// Set index file
        ///
        /// Redirects to specific index file for directory "/" instead of
        /// showing files listing.
        pub fn index_file<T: Into<String>>(mut self, index: T) -> StaticFiles<S, C> {
            self.index = Some(index.into());
            self
        }

        /// Sets default handler which is used when no matched file could be found.
        pub fn default_handler<H: Handler<S>>(mut self, handler: H) -> StaticFiles<S, C> {
            self.default = Box::new(WrapHandler::new(handler));
            self
        }

        fn try_handle(
            &self, req: &HttpRequest<S>,
        ) -> Result<AsyncResult<HttpResponse>, Error> {
            let tail: String = req.match_info().query("tail")?;
            let relpath = PathBuf::from_param(tail.trim_left_matches('/'))?;

            // full filepath
            let path = self.directory.join(&relpath).canonicalize()?;

            if path.is_dir() {
                if let Some(ref redir_index) = self.index {
                    // TODO: Don't redirect, just return the index content.
                    // TODO: It'd be nice if there were a good usable URL manipulation
                    // library
                    let mut new_path: String = req.path().to_owned();
                    if !new_path.ends_with('/') {
                        new_path.push('/');
                    }
                    new_path.push_str(redir_index);
                    HttpResponse::Found()
                        .header(header::LOCATION, new_path.as_str())
                        .finish()
                        .respond_to(&req)
                } else if self.show_index {
                    let dir = Directory::new(self.directory.clone(), path);
                    Ok((*self.renderer)(&dir, &req)?.into())
                } else {
                    Err(StaticFileError::IsDirectory.into())
                }
            } else {
                NamedFile::open_with_config(path, C::default())?
                    .set_cpu_pool(self.cpu_pool.clone())
                    .respond_to(&req)?
                    .respond_to(&req)
            }
        }
    }

    impl<S: 'static, C: 'static + StaticFileConfig> Handler<S> for StaticFiles<S, C> {
        type Result = Result<AsyncResult<HttpResponse>, Error>;

        fn handle(&self, req: &HttpRequest<S>) -> Self::Result {
            self.try_handle(req).or_else(|e| {
                debug!("StaticFiles: Failed to handle {}: {}", req.path(), e);
                Ok(self.default.handle(req))
            })
        }
    }

    /// HTTP Range header representation.
    #[derive(Debug, Clone, Copy)]
    struct HttpRange {
        pub start: u64,
        pub length: u64,
    }

    static PREFIX: &'static str = "bytes=";
    const PREFIX_LEN: usize = 6;

    impl HttpRange {
        /// Parses Range HTTP header string as per RFC 2616.
        ///
        /// `header` is HTTP Range header (e.g. `bytes=bytes=0-9`).
        /// `size` is full size of response (file).
        fn parse(header: &str, size: u64) -> Result<Vec<HttpRange>, ()> {
            if header.is_empty() {
                return Ok(Vec::new());
            }
            if !header.starts_with(PREFIX) {
                return Err(());
            }

            let size_sig = size as i64;
            let mut no_overlap = false;

            let all_ranges: Vec<Option<HttpRange>> = header[PREFIX_LEN..]
                .split(',')
                .map(|x| x.trim())
                .filter(|x| !x.is_empty())
                .map(|ra| {
                    let mut start_end_iter = ra.split('-');

                    let start_str = start_end_iter.next().ok_or(())?.trim();
                    let end_str = start_end_iter.next().ok_or(())?.trim();

                    if start_str.is_empty() {
                        // If no start is specified, end specifies the
                        // range start relative to the end of the file.
                        let mut length: i64 = try!(end_str.parse().map_err(|_| ()));

                        if length > size_sig {
                            length = size_sig;
                        }

                        Ok(Some(HttpRange {
                            start: (size_sig - length) as u64,
                            length: length as u64,
                        }))
                    } else {
                        let start: i64 = start_str.parse().map_err(|_| ())?;

                        if start < 0 {
                            return Err(());
                        }
                        if start >= size_sig {
                            no_overlap = true;
                            return Ok(None);
                        }

                        let length = if end_str.is_empty() {
                            // If no end is specified, range extends to end of the file.
                            size_sig - start
                        } else {
                            let mut end: i64 = end_str.parse().map_err(|_| ())?;

                            if start > end {
                                return Err(());
                            }

                            if end >= size_sig {
                                end = size_sig - 1;
                            }

                            end - start + 1
                        };

                        Ok(Some(HttpRange {
                            start: start as u64,
                            length: length as u64,
                        }))
                    }
                })
                .collect::<Result<_, _>>()?;

            let ranges: Vec<HttpRange> = all_ranges.into_iter().filter_map(|x| x).collect();

            if no_overlap && ranges.is_empty() {
                return Err(());
            }

            Ok(ranges)
        }
    }

    #[cfg(test)]
    mod tests {
        use std::fs;

        use super::*;
        use application::App;
        use body::{Binary, Body};
        use http::{header, Method, StatusCode};
        use test::{self, TestRequest};

        #[test]
        fn test_file_extension_to_mime() {
            let m = file_extension_to_mime("jpg");
            assert_eq!(m, mime::IMAGE_JPEG);

            let m = file_extension_to_mime("invalid extension!!");
            assert_eq!(m, mime::APPLICATION_OCTET_STREAM);

            let m = file_extension_to_mime("");
            assert_eq!(m, mime::APPLICATION_OCTET_STREAM);
        }

        #[test]
        fn test_named_file_text() {
            assert!(NamedFile::open("test--").is_err());
            let mut file = NamedFile::open("Cargo.toml")
                .unwrap()
                .set_cpu_pool(CpuPool::new(1));
            {
                file.file();
                let _f: &File = &file;
            }
            {
                let _f: &mut File = &mut file;
            }

            let req = TestRequest::default().finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "text/x-toml"
            );
            assert_eq!(
                resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
                "inline; filename=\"Cargo.toml\""
            );
        }

        #[test]
        fn test_named_file_set_content_type() {
            let mut file = NamedFile::open("Cargo.toml")
                .unwrap()
                .set_content_type(mime::TEXT_XML)
                .set_cpu_pool(CpuPool::new(1));
            {
                file.file();
                let _f: &File = &file;
            }
            {
                let _f: &mut File = &mut file;
            }

            let req = TestRequest::default().finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "text/xml"
            );
            assert_eq!(
                resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
                "inline; filename=\"Cargo.toml\""
            );
        }

        #[test]
        fn test_named_file_image() {
            let mut file = NamedFile::open("tests/test.png")
                .unwrap()
                .set_cpu_pool(CpuPool::new(1));
            {
                file.file();
                let _f: &File = &file;
            }
            {
                let _f: &mut File = &mut file;
            }

            let req = TestRequest::default().finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "image/png"
            );
            assert_eq!(
                resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
                "inline; filename=\"test.png\""
            );
        }

        #[test]
        fn test_named_file_image_attachment() {
            use header::{ContentDisposition, DispositionParam, DispositionType};
            let cd = ContentDisposition {
                disposition: DispositionType::Attachment,
                parameters: vec![DispositionParam::Filename(
                    header::Charset::Ext("UTF-8".to_owned()),
                    None,
                    "test.png".as_bytes().to_vec(),
                )],
            };
            let mut file = NamedFile::open("tests/test.png")
                .unwrap()
                .set_content_disposition(cd)
                .set_cpu_pool(CpuPool::new(1));
            {
                file.file();
                let _f: &File = &file;
            }
            {
                let _f: &mut File = &mut file;
            }

            let req = TestRequest::default().finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "image/png"
            );
            assert_eq!(
                resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
                "attachment; filename=\"test.png\""
            );
        }

        #[derive(Default)]
        pub struct AllAttachmentConfig;
        impl StaticFileConfig for AllAttachmentConfig {
            fn content_disposition_map(_typ: mime::Name) -> DispositionType {
                DispositionType::Attachment
            }
        }

        #[derive(Default)]
        pub struct AllInlineConfig;
        impl StaticFileConfig for AllInlineConfig {
            fn content_disposition_map(_typ: mime::Name) -> DispositionType {
                DispositionType::Inline
            }
        }

        #[test]
        fn test_named_file_image_attachment_and_custom_config() {
            let file = NamedFile::open_with_config("tests/test.png", AllAttachmentConfig)
                .unwrap()
                .set_cpu_pool(CpuPool::new(1));

            let req = TestRequest::default().finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "image/png"
            );
            assert_eq!(
                resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
                "attachment; filename=\"test.png\""
            );

            let file = NamedFile::open_with_config("tests/test.png", AllInlineConfig)
                .unwrap()
                .set_cpu_pool(CpuPool::new(1));

            let req = TestRequest::default().finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "image/png"
            );
            assert_eq!(
                resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
                "inline; filename=\"test.png\""
            );

        }

        #[test]
        fn test_named_file_binary() {
            let mut file = NamedFile::open("tests/test.binary")
                .unwrap()
                .set_cpu_pool(CpuPool::new(1));
            {
                file.file();
                let _f: &File = &file;
            }
            {
                let _f: &mut File = &mut file;
            }

            let req = TestRequest::default().finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "application/octet-stream"
            );
            assert_eq!(
                resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
                "attachment; filename=\"test.binary\""
            );
        }

        #[test]
        fn test_named_file_status_code_text() {
            let mut file = NamedFile::open("Cargo.toml")
                .unwrap()
                .set_status_code(StatusCode::NOT_FOUND)
                .set_cpu_pool(CpuPool::new(1));
            {
                file.file();
                let _f: &File = &file;
            }
            {
                let _f: &mut File = &mut file;
            }

            let req = TestRequest::default().finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "text/x-toml"
            );
            assert_eq!(
                resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
                "inline; filename=\"Cargo.toml\""
            );
            assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        }

        #[test]
        fn test_named_file_ranges_status_code() {
            let mut srv = test::TestServer::with_factory(|| {
                App::new().handler(
                    "test",
                    StaticFiles::new(".").unwrap().index_file("Cargo.toml"),
                )
            });

            // Valid range header
            let request = srv
                .get()
                .uri(srv.url("/t%65st/Cargo.toml"))
                .header(header::RANGE, "bytes=10-20")
                .finish()
                .unwrap();
            let response = srv.execute(request.send()).unwrap();
            assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);

            // Invalid range header
            let request = srv
                .get()
                .uri(srv.url("/t%65st/Cargo.toml"))
                .header(header::RANGE, "bytes=1-0")
                .finish()
                .unwrap();
            let response = srv.execute(request.send()).unwrap();

            assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
        }

        #[test]
        fn test_named_file_content_range_headers() {
            let mut srv = test::TestServer::with_factory(|| {
                App::new().handler(
                    "test",
                    StaticFiles::new(".")
                        .unwrap()
                        .index_file("tests/test.binary"),
                )
            });

            // Valid range header
            let request = srv
                .get()
                .uri(srv.url("/t%65st/tests/test.binary"))
                .header(header::RANGE, "bytes=10-20")
                .finish()
                .unwrap();

            let response = srv.execute(request.send()).unwrap();

            let contentrange = response
                .headers()
                .get(header::CONTENT_RANGE)
                .unwrap()
                .to_str()
                .unwrap();

            assert_eq!(contentrange, "bytes 10-20/100");

            // Invalid range header
            let request = srv
                .get()
                .uri(srv.url("/t%65st/tests/test.binary"))
                .header(header::RANGE, "bytes=10-5")
                .finish()
                .unwrap();

            let response = srv.execute(request.send()).unwrap();

            let contentrange = response
                .headers()
                .get(header::CONTENT_RANGE)
                .unwrap()
                .to_str()
                .unwrap();

            assert_eq!(contentrange, "bytes */100");
        }

        #[test]
        fn test_named_file_content_length_headers() {
            let mut srv = test::TestServer::with_factory(|| {
                App::new().handler(
                    "test",
                    StaticFiles::new(".")
                        .unwrap()
                        .index_file("tests/test.binary"),
                )
            });

            // Valid range header
            let request = srv
                .get()
                .uri(srv.url("/t%65st/tests/test.binary"))
                .header(header::RANGE, "bytes=10-20")
                .finish()
                .unwrap();

            let response = srv.execute(request.send()).unwrap();

            let contentlength = response
                .headers()
                .get(header::CONTENT_LENGTH)
                .unwrap()
                .to_str()
                .unwrap();

            assert_eq!(contentlength, "11");

            // Invalid range header
            let request = srv
                .get()
                .uri(srv.url("/t%65st/tests/test.binary"))
                .header(header::RANGE, "bytes=10-8")
                .finish()
                .unwrap();

            let response = srv.execute(request.send()).unwrap();

            let contentlength = response
                .headers()
                .get(header::CONTENT_LENGTH)
                .unwrap()
                .to_str()
                .unwrap();

            assert_eq!(contentlength, "0");

            // Without range header
            let request = srv
                .get()
                .uri(srv.url("/t%65st/tests/test.binary"))
                .no_default_headers()
                .finish()
                .unwrap();

            let response = srv.execute(request.send()).unwrap();

            let contentlength = response
                .headers()
                .get(header::CONTENT_LENGTH)
                .unwrap()
                .to_str()
                .unwrap();

            assert_eq!(contentlength, "100");

            // chunked
            let request = srv
                .get()
                .uri(srv.url("/t%65st/tests/test.binary"))
                .finish()
                .unwrap();

            let response = srv.execute(request.send()).unwrap();
            {
                let te = response
                    .headers()
                    .get(header::TRANSFER_ENCODING)
                    .unwrap()
                    .to_str()
                    .unwrap();
                assert_eq!(te, "chunked");
            }
            let bytes = srv.execute(response.body()).unwrap();
            let data = Bytes::from(fs::read("tests/test.binary").unwrap());
            assert_eq!(bytes, data);
        }

        #[derive(Default)]
        pub struct OnlyMethodHeadConfig;
        impl StaticFileConfig for OnlyMethodHeadConfig {
            fn is_method_allowed(method: &Method) -> bool {
                match *method {
                    Method::HEAD => true,
                    _ => false
                }
            }
        }

        #[test]
        fn test_named_file_not_allowed() {
            let file = NamedFile::open_with_config("Cargo.toml", OnlyMethodHeadConfig).unwrap();
            let req = TestRequest::default().method(Method::POST).finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);

            let file = NamedFile::open_with_config("Cargo.toml", OnlyMethodHeadConfig).unwrap();
            let req = TestRequest::default().method(Method::PUT).finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);

            let file = NamedFile::open_with_config("Cargo.toml", OnlyMethodHeadConfig).unwrap();
            let req = TestRequest::default().method(Method::GET).finish();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
        }

        #[test]
        fn test_named_file_content_encoding() {
            let req = TestRequest::default().method(Method::GET).finish();
            let file = NamedFile::open("Cargo.toml").unwrap();

            assert!(file.encoding.is_none());
            let resp = file
                .set_content_encoding(ContentEncoding::Identity)
                .respond_to(&req)
                .unwrap();

            assert!(resp.content_encoding().is_some());
            assert_eq!(resp.content_encoding().unwrap().as_str(), "identity");
        }

        #[test]
        fn test_named_file_any_method() {
            let req = TestRequest::default().method(Method::POST).finish();
            let file = NamedFile::open("Cargo.toml").unwrap();
            let resp = file.respond_to(&req).unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
        }

        #[test]
        fn test_static_files() {
            let mut st = StaticFiles::new(".").unwrap().show_files_listing();
            let req = TestRequest::with_uri("/missing")
                .param("tail", "missing")
                .finish();
            let resp = st.handle(&req).respond_to(&req).unwrap();
            let resp = resp.as_msg();
            assert_eq!(resp.status(), StatusCode::NOT_FOUND);

            st.show_index = false;
            let req = TestRequest::default().finish();
            let resp = st.handle(&req).respond_to(&req).unwrap();
            let resp = resp.as_msg();
            assert_eq!(resp.status(), StatusCode::NOT_FOUND);

            let req = TestRequest::default().param("tail", "").finish();

            st.show_index = true;
            let resp = st.handle(&req).respond_to(&req).unwrap();
            let resp = resp.as_msg();
            assert_eq!(
                resp.headers().get(header::CONTENT_TYPE).unwrap(),
                "text/html; charset=utf-8"
            );
            assert!(resp.body().is_binary());
            assert!(format!("{:?}", resp.body()).contains("README.md"));
        }

        #[test]
        fn test_static_files_bad_directory() {
            let st: Result<StaticFiles<()>, Error> = StaticFiles::new("missing");
            assert!(st.is_err());

            let st: Result<StaticFiles<()>, Error> = StaticFiles::new("Cargo.toml");
            assert!(st.is_err());
        }

        #[test]
        fn test_default_handler_file_missing() {
            let st = StaticFiles::new(".")
                .unwrap()
                .default_handler(|_: &_| "default content");
            let req = TestRequest::with_uri("/missing")
                .param("tail", "missing")
                .finish();

            let resp = st.handle(&req).respond_to(&req).unwrap();
            let resp = resp.as_msg();
            assert_eq!(resp.status(), StatusCode::OK);
            assert_eq!(
                resp.body(),
                &Body::Binary(Binary::Slice(b"default content"))
            );
        }

        #[test]
        fn test_redirect_to_index() {
            let st = StaticFiles::new(".").unwrap().index_file("index.html");
            let req = TestRequest::default().uri("/tests").finish();

            let resp = st.handle(&req).respond_to(&req).unwrap();
            let resp = resp.as_msg();
            assert_eq!(resp.status(), StatusCode::FOUND);
            assert_eq!(
                resp.headers().get(header::LOCATION).unwrap(),
                "/tests/index.html"
            );

            let req = TestRequest::default().uri("/tests/").finish();
            let resp = st.handle(&req).respond_to(&req).unwrap();
            let resp = resp.as_msg();
            assert_eq!(resp.status(), StatusCode::FOUND);
            assert_eq!(
                resp.headers().get(header::LOCATION).unwrap(),
                "/tests/index.html"
            );
        }

        #[test]
        fn test_redirect_to_index_nested() {
            let st = StaticFiles::new(".").unwrap().index_file("mod.rs");
            let req = TestRequest::default().uri("/src/client").finish();
            let resp = st.handle(&req).respond_to(&req).unwrap();
            let resp = resp.as_msg();
            assert_eq!(resp.status(), StatusCode::FOUND);
            assert_eq!(
                resp.headers().get(header::LOCATION).unwrap(),
                "/src/client/mod.rs"
            );
        }

        #[test]
        fn integration_redirect_to_index_with_prefix() {
            let mut srv = test::TestServer::with_factory(|| {
                App::new()
                    .prefix("public")
                    .handler("/", StaticFiles::new(".").unwrap().index_file("Cargo.toml"))
            });

            let request = srv.get().uri(srv.url("/public")).finish().unwrap();
            let response = srv.execute(request.send()).unwrap();
            assert_eq!(response.status(), StatusCode::FOUND);
            let loc = response
                .headers()
                .get(header::LOCATION)
                .unwrap()
                .to_str()
                .unwrap();
            assert_eq!(loc, "/public/Cargo.toml");

            let request = srv.get().uri(srv.url("/public/")).finish().unwrap();
            let response = srv.execute(request.send()).unwrap();
            assert_eq!(response.status(), StatusCode::FOUND);
            let loc = response
                .headers()
                .get(header::LOCATION)
                .unwrap()
                .to_str()
                .unwrap();
            assert_eq!(loc, "/public/Cargo.toml");
        }

        #[test]
        fn integration_redirect_to_index() {
            let mut srv = test::TestServer::with_factory(|| {
                App::new().handler(
                    "test",
                    StaticFiles::new(".").unwrap().index_file("Cargo.toml"),
                )
            });

            let request = srv.get().uri(srv.url("/test")).finish().unwrap();
            let response = srv.execute(request.send()).unwrap();
            assert_eq!(response.status(), StatusCode::FOUND);
            let loc = response
                .headers()
                .get(header::LOCATION)
                .unwrap()
                .to_str()
                .unwrap();
            assert_eq!(loc, "/test/Cargo.toml");

            let request = srv.get().uri(srv.url("/test/")).finish().unwrap();
            let response = srv.execute(request.send()).unwrap();
            assert_eq!(response.status(), StatusCode::FOUND);
            let loc = response
                .headers()
                .get(header::LOCATION)
                .unwrap()
                .to_str()
                .unwrap();
            assert_eq!(loc, "/test/Cargo.toml");
        }

        #[test]
        fn integration_percent_encoded() {
            let mut srv = test::TestServer::with_factory(|| {
                App::new().handler(
                    "test",
                    StaticFiles::new(".").unwrap().index_file("Cargo.toml"),
                )
            });

            let request = srv
                .get()
                .uri(srv.url("/test/%43argo.toml"))
                .finish()
                .unwrap();
            let response = srv.execute(request.send()).unwrap();
            assert_eq!(response.status(), StatusCode::OK);
        }

        struct T(&'static str, u64, Vec<HttpRange>);

        #[test]
        fn test_parse() {
            let tests = vec![
                T("", 0, vec![]),
                T("", 1000, vec![]),
                T("foo", 0, vec![]),
                T("bytes=", 0, vec![]),
                T("bytes=7", 10, vec![]),
                T("bytes= 7 ", 10, vec![]),
                T("bytes=1-", 0, vec![]),
                T("bytes=5-4", 10, vec![]),
                T("bytes=0-2,5-4", 10, vec![]),
                T("bytes=2-5,4-3", 10, vec![]),
                T("bytes=--5,4--3", 10, vec![]),
                T("bytes=A-", 10, vec![]),
                T("bytes=A- ", 10, vec![]),
                T("bytes=A-Z", 10, vec![]),
                T("bytes= -Z", 10, vec![]),
                T("bytes=5-Z", 10, vec![]),
                T("bytes=Ran-dom, garbage", 10, vec![]),
                T("bytes=0x01-0x02", 10, vec![]),
                T("bytes=         ", 10, vec![]),
                T("bytes= , , ,   ", 10, vec![]),
                T(
                    "bytes=0-9",
                    10,
                    vec![HttpRange {
                        start: 0,
                        length: 10,
                    }],
                ),
                T(
                    "bytes=0-",
                    10,
                    vec![HttpRange {
                        start: 0,
                        length: 10,
                    }],
                ),
                T(
                    "bytes=5-",
                    10,
                    vec![HttpRange {
                        start: 5,
                        length: 5,
                    }],
                ),
                T(
                    "bytes=0-20",
                    10,
                    vec![HttpRange {
                        start: 0,
                        length: 10,
                    }],
                ),
                T(
                    "bytes=15-,0-5",
                    10,
                    vec![HttpRange {
                        start: 0,
                        length: 6,
                    }],
                ),
                T(
                    "bytes=1-2,5-",
                    10,
                    vec![
                        HttpRange {
                            start: 1,
                            length: 2,
                        },
                        HttpRange {
                            start: 5,
                            length: 5,
                        },
                    ],
                ),
                T(
                    "bytes=-2 , 7-",
                    11,
                    vec![
                        HttpRange {
                            start: 9,
                            length: 2,
                        },
                        HttpRange {
                            start: 7,
                            length: 4,
                        },
                    ],
                ),
                T(
                    "bytes=0-0 ,2-2, 7-",
                    11,
                    vec![
                        HttpRange {
                            start: 0,
                            length: 1,
                        },
                        HttpRange {
                            start: 2,
                            length: 1,
                        },
                        HttpRange {
                            start: 7,
                            length: 4,
                        },
                    ],
                ),
                T(
                    "bytes=-5",
                    10,
                    vec![HttpRange {
                        start: 5,
                        length: 5,
                    }],
                ),
                T(
                    "bytes=-15",
                    10,
                    vec![HttpRange {
                        start: 0,
                        length: 10,
                    }],
                ),
                T(
                    "bytes=0-499",
                    10000,
                    vec![HttpRange {
                        start: 0,
                        length: 500,
                    }],
                ),
                T(
                    "bytes=500-999",
                    10000,
                    vec![HttpRange {
                        start: 500,
                        length: 500,
                    }],
                ),
                T(
                    "bytes=-500",
                    10000,
                    vec![HttpRange {
                        start: 9500,
                        length: 500,
                    }],
                ),
                T(
                    "bytes=9500-",
                    10000,
                    vec![HttpRange {
                        start: 9500,
                        length: 500,
                    }],
                ),
                T(
                    "bytes=0-0,-1",
                    10000,
                    vec![
                        HttpRange {
                            start: 0,
                            length: 1,
                        },
                        HttpRange {
                            start: 9999,
                            length: 1,
                        },
                    ],
                ),
                T(
                    "bytes=500-600,601-999",
                    10000,
                    vec![
                        HttpRange {
                            start: 500,
                            length: 101,
                        },
                        HttpRange {
                            start: 601,
                            length: 399,
                        },
                    ],
                ),
                T(
                    "bytes=500-700,601-999",
                    10000,
                    vec![
                        HttpRange {
                            start: 500,
                            length: 201,
                        },
                        HttpRange {
                            start: 601,
                            length: 399,
                        },
                    ],
                ),
                // Match Apache laxity:
                T(
                    "bytes=   1 -2   ,  4- 5, 7 - 8 , ,,",
                    11,
                    vec![
                        HttpRange {
                            start: 1,
                            length: 2,
                        },
                        HttpRange {
                            start: 4,
                            length: 2,
                        },
                        HttpRange {
                            start: 7,
                            length: 2,
                        },
                    ],
                ),
            ];

            for t in tests {
                let header = t.0;
                let size = t.1;
                let expected = t.2;

                let res = HttpRange::parse(header, size);

                if res.is_err() {
                    if expected.is_empty() {
                        continue;
                    } else {
                        assert!(
                            false,
                            "parse({}, {}) returned error {:?}",
                            header,
                            size,
                            res.unwrap_err()
                        );
                    }
                }

                let got = res.unwrap();

                if got.len() != expected.len() {
                    assert!(
                        false,
                        "len(parseRange({}, {})) = {}, want {}",
                        header,
                        size,
                        got.len(),
                        expected.len()
                    );
                    continue;
                }

                for i in 0..expected.len() {
                    if got[i].start != expected[i].start {
                        assert!(
                            false,
                            "parseRange({}, {})[{}].start = {}, want {}",
                            header, size, i, got[i].start, expected[i].start
                        )
                    }
                    if got[i].length != expected[i].length {
                        assert!(
                            false,
                            "parseRange({}, {})[{}].length = {}, want {}",
                            header, size, i, got[i].length, expected[i].length
                        )
                    }
                }
            }
        }
    }

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g. `str,u8` or `String,struct:Vec,test`)