1use std::cell::{Ref, RefMut};
2use std::str;
3
4use encoding_rs::{Encoding, UTF_8};
5use mime::Mime;
6use ntex_http::header;
7
8#[cfg(feature = "cookie")]
9use coo_kie::Cookie;
10
11use super::error::{ContentTypeError, DecodeError};
12use super::header::HeaderMap;
13use crate::util::Extensions;
14
15#[cfg(feature = "cookie")]
16struct Cookies(Vec<Cookie<'static>>);
17
18pub trait HttpMessage: Sized {
20 fn message_headers(&self) -> &HeaderMap;
22
23 fn message_extensions(&self) -> Ref<'_, Extensions>;
25
26 fn message_extensions_mut(&self) -> RefMut<'_, Extensions>;
28
29 fn content_type(&self) -> &str {
34 if let Some(content_type) = self.message_headers().get(header::CONTENT_TYPE)
35 && let Ok(content_type) = content_type.to_str()
36 {
37 return content_type.split(';').next().unwrap().trim();
38 }
39 ""
40 }
41
42 fn encoding(&self) -> Result<&'static Encoding, ContentTypeError> {
51 if let Some(mime_type) = self.mime_type()? {
52 if let Some(charset) = mime_type.get_param("charset") {
53 if let Some(enc) = Encoding::for_label_no_replacement(charset.as_str().as_bytes()) {
54 Ok(enc)
55 } else {
56 Err(ContentTypeError::UnknownEncoding)
57 }
58 } else {
59 Ok(UTF_8)
60 }
61 } else {
62 Ok(UTF_8)
63 }
64 }
65
66 fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError> {
73 if let Some(content_type) = self.message_headers().get(header::CONTENT_TYPE) {
74 if let Ok(content_type) = content_type.to_str() {
75 return match content_type.parse() {
76 Ok(mt) => Ok(Some(mt)),
77 Err(_) => Err(ContentTypeError::ParseError),
78 };
79 }
80 Err(ContentTypeError::ParseError)
81 } else {
82 Ok(None)
83 }
84 }
85
86 fn chunked(&self) -> Result<bool, DecodeError> {
93 if let Some(encodings) = self.message_headers().get(header::TRANSFER_ENCODING) {
94 if let Ok(s) = encodings.to_str() {
95 Ok(s.to_lowercase().contains("chunked"))
96 } else {
97 Err(DecodeError::Header)
98 }
99 } else {
100 Ok(false)
101 }
102 }
103
104 #[cfg(feature = "cookie")]
105 fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, coo_kie::ParseError> {
114 if self.message_extensions().get::<Cookies>().is_none() {
115 let mut cookies = Vec::new();
116 for hdr in self.message_headers().get_all(header::COOKIE) {
117 for pair in hdr.as_bytes().split(|b| *b == b';') {
118 if let Ok(pair) = str::from_utf8(pair)
119 && let Ok(cookie) = Cookie::parse_encoded(pair)
120 {
121 cookies.push(cookie.into_owned());
122 }
123 }
124 }
125 self.message_extensions_mut().insert(Cookies(cookies));
126 }
127 Ok(Ref::map(self.message_extensions(), |ext| {
128 &ext.get::<Cookies>().unwrap().0
129 }))
130 }
131
132 #[cfg(feature = "cookie")]
133 fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
135 if let Ok(cookies) = self.cookies() {
136 for cookie in cookies.iter() {
137 if cookie.name() == name {
138 return Some(cookie.to_owned());
139 }
140 }
141 }
142 None
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use encoding_rs::ISO_8859_2;
149
150 use super::*;
151 use crate::http::test::TestRequest;
152
153 #[test]
158 fn test_content_type() {
159 let req = TestRequest::with_header("content-type", "text/plain").build();
160 assert_eq!(req.content_type(), "text/plain");
161 let req =
162 TestRequest::with_header("content-type", "application/json; charset=utf=8").build();
163 assert_eq!(req.content_type(), "application/json");
164 let req = TestRequest::builder().build();
165 assert_eq!(req.content_type(), "");
166 }
167
168 #[test]
174 fn test_mime_type() {
175 let req = TestRequest::with_header("content-type", "application/json").build();
176 assert_eq!(req.mime_type().unwrap(), Some(mime::APPLICATION_JSON));
177 let req = TestRequest::builder().build();
178 assert_eq!(req.mime_type().unwrap(), None);
179 let req =
180 TestRequest::with_header("content-type", "application/json; charset=utf-8").build();
181 let mt = req.mime_type().unwrap().unwrap();
182 assert_eq!(mt.get_param(mime::CHARSET), Some(mime::UTF_8));
183 assert_eq!(mt.type_(), mime::APPLICATION);
184 assert_eq!(mt.subtype(), mime::JSON);
185 }
186
187 #[test]
192 fn test_mime_type_error() {
193 let req =
194 TestRequest::with_header("content-type", "applicationadfadsfasdflknadsfklnadsfjson")
195 .build();
196 assert_eq!(Err(ContentTypeError::ParseError), req.mime_type());
197 }
198
199 #[test]
204 fn test_encoding() {
205 let req = TestRequest::builder().build();
206 assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
207
208 let req = TestRequest::with_header("content-type", "application/json").build();
209 assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
210
211 let req = TestRequest::with_header("content-type", "application/json; charset=ISO-8859-2")
212 .build();
213 assert_eq!(ISO_8859_2, req.encoding().unwrap());
214 }
215
216 #[test]
221 fn test_encoding_error() {
222 let req = TestRequest::with_header("content-type", "applicatjson").build();
223 assert_eq!(Some(ContentTypeError::ParseError), req.encoding().err());
224
225 let req =
226 TestRequest::with_header("content-type", "application/json; charset=kkkttktk").build();
227 assert_eq!(
228 Some(ContentTypeError::UnknownEncoding),
229 req.encoding().err()
230 );
231 }
232
233 #[test]
238 fn test_chunked() {
239 let req = TestRequest::builder().build();
240 assert!(!req.chunked().unwrap());
241
242 let req = TestRequest::with_header(header::TRANSFER_ENCODING, "chunked").build();
243 assert!(req.chunked().unwrap());
244
245 let req = TestRequest::builder()
246 .header(
247 header::TRANSFER_ENCODING,
248 b"some va\xadscc\xacas0xsdasdlue".as_ref(),
249 )
250 .build();
251 assert!(req.chunked().is_err());
252 }
253
254 #[test]
259 fn test_mime_type_not_utf8() {
260 let req = TestRequest::default()
261 .header(
262 header::CONTENT_TYPE,
263 header::HeaderValue::from_bytes(b"text/\xff").unwrap(),
264 )
265 .build();
266 assert_eq!(req.mime_type(), Err(ContentTypeError::ParseError));
267 }
268
269 #[cfg(feature = "cookie")]
277 #[test]
278 fn test_cookie_malformed_pair() {
279 let req = TestRequest::default()
280 .header(header::COOKIE, "sid=ok; garbage; =x; a=b")
281 .header(
282 header::COOKIE,
283 header::HeaderValue::from_bytes(b"c\xff=1; d=2").unwrap(),
284 )
285 .build();
286 let names: Vec<_> = req
287 .cookies()
288 .unwrap()
289 .iter()
290 .map(|c| (c.name().to_owned(), c.value().to_owned()))
291 .collect();
292 assert_eq!(
293 names,
294 [
295 ("sid".into(), "ok".into()),
296 ("a".into(), "b".into()),
297 ("d".into(), "2".into())
298 ]
299 );
300 assert_eq!(req.cookie("sid").unwrap().value(), "ok");
301 }
302
303 #[cfg(feature = "cookie")]
308 #[test]
309 fn test_cookie_not_found() {
310 let req = TestRequest::default()
311 .header(header::COOKIE, "c1=v1; ")
312 .build();
313 assert_eq!(req.cookies().unwrap().len(), 1);
314 assert!(req.cookie("c2").is_none());
315 }
316}