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
extern crate regex;

use self::regex::Regex;
use super::{ValidatorOption, Validated, ValidatedWrapper};

use std::fmt::{self, Display, Debug, Formatter};
use std::str::Utf8Error;

use super::host::{Host, HostLocalable, HostError};

#[derive(Debug, PartialEq, Clone)]
pub enum HttpUrlError {
    IncorrectFormat,
    IncorrectHostFormat(HostError),
    LocalNotAllow,
    LocalNotFound,
    ProtocolNotAllow,
    ProtocolNotFound,
    UTF8Error(Utf8Error),
}

pub type HttpUrlResult = Result<HttpUrl, HttpUrlError>;

pub struct HttpUrlValidator {
    pub local: ValidatorOption,
    pub protocol: ValidatorOption,
}

#[derive(Clone)]
pub struct HttpUrl {
    protocol: usize,
    host: Host,
    host_index: usize,
    path: usize,
    query: usize,
    fragment: usize,
    full_http_url: String,
    full_http_url_len: usize,
    is_https: bool,
    is_local: bool,
    is_absolute: bool,
}

impl HttpUrl {
    pub fn get_protocol(&self) -> Option<&str> {
        if self.protocol != self.full_http_url_len {
            if self.is_absolute {
                Some(&self.full_http_url[..(self.host_index - 3)])
            } else {
                Some(&self.full_http_url[..(self.host_index - 1)])
            }
        } else {
            None
        }
    }

    pub fn get_host(&self) -> &Host {
        &self.host
    }

    pub fn get_path(&self) -> Option<&str> {
        if self.path != self.full_http_url_len {
            if self.query != self.full_http_url_len {
                Some(&self.full_http_url[self.path..(self.query - 1)])
            } else {
                if self.fragment != self.full_http_url_len {
                    Some(&self.full_http_url[self.path..(self.fragment - 1)])
                } else {
                    Some(&self.full_http_url[self.path..])
                }
            }
        } else {
            None
        }
    }

    pub fn get_query(&self) -> Option<&str> {
        if self.query != self.full_http_url_len {
            if self.fragment != self.full_http_url_len {
                Some(&self.full_http_url[self.query..(self.fragment - 1)])
            } else {
                Some(&self.full_http_url[self.query..])
            }
        } else {
            None
        }
    }

    pub fn get_fragment(&self) -> Option<&str> {
        if self.fragment != self.full_http_url_len {
            Some(&self.full_http_url[self.fragment..])
        } else {
            None
        }
    }

    pub fn get_full_http_url(&self) -> &str {
        &self.full_http_url
    }

    pub fn get_full_http_url_without_query_and_fragment(&self) -> &str {
        if self.query != self.full_http_url_len {
            &self.full_http_url[..(self.query - 1)]
        } else {
            if self.fragment != self.full_http_url_len {
                &self.full_http_url[..(self.fragment - 1)]
            } else {
                &self.full_http_url
            }
        }
    }

    pub fn is_https(&self) -> bool {
        self.is_https
    }

    pub fn is_local(&self) -> bool {
        self.is_local
    }
}

impl Validated for HttpUrl {}

impl Debug for HttpUrl {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_fmt(format_args!("HttpUrl({})", self.full_http_url))?;
        Ok(())
    }
}

impl Display for HttpUrl {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(&self.full_http_url)?;
        Ok(())
    }
}

impl PartialEq for HttpUrl {
    fn eq(&self, other: &Self) -> bool {
        self.full_http_url.eq(&other.full_http_url)
    }

    fn ne(&self, other: &Self) -> bool {
        self.full_http_url.ne(&other.full_http_url)
    }
}

impl HttpUrlValidator {
    pub fn is_http_url(&self, full_http_url: &str) -> bool {
        self.parse_inner(full_http_url).is_ok()
    }

    pub fn parse_string(&self, full_http_url: String) -> HttpUrlResult {
        let mut http_url_inner = self.parse_inner(&full_http_url)?;

        http_url_inner.full_http_url = full_http_url;

        Ok(http_url_inner)
    }

    pub fn parse_str(&self, full_http_url: &str) -> HttpUrlResult {
        let mut http_url_inner = self.parse_inner(full_http_url)?;

        http_url_inner.full_http_url = full_http_url.to_string();

        Ok(http_url_inner)
    }

    fn parse_inner(&self, full_http_url: &str) -> HttpUrlResult {
        let re = Regex::new(r"^((http|https):)?(//)?([\S&&[^/]]+)(/[\S&&[^?#]]*)?([?]([\S&&[^#]]*))?(#([\S]*))?$").unwrap();

        let c = match re.captures(&full_http_url) {
            Some(c) => c,
            None => return Err(HttpUrlError::LocalNotFound)
        };

        let full_http_url_len = full_http_url.len();

        let is_local;
        let mut is_https = false;

        let protocol = match c.get(2) {
            Some(m) => {
                if self.protocol.not_allow() {
                    return Err(HttpUrlError::ProtocolNotAllow);
                }

                let e = m.end();
                is_https = full_http_url[(e - 1)..e].eq("s");

                0
            }
            None => {
                if self.protocol.must() {
                    return Err(HttpUrlError::ProtocolNotFound);
                }

                full_http_url_len
            }
        };

        let is_absolute = c.get(3).is_some();

        let host;

        let host_index = match c.get(4) {
            Some(m) => {
                let host_localable = HostLocalable::from_str(&full_http_url[m.start()..m.end()]).map_err(|err| HttpUrlError::IncorrectHostFormat(err))?;

                match self.local {
                    ValidatorOption::Must => {
                        if !host_localable.is_local() {
                            return Err(HttpUrlError::LocalNotFound);
                        }
                    }
                    ValidatorOption::NotAllow => {
                        if host_localable.is_local() {
                            return Err(HttpUrlError::LocalNotAllow);
                        }
                    }
                    _ => {}
                }

                is_local = host_localable.is_local();

                host = host_localable.into_host();

                m.start()
            }
            None => {
                panic!("impossible");
            }
        };

        let path = match c.get(5) {
            Some(m) => {
                m.start()
            }
            None => {
                full_http_url_len
            }
        };

        let query = match c.get(7) {
            Some(m) => {
                m.start()
            }
            None => {
                full_http_url_len
            }
        };

        let fragment = match c.get(9) {
            Some(m) => {
                m.start()
            }
            None => {
                full_http_url_len
            }
        };


        Ok(HttpUrl {
            protocol,
            host,
            host_index,
            path,
            query,
            fragment,
            full_http_url: String::new(),
            full_http_url_len,
            is_https,
            is_local,
            is_absolute,
        })
    }
}

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

    #[test]
    fn test_http_url_methods() {
        let url = "https://magiclen.org:8080/path/to/something?a=1&b=2#12345".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        let http_url = huv.parse_string(url).unwrap();

        assert_eq!("https://magiclen.org:8080/path/to/something?a=1&b=2#12345", http_url.get_full_http_url());
        assert_eq!("https://magiclen.org:8080/path/to/something", http_url.get_full_http_url_without_query_and_fragment());
        assert_eq!("https", http_url.get_protocol().unwrap());
        assert_eq!("magiclen.org:8080", http_url.get_host().get_full_host());
        assert_eq!("/path/to/something", http_url.get_path().unwrap());
        assert_eq!("a=1&b=2", http_url.get_query().unwrap());
        assert_eq!("12345", http_url.get_fragment().unwrap());
        assert_eq!(false, http_url.is_local());
        assert_eq!(true, http_url.is_https());
    }

    #[test]
    fn test_http_url_lv1_1() {
        let url = "http://magiclen.org".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv1_2() {
        let url = "http://localhost".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::Allow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv1_3() {
        let url = "http://127.0.0.1".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::Allow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv2() {
        let url = "//magiclen.org".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv3() {
        let url = "magiclen.org".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv4_1() {
        let url = "https://magiclen.org/path/to/something".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv4_2() {
        let url = "https://localhost/path/to/something".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::Allow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv4_3() {
        let url = "https://127.0.0.1/path/to/something".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::Allow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv5() {
        let url = "https://magiclen.org/path/to/something".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv6() {
        let url = "https://magiclen.org/path/to/something?a=1".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv7() {
        let url = "https://magiclen.org/path/to/something?a=1".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }

    #[test]
    fn test_http_url_lv8() {
        let url = "https://magiclen.org/path/to/something?a=1&b=2#12345".to_string();

        let huv = HttpUrlValidator {
            local: ValidatorOption::NotAllow,
            protocol: ValidatorOption::Allow,
        };

        huv.parse_string(url).unwrap();
    }
}

macro_rules! extend {
    ( $name:ident, $protocol:expr, $local:expr ) => {
        #[derive(Clone)]
        pub struct $name(HttpUrl);

        impl From<$name> for HttpUrl {
            fn from(d: $name) -> Self {
                d.0
            }
        }

        impl Validated for $name {}

        impl ValidatedWrapper for $name {
            type Error = HttpUrlError;

            fn from_string(full_http_url: String) -> Result<Self, Self::Error>{
                $name::from_string(full_http_url)
            }

            fn from_str(full_http_url: &str) -> Result<Self, Self::Error>{
                $name::from_str(full_http_url)
            }
        }

        impl Debug for $name {
            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
                f.write_fmt(format_args!("{}({})", stringify!($name), self.0))?;
                Ok(())
            }
        }

        impl Display for $name {
            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
                Display::fmt(&self.0, f)
            }
        }

        impl PartialEq for $name {
            fn eq(&self, other: &Self) -> bool {
                self.0.eq(&other.0)
            }

            fn ne(&self, other: &Self) -> bool {
                self.0.ne(&other.0)
            }
        }

        impl PartialEq<HttpUrl> for $name {
            fn eq(&self, other: &HttpUrl) -> bool {
                self.0.eq(&other)
            }

            fn ne(&self, other: &HttpUrl) -> bool {
                self.0.ne(&other)
            }
        }

        impl $name {
            pub fn from_string(full_http_url: String) -> Result<$name, HttpUrlError> {
                let huv = HttpUrlValidator {
                    protocol: $protocol,
                    local: $local,
                };

                Ok($name(huv.parse_string(full_http_url)?))
            }

            pub fn from_str(full_http_url: &str) -> Result<$name, HttpUrlError> {
                let huv = HttpUrlValidator {
                    protocol: $protocol,
                    local: $local,
                };

                Ok($name(huv.parse_str(full_http_url)?))
            }

            pub fn from_http_url(http_url: HttpUrl) -> Result<$name, HttpUrlError> {
                 match $protocol {
                    ValidatorOption::Must => {
                        if http_url.protocol == http_url.full_http_url_len {
                            return Err(HttpUrlError::ProtocolNotFound)
                        }
                    },
                    ValidatorOption::NotAllow => {
                        if http_url.protocol == http_url.full_http_url_len {
                            return Err(HttpUrlError::ProtocolNotAllow)
                        }
                    }
                    _=>()
                }
                match $local {
                    ValidatorOption::Must => {
                        if !http_url.is_local {
                            return Err(HttpUrlError::LocalNotFound)
                        }
                    },
                    ValidatorOption::NotAllow => {
                        if http_url.is_local {
                            return Err(HttpUrlError::LocalNotAllow)
                        }
                    }
                    _=>()
                }

                Ok($name(http_url))
            }

            pub fn into_http_url(self) -> HttpUrl {
                self.0
            }

            pub fn as_http_url(&self) -> &HttpUrl {
                &self.0
            }
        }

        impl $name {
            pub fn get_host(&self) -> &Host {
                &self.0.host
            }

            pub fn get_path(&self) -> Option<&str> {
                if self.0.path != self.0.full_http_url_len {
                    if self.0.query != self.0.full_http_url_len {
                        Some(&self.0.full_http_url[self.0.path..(self.0.query - 1)])
                    } else {
                        if self.0.fragment != self.0.full_http_url_len {
                            Some(&self.0.full_http_url[self.0.path..(self.0.fragment - 1)])
                        } else {
                            Some(&self.0.full_http_url[self.0.path..])
                        }
                    }
                } else {
                    None
                }
            }

            pub fn get_query(&self) -> Option<&str> {
                if self.0.query != self.0.full_http_url_len {
                    if self.0.fragment != self.0.full_http_url_len {
                        Some(&self.0.full_http_url[self.0.query..(self.0.fragment - 1)])
                    } else {
                        Some(&self.0.full_http_url[self.0.query..])
                    }
                } else {
                    None
                }
            }

            pub fn get_fragment(&self) -> Option<&str> {
                if self.0.fragment != self.0.full_http_url_len {
                    Some(&self.0.full_http_url[self.0.fragment..])
                } else {
                    None
                }
            }

            pub fn get_full_http_url(&self) -> &str {
                &self.0.full_http_url
            }

            pub fn get_full_http_url_without_query_and_fragment(&self) -> &str {
                if self.0.query != self.0.full_http_url_len {
                    &self.0.full_http_url[..(self.0.query - 1)]
                } else {
                    if self.0.fragment != self.0.full_http_url_len {
                        &self.0.full_http_url[..(self.0.fragment - 1)]
                    } else {
                        &self.0.full_http_url
                    }
                }
            }

            pub fn is_https(&self) -> bool {
                self.0.is_https
            }
        }

         #[cfg(feature = "rocketly")]
        impl<'a> ::rocket::request::FromFormValue<'a> for $name {
            type Error = HttpUrlError;

            fn from_form_value(form_value: &'a ::rocket::http::RawStr) -> Result<Self, Self::Error>{
                $name::from_string(form_value.url_decode().map_err(|err| HttpUrlError::UTF8Error(err))?)
            }
        }
    };
}

extend!(HttpUrlLocalableWithProtocol, ValidatorOption::Must, ValidatorOption::Allow);

impl HttpUrlLocalableWithProtocol {
    pub fn get_protocol(&self) -> &str {
        if self.0.is_absolute {
            &self.0.full_http_url[..(self.0.host_index - 3)]
        } else {
            &self.0.full_http_url[..(self.0.host_index - 1)]
        }
    }

    pub fn is_local(&self) -> bool {
        self.0.is_local
    }
}

extend!(HttpUrlUnlocalableWithProtocol, ValidatorOption::Must, ValidatorOption::NotAllow);

impl HttpUrlUnlocalableWithProtocol {
    pub fn get_protocol(&self) -> &str {
        if self.0.is_absolute {
            &self.0.full_http_url[..(self.0.host_index - 3)]
        } else {
            &self.0.full_http_url[..(self.0.host_index - 1)]
        }
    }
}