-
Notifications
You must be signed in to change notification settings - Fork 677
/
http.rs
7009 lines (6467 loc) · 269 KB
/
http.rs
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
/*
copyright: (c) 2013-2020 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your option) any later version.
Blockstack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, including without the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Blockstack. If not, see <http://www.gnu.org/licenses/>.
*/
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::io::{Read, Write};
use std::mem;
use std::net::SocketAddr;
use std::str;
use std::str::FromStr;
use std::time::SystemTime;
use clarity::vm::representations::MAX_STRING_LEN;
use percent_encoding::percent_decode_str;
use regex::{Captures, Regex};
use serde::{Deserialize, Serialize};
use serde_json;
use time;
use url::{form_urlencoded, Url};
use crate::burnchains::{Address, Txid};
use crate::chainstate::burn::ConsensusHash;
use crate::chainstate::stacks::{
StacksBlock, StacksMicroblock, StacksPublicKey, StacksTransaction,
};
use crate::deps::httparse;
use crate::net::atlas::Attachment;
use crate::net::ClientError;
use crate::net::Error as net_error;
use crate::net::Error::ClarityError;
use crate::net::ExtendedStacksHeader;
use crate::net::HttpContentType;
use crate::net::HttpRequestMetadata;
use crate::net::HttpRequestPreamble;
use crate::net::HttpRequestType;
use crate::net::HttpResponseMetadata;
use crate::net::HttpResponsePreamble;
use crate::net::HttpResponseType;
use crate::net::HttpVersion;
use crate::net::MemPoolSyncData;
use crate::net::MessageSequence;
use crate::net::NeighborAddress;
use crate::net::PeerAddress;
use crate::net::PeerHost;
use crate::net::ProtocolFamily;
use crate::net::StacksHttpMessage;
use crate::net::StacksHttpPreamble;
use crate::net::UnconfirmedTransactionResponse;
use crate::net::UnconfirmedTransactionStatus;
use crate::net::HTTP_PREAMBLE_MAX_ENCODED_SIZE;
use crate::net::HTTP_PREAMBLE_MAX_NUM_HEADERS;
use crate::net::HTTP_REQUEST_ID_RESERVED;
use crate::net::MAX_HEADERS;
use crate::net::MAX_MICROBLOCKS_UNCONFIRMED;
use crate::net::{CallReadOnlyRequestBody, TipRequest};
use crate::net::{GetAttachmentResponse, GetAttachmentsInvResponse, PostTransactionRequestBody};
use clarity::vm::ast::parser::v1::CLARITY_NAME_REGEX;
use clarity::vm::types::{StandardPrincipalData, TraitIdentifier};
use clarity::vm::{
representations::{
CONTRACT_NAME_REGEX_STRING, PRINCIPAL_DATA_REGEX_STRING, STANDARD_PRINCIPAL_REGEX_STRING,
},
types::{PrincipalData, BOUND_VALUE_SERIALIZATION_HEX},
ClarityName, ContractName, Value,
};
use stacks_common::util::hash::hex_bytes;
use stacks_common::util::hash::to_hex;
use stacks_common::util::hash::Hash160;
use stacks_common::util::log;
use stacks_common::util::retry::BoundReader;
use stacks_common::util::retry::RetryReader;
use crate::chainstate::stacks::StacksBlockHeader;
use crate::chainstate::stacks::TransactionPayload;
use crate::codec::{
read_next, write_next, Error as codec_error, StacksMessageCodec, MAX_MESSAGE_LEN,
MAX_PAYLOAD_LEN,
};
use crate::types::chainstate::{BlockHeaderHash, StacksAddress, StacksBlockId};
use super::FeeRateEstimateRequestBody;
lazy_static! {
static ref PATH_GETINFO: Regex = Regex::new(r#"^/v2/info$"#).unwrap();
static ref PATH_GETPOXINFO: Regex = Regex::new(r#"^/v2/pox$"#).unwrap();
static ref PATH_GETNEIGHBORS: Regex = Regex::new(r#"^/v2/neighbors$"#).unwrap();
static ref PATH_GETHEADERS: Regex = Regex::new(r#"^/v2/headers/([0-9]+)$"#).unwrap();
static ref PATH_GETBLOCK: Regex = Regex::new(r#"^/v2/blocks/([0-9a-f]{64})$"#).unwrap();
static ref PATH_GETMICROBLOCKS_INDEXED: Regex =
Regex::new(r#"^/v2/microblocks/([0-9a-f]{64})$"#).unwrap();
static ref PATH_GETMICROBLOCKS_CONFIRMED: Regex =
Regex::new(r#"^/v2/microblocks/confirmed/([0-9a-f]{64})$"#).unwrap();
static ref PATH_GETMICROBLOCKS_UNCONFIRMED: Regex =
Regex::new(r#"^/v2/microblocks/unconfirmed/([0-9a-f]{64})/([0-9]{1,5})$"#).unwrap();
static ref PATH_GETTRANSACTION_UNCONFIRMED: Regex =
Regex::new(r#"^/v2/transactions/unconfirmed/([0-9a-f]{64})$"#).unwrap();
static ref PATH_POSTTRANSACTION: Regex = Regex::new(r#"^/v2/transactions$"#).unwrap();
static ref PATH_POST_FEE_RATE_ESIMATE: Regex = Regex::new(r#"^/v2/fees/transaction$"#).unwrap();
static ref PATH_POSTBLOCK: Regex = Regex::new(r#"^/v2/blocks/upload/([0-9a-f]{40})$"#).unwrap();
static ref PATH_POSTMICROBLOCK: Regex = Regex::new(r#"^/v2/microblocks$"#).unwrap();
static ref PATH_GET_ACCOUNT: Regex = Regex::new(&format!(
"^/v2/accounts/(?P<principal>{})$",
*PRINCIPAL_DATA_REGEX_STRING
))
.unwrap();
static ref PATH_GET_DATA_VAR: Regex = Regex::new(&format!(
"^/v2/data_var/(?P<address>{})/(?P<contract>{})/(?P<varname>{})$",
*STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_NAME_REGEX_STRING, *CLARITY_NAME_REGEX
))
.unwrap();
static ref PATH_GET_MAP_ENTRY: Regex = Regex::new(&format!(
"^/v2/map_entry/(?P<address>{})/(?P<contract>{})/(?P<map>{})$",
*STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_NAME_REGEX_STRING, *CLARITY_NAME_REGEX
))
.unwrap();
static ref PATH_POST_CALL_READ_ONLY: Regex = Regex::new(&format!(
"^/v2/contracts/call-read/(?P<address>{})/(?P<contract>{})/(?P<function>{})$",
*STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_NAME_REGEX_STRING, *CLARITY_NAME_REGEX
))
.unwrap();
static ref PATH_GET_CONTRACT_SRC: Regex = Regex::new(&format!(
"^/v2/contracts/source/(?P<address>{})/(?P<contract>{})$",
*STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_NAME_REGEX_STRING
))
.unwrap();
static ref PATH_GET_IS_TRAIT_IMPLEMENTED: Regex = Regex::new(&format!(
"^/v2/traits/(?P<address>{})/(?P<contract>{})/(?P<traitContractAddr>{})/(?P<traitContractName>{})/(?P<traitName>{})$",
*STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_NAME_REGEX_STRING, *STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_NAME_REGEX_STRING, *CLARITY_NAME_REGEX
))
.unwrap();
static ref PATH_GET_CONTRACT_ABI: Regex = Regex::new(&format!(
"^/v2/contracts/interface/(?P<address>{})/(?P<contract>{})$",
*STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_NAME_REGEX_STRING
))
.unwrap();
static ref PATH_GET_TRANSFER_COST: Regex = Regex::new("^/v2/fees/transfer$").unwrap();
static ref PATH_GET_ATTACHMENTS_INV: Regex = Regex::new("^/v2/attachments/inv$").unwrap();
static ref PATH_GET_ATTACHMENT: Regex =
Regex::new(r#"^/v2/attachments/([0-9a-f]{40})$"#).unwrap();
static ref PATH_POST_MEMPOOL_QUERY: Regex =
Regex::new(r#"^/v2/mempool/query$"#).unwrap();
static ref PATH_OPTIONS_WILDCARD: Regex = Regex::new("^/v2/.{0,4096}$").unwrap();
}
/// HTTP headers that we really care about
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum HttpReservedHeader {
ContentLength(u32),
ContentType(HttpContentType),
XRequestID(u32),
Host(PeerHost),
CanonicalStacksTipHeight(u64),
}
/// Stacks block accepted struct
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StacksBlockAcceptedData {
pub stacks_block_id: StacksBlockId,
pub accepted: bool,
}
impl FromStr for PeerHost {
type Err = net_error;
fn from_str(header: &str) -> Result<PeerHost, net_error> {
// we're looser than the RFC allows for DNS names -- anything that doesn't parse to an IP
// address will be parsed to a DNS name.
// try as IP:port
match header.parse::<SocketAddr>() {
Ok(socketaddr) => Ok(PeerHost::IP(
PeerAddress::from_socketaddr(&socketaddr),
socketaddr.port(),
)),
Err(_) => {
// maybe missing :port
let hostport = format!("{}:80", header);
match hostport.parse::<SocketAddr>() {
Ok(socketaddr) => Ok(PeerHost::IP(
PeerAddress::from_socketaddr(&socketaddr),
socketaddr.port(),
)),
Err(_) => {
// try as DNS-name:port
let host;
let port;
let parts: Vec<&str> = header.split(":").collect();
if parts.len() == 0 {
return Err(net_error::DeserializeError(
"Failed to parse PeerHost: no parts".to_string(),
));
} else if parts.len() == 1 {
// no port
host = Some(parts[0].to_string());
port = Some(80);
} else {
let np = parts.len();
if parts[np - 1].chars().all(char::is_numeric) {
// ends in :port
let host_str = parts[0..np - 1].join(":");
if host_str.len() == 0 {
return Err(net_error::DeserializeError(
"Empty host".to_string(),
));
}
host = Some(host_str);
let port_res = parts[np - 1].parse::<u16>();
port = match port_res {
Ok(p) => Some(p),
Err(_) => {
return Err(net_error::DeserializeError(
"Failed to parse PeerHost: invalid port".to_string(),
));
}
};
} else {
// only host
host = Some(header.to_string());
port = Some(80);
}
}
match (host, port) {
(Some(h), Some(p)) => Ok(PeerHost::DNS(h, p)),
(_, _) => Err(net_error::DeserializeError(
"Failed to parse PeerHost: failed to extract host and/or port"
.to_string(),
)), // I don't think this is reachable
}
}
}
}
}
}
}
impl HttpReservedHeader {
pub fn is_reserved(header: &str) -> bool {
let hdr = header.to_string();
match hdr.as_str() {
"content-length"
| "content-type"
| "x-request-id"
| "host"
| "x-canonical-stacks-tip-height" => true,
_ => false,
}
}
pub fn try_from_str(header: &str, value: &str) -> Option<HttpReservedHeader> {
let hdr = header.to_string().to_lowercase();
match hdr.as_str() {
"content-length" => match value.parse::<u32>() {
Ok(cl) => Some(HttpReservedHeader::ContentLength(cl)),
Err(_) => None,
},
"content-type" => match value.parse::<HttpContentType>() {
Ok(ct) => Some(HttpReservedHeader::ContentType(ct)),
Err(_) => None,
},
"x-request-id" => match value.parse::<u32>() {
Ok(rid) => Some(HttpReservedHeader::XRequestID(rid)),
Err(_) => None,
},
"host" => match value.parse::<PeerHost>() {
Ok(ph) => Some(HttpReservedHeader::Host(ph)),
Err(_) => None,
},
"x-canonical-stacks-tip-height" => match value.parse::<u64>() {
Ok(h) => Some(HttpReservedHeader::CanonicalStacksTipHeight(h)),
Err(_) => None,
},
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Copy)]
enum HttpChunkedTransferParseMode {
ChunkBoundary,
Chunk,
ChunkTrailer,
EOF,
}
#[derive(Debug, Clone, PartialEq, Copy)]
struct HttpChunkedTransferReaderState {
parse_step: HttpChunkedTransferParseMode,
chunk_size: u64,
chunk_read: u64,
max_size: u64,
total_size: u64,
last_chunk_size: u64,
// for parsing a chunk boundary
// (we don't use extensions, so 16 bytes for size + 2 for \r\n delimiter ought to be enough)
chunk_buffer: [u8; 18],
i: usize,
}
impl HttpChunkedTransferReaderState {
pub fn new(max_size: u64) -> HttpChunkedTransferReaderState {
HttpChunkedTransferReaderState {
parse_step: HttpChunkedTransferParseMode::ChunkBoundary,
chunk_size: 0,
chunk_read: 0,
max_size: max_size,
total_size: 0,
last_chunk_size: u64::MAX, // if this ever becomes 0, then we should expect chunk boundary '0\r\n\r\n' and EOF
chunk_buffer: [0u8; 18],
i: 0,
}
}
pub fn is_eof(&self) -> bool {
self.parse_step == HttpChunkedTransferParseMode::EOF
}
}
/// read adapter for chunked transfer encoding
struct HttpChunkedTransferReader<'a, R: Read> {
fd: &'a mut R,
state: HttpChunkedTransferReaderState,
}
impl<'a, R: Read> HttpChunkedTransferReader<'a, R> {
pub fn from_reader(r: &'a mut R, max_size: u64) -> HttpChunkedTransferReader<'a, R> {
HttpChunkedTransferReader {
fd: r,
state: HttpChunkedTransferReaderState::new(max_size),
}
}
pub fn from_state(
r: &'a mut R,
state: HttpChunkedTransferReaderState,
) -> HttpChunkedTransferReader<'a, R> {
HttpChunkedTransferReader {
fd: r,
state: state,
}
}
}
impl HttpChunkedTransferReaderState {
/// Read until we have a chunk marker we can parse completely.
/// Interruptable -- call repeatedly on EINTR.
/// Reads at most one byte.
fn read_chunk_boundary<R: Read>(&mut self, fd: &mut R) -> io::Result<usize> {
assert_eq!(self.parse_step, HttpChunkedTransferParseMode::ChunkBoundary);
// next byte
let mut b = [0u8; 1];
trace!("Read {} bytes", b.len());
let nr = fd.read(&mut b)?;
if nr == 0 {
return Ok(nr);
}
trace!("Got {} bytes", nr);
self.chunk_buffer[self.i] = b[0];
self.i += 1;
if self.i >= self.chunk_buffer.len() {
// don't allow ridiculous extension lengths
return Err(io::Error::new(
io::ErrorKind::InvalidData,
net_error::DeserializeError("Invalid HTTP chunk boundary: too long".to_string()),
));
}
let (offset, chunk_len) = match httparse::parse_chunk_size(&self.chunk_buffer[0..self.i]) {
Ok(httparse::Status::Partial) => {
return Ok(nr);
}
Ok(httparse::Status::Complete((offset, chunk_len))) => (offset, chunk_len),
Err(_) => {
test_debug!(
"Invalid chunk boundary: {:?}",
self.chunk_buffer[0..self.i].to_vec()
);
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Invalid HTTP chunk boundary: could not parse".to_string(),
));
}
};
trace!("chunk offset: {}. chunk len: {}", offset, chunk_len);
if chunk_len > MAX_MESSAGE_LEN as u64 {
trace!("chunk buffer: {:?}", &self.chunk_buffer[0..self.i]);
return Err(io::Error::new(
io::ErrorKind::InvalidData,
net_error::DeserializeError("Invalid HTTP chunk: too big".to_string()),
));
}
// got an offset/len.
// offset ought to equal the number of bytes taken by the encoded chunk boundary.
assert_eq!(offset, self.i);
// reset buffers
self.i = 0;
self.chunk_size = chunk_len;
self.chunk_read = 0;
// begin reading chunk
trace!("begin reading chunk");
self.parse_step = HttpChunkedTransferParseMode::Chunk;
Ok(nr)
}
/// Read a chunk -- read up to self.chunk_size bytes over successive calls.
/// Reads at most self.chunk_size bytes.
fn read_chunk_bytes<R: Read>(&mut self, fd: &mut R, buf: &mut [u8]) -> io::Result<usize> {
assert_eq!(self.parse_step, HttpChunkedTransferParseMode::Chunk);
if self.total_size >= self.max_size && self.chunk_size > 0 {
return Err(io::Error::new(
io::ErrorKind::Other,
net_error::OverflowError("HTTP body exceeds maximum expected length".to_string()),
));
}
let remaining =
if self.chunk_size - self.chunk_read <= (self.max_size - self.total_size) as u64 {
self.chunk_size - self.chunk_read
} else {
(self.max_size - self.total_size) as u64
};
let nr = if (buf.len() as u64) < remaining {
// can fill buffer
trace!("Read {} bytes (fill buffer)", buf.len());
fd.read(buf)? as u64
} else {
// will read up to a chunk boundary
trace!("Read {} bytes (fill remainder)", remaining);
fd.read(&mut buf[0..(remaining as usize)])? as u64
};
trace!("Got {} bytes", nr);
self.chunk_read += nr;
if self.chunk_read >= self.chunk_size {
// done reading; proceed to consume trailer
trace!(
"begin reading trailer ({} >= {})",
self.chunk_read,
self.chunk_size
);
self.parse_step = HttpChunkedTransferParseMode::ChunkTrailer;
}
self.total_size += nr;
Ok(nr as usize)
}
/// Read chunk trailer -- read end-of-chunk \r\n
/// Returns number of bytes read on success
/// Reads at most 2 bytes.
fn read_chunk_trailer<R: Read>(&mut self, fd: &mut R) -> io::Result<usize> {
assert_eq!(self.parse_step, HttpChunkedTransferParseMode::ChunkTrailer);
let mut nr = 0;
// read trailer
if self.i < 2 {
let mut trailer_buf = [0u8; 2];
trace!("Read at most {} bytes", 2 - self.i);
nr = fd.read(&mut trailer_buf[self.i..2])?;
if nr == 0 {
return Ok(nr);
}
self.chunk_buffer[self.i..2].copy_from_slice(&trailer_buf[self.i..2]);
self.i += nr;
}
if self.i == 2 {
// expect '\r\n'
if &self.chunk_buffer[0..2] != &[0x0d, 0x0a] {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
net_error::DeserializeError("Invalid chunk trailer".to_string()),
));
}
// end of chunk
self.last_chunk_size = self.chunk_size;
self.i = 0;
trace!("begin reading boundary");
self.parse_step = HttpChunkedTransferParseMode::ChunkBoundary;
}
trace!("Consumed {} bytes of chunk boundary (i = {})", nr, self.i);
Ok(nr)
}
/// Read from a Read.
/// Returns (number of bytes decoded, number of bytes consumed from the Read)
fn do_read<R: Read>(&mut self, fd: &mut R, buf: &mut [u8]) -> io::Result<(usize, usize)> {
let mut decoded = 0;
let mut consumed = 0;
while decoded < buf.len() {
match self.parse_step {
HttpChunkedTransferParseMode::ChunkBoundary => {
let count = self.read_chunk_boundary(fd)?;
if count == 0 {
break;
}
consumed += count;
}
HttpChunkedTransferParseMode::Chunk => {
let nr = self.read_chunk_bytes(fd, &mut buf[decoded..])?;
if nr == 0 && self.parse_step == HttpChunkedTransferParseMode::Chunk {
// still trying to read the chunk, but got 0 bytes
break;
}
decoded += nr;
consumed += nr;
}
HttpChunkedTransferParseMode::ChunkTrailer => {
let count = self.read_chunk_trailer(fd)?;
if count == 0 {
break;
}
consumed += count;
if self.last_chunk_size == 0 {
// we're done
trace!("finished last chunk");
self.parse_step = HttpChunkedTransferParseMode::EOF;
break;
}
}
HttpChunkedTransferParseMode::EOF => {
break;
}
}
}
Ok((decoded, consumed))
}
}
impl<'a, R: Read> Read for HttpChunkedTransferReader<'a, R> {
/// Read a HTTP chunk-encoded stream.
/// Returns number of decoded bytes (i.e. number of bytes copied to buf, as expected)
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.state
.do_read(self.fd, buf)
.and_then(|(decoded, _)| Ok(decoded))
}
}
pub struct HttpChunkedTransferWriterState {
chunk_size: usize,
chunk_buf: Vec<u8>,
corked: bool,
}
impl HttpChunkedTransferWriterState {
pub fn new(chunk_size: usize) -> HttpChunkedTransferWriterState {
HttpChunkedTransferWriterState {
chunk_size: chunk_size,
chunk_buf: vec![],
corked: false,
}
}
}
pub struct HttpChunkedTransferWriter<'a, 'state, W: Write> {
fd: &'a mut W,
state: &'state mut HttpChunkedTransferWriterState,
}
impl<'a, 'state, W: Write> HttpChunkedTransferWriter<'a, 'state, W> {
pub fn from_writer_state(
fd: &'a mut W,
state: &'state mut HttpChunkedTransferWriterState,
) -> HttpChunkedTransferWriter<'a, 'state, W> {
HttpChunkedTransferWriter {
fd: fd,
state: state,
}
}
fn send_chunk(fd: &mut W, chunk_size: usize, bytes: &[u8]) -> io::Result<usize> {
let to_send = if chunk_size < bytes.len() {
chunk_size
} else {
bytes.len()
};
fd.write_all(format!("{:x}\r\n", to_send).as_bytes())?;
fd.write_all(&bytes[0..to_send])?;
fd.write_all("\r\n".as_bytes())?;
Ok(to_send)
}
fn flush_chunk(&mut self) -> io::Result<usize> {
let sent = HttpChunkedTransferWriter::send_chunk(
&mut self.fd,
self.state.chunk_size,
&self.state.chunk_buf,
)?;
self.state.chunk_buf.clear();
Ok(sent)
}
fn buf_chunk(&mut self, buf: &[u8]) -> usize {
let to_copy = if self.state.chunk_size - self.state.chunk_buf.len() < buf.len() {
self.state.chunk_size - self.state.chunk_buf.len()
} else {
buf.len()
};
self.state.chunk_buf.extend_from_slice(&buf[0..to_copy]);
to_copy
}
pub fn cork(&mut self) -> () {
// block future flushes from sending trailing empty chunks -- we're done sending
self.state.corked = true;
}
pub fn corked(&self) -> bool {
self.state.corked
}
}
impl<'a, 'state, W: Write> Write for HttpChunkedTransferWriter<'a, 'state, W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut written = 0;
while written < buf.len() && !self.state.corked {
if self.state.chunk_buf.len() > 0 {
if self.state.chunk_buf.len() < self.state.chunk_size {
let nw = self.buf_chunk(&buf[written..]);
written += nw;
}
if self.state.chunk_buf.len() >= self.state.chunk_size {
self.flush_chunk()?;
}
} else {
if written + self.state.chunk_size < buf.len() {
let nw = HttpChunkedTransferWriter::send_chunk(
&mut self.fd,
self.state.chunk_size,
&buf[written..(written + self.state.chunk_size)],
)?;
written += nw;
} else {
let nw = self.buf_chunk(&buf[written..]);
written += nw;
}
}
}
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
// send out any buffered chunk data
if !self.state.corked {
self.flush_chunk().and_then(|nw| {
if nw > 0 {
// send empty chunk
self.fd
.write_all(format!("0\r\n\r\n").as_bytes())
.and_then(|_nw| Ok(()))
} else {
Ok(())
}
})
} else {
Ok(())
}
}
}
impl HttpRequestPreamble {
pub fn new(
version: HttpVersion,
verb: String,
path: String,
hostname: String,
port: u16,
keep_alive: bool,
) -> HttpRequestPreamble {
HttpRequestPreamble {
version: version,
verb: verb,
path: path,
host: PeerHost::from_host_port(hostname, port),
content_type: None,
content_length: None,
keep_alive: keep_alive,
headers: HashMap::new(),
}
}
pub fn new_serialized<W: Write, F>(
fd: &mut W,
version: &HttpVersion,
verb: &str,
path: &str,
host: &PeerHost,
keep_alive: bool,
content_length: Option<u32>,
content_type: Option<&HttpContentType>,
mut write_headers: F,
) -> Result<(), codec_error>
where
F: FnMut(&mut W) -> Result<(), codec_error>,
{
// "$verb $path HTTP/1.${version}\r\n"
fd.write_all(verb.as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all(" ".as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all(path.as_bytes())
.map_err(codec_error::WriteError)?;
match *version {
HttpVersion::Http10 => {
fd.write_all(" HTTP/1.0\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
HttpVersion::Http11 => {
fd.write_all(" HTTP/1.1\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
}
// "User-Agent: $agent\r\nHost: $host\r\n"
fd.write_all("User-Agent: stacks/2.0\r\nHost: ".as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all(format!("{}", host).as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all("\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
// content-type
match content_type {
Some(ref c) => {
fd.write_all("Content-Type: ".as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all(c.as_str().as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all("\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
None => {}
}
// content-length
match content_length {
Some(l) => {
fd.write_all("Content-Length: ".as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all(format!("{}", l).as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all("\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
None => {}
}
match *version {
HttpVersion::Http10 => {
if keep_alive {
fd.write_all("Connection: keep-alive\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
}
HttpVersion::Http11 => {
if !keep_alive {
fd.write_all("Connection: close\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
}
}
// headers
write_headers(fd)?;
// end-of-headers
fd.write_all("\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
Ok(())
}
#[cfg(test)]
pub fn from_headers(
version: HttpVersion,
verb: String,
path: String,
hostname: String,
port: u16,
keep_alive: bool,
mut keys: Vec<String>,
values: Vec<String>,
) -> HttpRequestPreamble {
assert_eq!(keys.len(), values.len());
let mut req = HttpRequestPreamble::new(version, verb, path, hostname, port, keep_alive);
for (k, v) in keys.drain(..).zip(values) {
req.add_header(k, v);
}
req
}
pub fn add_header(&mut self, key: String, value: String) -> () {
let hdr = key.to_lowercase();
if HttpReservedHeader::is_reserved(&hdr) {
match HttpReservedHeader::try_from_str(&hdr, &value) {
Some(h) => match h {
HttpReservedHeader::Host(ph) => {
self.host = ph;
return;
}
HttpReservedHeader::ContentType(ct) => {
self.content_type = Some(ct);
return;
}
_ => {} // can just fall through and insert
},
None => {
return;
}
}
}
self.headers.insert(hdr, value);
}
/// Content-Length for this request.
/// If there is no valid Content-Length header, then
/// the Content-Length is 0
pub fn get_content_length(&self) -> u32 {
self.content_length.unwrap_or(0)
}
/// Set the content-length for this request
pub fn set_content_length(&mut self, len: u32) -> () {
self.content_length = Some(len);
}
/// Set the content-type for this request
pub fn set_content_type(&mut self, content_type: HttpContentType) -> () {
self.content_type = Some(content_type)
}
}
fn empty_headers<W: Write>(_fd: &mut W) -> Result<(), codec_error> {
Ok(())
}
fn stacks_height_headers<W: Write>(
fd: &mut W,
md: &HttpRequestMetadata,
) -> Result<(), codec_error> {
match md.canonical_stacks_tip_height {
Some(height) => {
fd.write_all(format!("X-Canonical-Stacks-Tip-Height: {}\r\n", height).as_bytes())
.map_err(codec_error::WriteError)?;
}
_ => {}
}
Ok(())
}
fn keep_alive_headers<W: Write>(fd: &mut W, md: &HttpResponseMetadata) -> Result<(), codec_error> {
match md.client_version {
HttpVersion::Http10 => {
// client expects explicit keep-alive
if md.client_keep_alive {
fd.write_all("Connection: keep-alive\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
} else {
fd.write_all("Connection: close\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
}
HttpVersion::Http11 => {
// only need "connection: close" if we're explicitly _not_ doing keep-alive
if !md.client_keep_alive {
fd.write_all("Connection: close\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
}
}
match md.canonical_stacks_tip_height {
Some(height) => {
fd.write_all(format!("X-Canonical-Stacks-Tip-Height: {}\r\n", height).as_bytes())
.map_err(codec_error::WriteError)?;
}
_ => {}
}
Ok(())
}
fn write_headers<W: Write>(
fd: &mut W,
headers: &HashMap<String, String>,
) -> Result<(), codec_error> {
for (ref key, ref value) in headers.iter() {
fd.write_all(key.as_str().as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all(": ".as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all(value.as_str().as_bytes())
.map_err(codec_error::WriteError)?;
fd.write_all("\r\n".as_bytes())
.map_err(codec_error::WriteError)?;
}
Ok(())
}
fn default_accept_header() -> String {
format!(
"Accept: {}, {}, {}",
HttpContentType::Bytes,
HttpContentType::JSON,
HttpContentType::Text
)
}
/// Read from a stream until we see '\r\n\r\n', with the purpose of reading an HTTP preamble.
/// It's gonna be important here that R does some bufferring, since this reads byte by byte.
/// EOF if we read 0 bytes.
fn read_to_crlf2<R: Read>(fd: &mut R) -> Result<Vec<u8>, codec_error> {
let mut ret = Vec::with_capacity(HTTP_PREAMBLE_MAX_ENCODED_SIZE as usize);
while ret.len() < HTTP_PREAMBLE_MAX_ENCODED_SIZE as usize {
let mut b = [0u8];
fd.read_exact(&mut b).map_err(codec_error::ReadError)?;
ret.push(b[0]);
if ret.len() > 4 {
let last_4 = &ret[(ret.len() - 4)..ret.len()];
// '\r\n\r\n' is [0x0d, 0x0a, 0x0d, 0x0a]
if last_4 == &[0x0d, 0x0a, 0x0d, 0x0a] {
break;
}
}
}
Ok(ret)
}
impl StacksMessageCodec for HttpRequestPreamble {
fn consensus_serialize<W: Write>(&self, fd: &mut W) -> Result<(), codec_error> {
HttpRequestPreamble::new_serialized(
fd,
&self.version,
&self.verb,
&self.path,
&self.host,
self.keep_alive,
self.content_length.clone(),
self.content_type.as_ref(),
|ref mut fd| write_headers(fd, &self.headers),
)
}
fn consensus_deserialize<R: Read>(fd: &mut R) -> Result<HttpRequestPreamble, codec_error> {
// realistically, there won't be more than HTTP_PREAMBLE_MAX_NUM_HEADERS headers
let mut headers = [httparse::EMPTY_HEADER; HTTP_PREAMBLE_MAX_NUM_HEADERS];
let mut req = httparse::Request::new(&mut headers);
let buf_read = read_to_crlf2(fd)?;
// consume request
match req.parse(&buf_read).map_err(|e| {
codec_error::DeserializeError(format!("Failed to parse HTTP request: {:?}", &e))
})? {
httparse::Status::Partial => {
// partial
return Err(codec_error::UnderflowError(