-
Notifications
You must be signed in to change notification settings - Fork 787
/
Uri.scala
1432 lines (1203 loc) · 50.1 KB
/
Uri.scala
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 2013 http4s.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2013-2020 http4s.org
*
* SPDX-License-Identifier: Apache-2.0
*
* Based on https://github.com/scalatra/rl/blob/v0.4.10/core/src/main/scala/rl/UrlCodingUtils.scala
* Copyright (c) 2011 Mojolly Ltd.
* See licenses/LICENSE_rl
*/
package org.http4s
import cats.Contravariant
import cats.Eval
import cats.Hash
import cats.Order
import cats.Show
import cats.data.NonEmptyList
import cats.kernel.Semigroup
import cats.parse.Parser0
import cats.parse.{Parser => P}
import cats.syntax.all._
import com.comcast.ip4s
import org.http4s.internal.UriCoding
import org.http4s.internal.compareField
import org.http4s.internal.hashLower
import org.http4s.internal.parsing.Rfc3986
import org.http4s.internal.reduceComparisons
import org.http4s.util.Renderable
import org.http4s.util.Writer
import org.typelevel.ci.CIString
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.InetAddress
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.StandardCharsets
import java.nio.charset.{Charset => JCharset}
import scala.collection.immutable
import scala.util.hashing.MurmurHash3
/** Representation of the [[Request]] URI
*
* @param scheme optional Uri Scheme. eg, http, https
* @param authority optional Uri Authority. eg, localhost:8080, www.foo.bar
* @param path url-encoded string representation of the path component of the Uri.
* @param query optional Query. url-encoded.
* @param fragment optional Uri Fragment. url-encoded.
*/
final case class Uri(
scheme: Option[Uri.Scheme] = None,
authority: Option[Uri.Authority] = None,
path: Uri.Path = Uri.Path.empty,
query: Query = Query.empty,
fragment: Option[Uri.Fragment] = None,
) extends QueryOps
with Renderable {
/** Adds the path exactly as described. Any path element must be urlencoded ahead of time.
* @param path the path string to replace
*/
@deprecated("Use {withPath(Uri.Path)} instead", "0.22.0-M1")
def withPath(path: String): Uri = copy(path = Uri.Path.unsafeFromString(path))
def withPath(path: Uri.Path): Uri = copy(path = path)
def withFragment(fragment: Uri.Fragment): Uri = copy(fragment = Option(fragment))
def withoutFragment: Uri = copy(fragment = Option.empty[Uri.Fragment])
/** Urlencodes and adds a path segment to the Uri
*
* @param newSegment the segment to add.
* @return a new uri with the segment added to the path
*/
def addSegment(newSegment: String): Uri = addSegment[String](newSegment)
/** Urlencodes and adds a path segment to the Uri
*
* @tparam Type to be encoded to a Uri Segment
* @param newSegment the segment to add.
* @return a new uri with the segment added to the path
*/
def addSegment[A: Uri.Path.SegmentEncoder](newSegment: A): Uri =
copy(path = path / newSegment)
/** This is an alias to [[addSegment(*]]
*/
def /(newSegment: String): Uri = addSegment[String](newSegment)
/** This is an alias to [[addSegment[*]]]
*/
def /[A: Uri.Path.SegmentEncoder](newSegment: A): Uri = addSegment[A](newSegment)
/** Splits the path segments and adds each of them to the path url-encoded.
* A segment is delimited by /
* @param morePath the path to add
* @return a new uri with the segments added to the path
*/
def addPath(morePath: String): Uri =
copy(path = morePath.split("/").foldLeft(path)((p, segment) => p.addSegment(segment)))
def host: Option[Uri.Host] = authority.map(_.host)
def port: Option[Int] = authority.flatMap(_.port)
def userInfo: Option[Uri.UserInfo] = authority.flatMap(_.userInfo)
def resolve(relative: Uri): Uri = Uri.resolve(this, relative)
/** Representation of the query string as a map
*
* In case a parameter is available in query string but no value is there the
* sequence will be empty. If the value is empty the the sequence contains an
* empty string.
*
* =====Examples=====
* <table>
* <tr><th>Query String</th><th>Map</th></tr>
* <tr><td><code>?param=v</code></td><td><code>Map("param" -> Seq("v"))</code></td></tr>
* <tr><td><code>?param=</code></td><td><code>Map("param" -> Seq(""))</code></td></tr>
* <tr><td><code>?param</code></td><td><code>Map("param" -> Seq())</code></td></tr>
* <tr><td><code>?=value</code></td><td><code>Map("" -> Seq("value"))</code></td></tr>
* <tr><td><code>?p1=v1&p1=v2&p2=v3&p2=v3</code></td><td><code>Map("p1" -> Seq("v1","v2"), "p2" -> Seq("v3","v4"))</code></td></tr>
* </table>
*
* The query string is lazily parsed. If an error occurs during parsing
* an empty `Map` is returned.
*/
def multiParams: Map[String, immutable.Seq[String]] = query.multiParams
/** View of the head elements of the URI parameters in query string.
*
* In case a parameter has no value the map returns an empty string.
*
* @see multiParams
*/
def params: Map[String, String] = query.params
override lazy val renderString: String =
super.renderString
override def render(writer: Writer): writer.type = {
def renderScheme(s: Uri.Scheme): writer.type =
writer << s << ':'
this match {
case Uri(Some(s), Some(a), _, _, _) =>
renderScheme(s) << "//" << a
case Uri(Some(s), None, _, _, _) =>
renderScheme(s)
case Uri(None, Some(a), _, _, _) =>
writer << "//" << a // https://stackoverflow.com/questions/64513631/uri-and-double-slashes/64513776#64513776
case Uri(None, None, _, _, _) =>
}
this match {
case Uri(_, Some(_), p, _, _) if p.nonEmpty && !p.absolute =>
writer << "/" << p
case Uri(None, None, p, _, _) =>
if (!p.absolute && p.segments.headOption.fold(false)(_.toString.contains(":"))) {
writer << "./" << p // https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 last paragraph
} else {
writer << p
}
case Uri(_, _, p, _, _) =>
writer << p
}
if (query.nonEmpty) writer << '?' << query
fragment.foreach { f =>
writer << '#' << Uri.encode(f, spaceIsPlus = false)
}
writer
}
// ///////// Query Operations ///////////////
override protected type Self = Uri
override protected def self: Self = this
override protected def replaceQuery(query: Query): Self = copy(query = query)
/** Converts this request to origin-form, which is the absolute path and optional
* query. If the path is relative, it is assumed to be relative to the root.
*/
def toOriginForm: Uri =
Uri(path = path.toAbsolute, query = query)
}
object Uri extends UriPlatform {
/** Decodes the String to a [[Uri]] using the RFC 3986 uri decoding specification */
def fromString(s: String): ParseResult[Uri] =
ParseResult.fromParser(Parser.uriReferenceUtf8, "Invalid URI")(s)
/** Parses a String to a [[Uri]] according to RFC 3986. If decoding
* fails, throws a [[ParseFailure]].
*
* For totality, call [[fromString]]. For compile-time
* verification of literals, call [[uri]].
*/
def unsafeFromString(s: String): Uri =
fromString(s).valueOr(throw _)
/** Decodes the String to a [[Uri]] using the RFC 7230 section 5.3 uri decoding specification */
def requestTarget(s: String): ParseResult[Uri] =
ParseResult.fromParser(Parser.requestTargetParser, "Invalid request target")(s)
/** A [[org.http4s.Uri]] may begin with a scheme name that refers to a
* specification for assigning identifiers within that scheme.
*
* If the scheme is defined, the URI is absolute. If the scheme is
* not defined, the URI is a relative reference.
*
* @see [[https://datatracker.ietf.org/doc/html/rfc3986#section-3.1 RFC 3986, Section 3.1, Scheme]]
*/
final class Scheme private[http4s] (val value: String) extends Ordered[Scheme] {
override def equals(o: Any): Boolean =
o match {
case that: Scheme => this.value.equalsIgnoreCase(that.value)
case _ => false
}
private[this] var hash = 0
override def hashCode(): Int = {
if (hash == 0)
hash = hashLower(value)
hash
}
override def toString: String = s"Scheme($value)"
override def compare(other: Scheme): Int =
value.compareToIgnoreCase(other.value)
}
object Scheme {
val http: Scheme = new Scheme("http")
val https: Scheme = new Scheme("https")
@deprecated("Renamed to fromString", "0.21.0-M2")
def parse(s: String): ParseResult[Scheme] = fromString(s)
def fromString(s: String): ParseResult[Scheme] =
ParseResult.fromParser(Parser.scheme, "Invalid scheme")(s)
/** Like `fromString`, but throws on invalid input */
def unsafeFromString(s: String): Scheme =
fromString(s).fold(throw _, identity)
implicit val http4sOrderForScheme: Order[Scheme] =
Order.fromComparable
implicit val http4sShowForScheme: Show[Scheme] =
Show.fromToString
implicit val http4sInstancesForScheme: HttpCodec[Scheme] =
new HttpCodec[Scheme] {
def parse(s: String): ParseResult[Scheme] =
Scheme.fromString(s)
def render(writer: Writer, scheme: Scheme): writer.type =
writer << scheme.value
}
}
type Fragment = String
final case class Authority(
userInfo: Option[UserInfo] = None,
host: Host = RegName("localhost"),
port: Option[Int] = None,
) extends Renderable {
override def render(writer: Writer): writer.type =
this match {
case Authority(Some(u), h, None) => writer << u << '@' << h
case Authority(Some(u), h, Some(p)) => writer << u << '@' << h << ':' << p
case Authority(None, h, Some(p)) => writer << h << ':' << p
case Authority(_, h, _) => writer << h
}
}
object Authority {
implicit val catsInstancesForHttp4sAuthority
: Hash[Authority] with Order[Authority] with Show[Authority] =
new Hash[Authority] with Order[Authority] with Show[Authority] {
override def hash(x: Authority): Int =
x.hashCode
override def compare(x: Authority, y: Authority): Int = {
def compareAuthorities[A: Order](focus: Authority => A): Int =
compareField(x, y, focus)
reduceComparisons(
compareAuthorities(_.userInfo),
Eval.later(compareAuthorities(_.host)),
Eval.later(compareAuthorities(_.port)),
)
}
override def show(a: Authority): String =
a.renderString
}
}
final class Path private (
val segments: Vector[Path.Segment],
val absolute: Boolean,
val endsWithSlash: Boolean,
) extends Renderable {
def isEmpty: Boolean = segments.isEmpty
def nonEmpty: Boolean = segments.nonEmpty
override def equals(obj: Any): Boolean =
obj match {
case p: Path => doEquals(p)
case _ => false
}
private def doEquals(path: Path): Boolean =
this.segments == path.segments && path.absolute == this.absolute && path.endsWithSlash == this.endsWithSlash
override def hashCode(): Int = {
var hash = Path.hashSeed
hash = MurmurHash3.mix(hash, segments.##)
hash = MurmurHash3.mix(hash, absolute.##)
hash = MurmurHash3.mix(hash, endsWithSlash.##)
MurmurHash3.finalizeHash(hash, 3)
}
def render(writer: Writer): writer.type = {
val start = if (absolute) "/" else ""
writer << start << segments.iterator.mkString("/")
if (endsWithSlash && segments.nonEmpty) writer << "/" else writer
}
override val renderString: String = super.renderString
override def toString: String = renderString
/** This is an alias to [[addSegment(*]]
*/
def /(segment: Path.Segment): Path = addSegment(segment)
/** This is an alias to [[addSegment[*]]
*/
def /[A: Path.SegmentEncoder](segment: A): Path = addSegment[A](segment)
def addSegment(segment: Path.Segment): Path = {
val segments = this.segments :+ segment
val endsWithSlash = if (segment.isEmpty) this.endsWithSlash else false
Path(
segments = segments,
absolute = absolute || this.segments.isEmpty,
endsWithSlash = endsWithSlash,
)
}
def addSegment[A](segment: A)(implicit encoder: Path.SegmentEncoder[A]): Path =
addSegment(encoder.toSegment(segment))
def addSegments(value: Seq[Path.Segment]): Path =
if (value.isEmpty) this
else {
val segments = this.segments ++ value
val endsWithSlash = value match {
case Nil | Seq(Path.Segment.empty) =>
this.endsWithSlash
case _ =>
false
}
Path(
segments = segments,
absolute = absolute || this.segments.isEmpty,
endsWithSlash = endsWithSlash,
)
}
def normalize: Path = Path(segments.filterNot(_.isEmpty))
/* Merge paths per RFC 3986 5.2.3 */
def merge(path: Path): Path = {
val merge = if (isEmpty || endsWithSlash) segments else segments.init
Path(merge ++ path.segments, absolute = absolute, endsWithSlash = path.endsWithSlash)
}
def concat(path: Path): Path =
Path(
segments ++ path.segments,
absolute = this.absolute || (this.isEmpty && path.absolute),
endsWithSlash = path.endsWithSlash || (path.isEmpty && this.endsWithSlash),
)
def startsWith(path: Path): Boolean = segments.startsWith(path.segments)
def startsWithString(path: String): Boolean = startsWith(Path.unsafeFromString(path))
@deprecated("Misnamed, use findSplit(prefix) instead", since = "0.22.0-M1")
def indexOf(prefix: Path): Option[Int] = findSplit(prefix)
@deprecated("Misnamed, use findSplitOfString(prefix) instead", since = "0.22.0-M1")
def indexOfString(path: String): Option[Int] = findSplit(Path.unsafeFromString(path))
def findSplit(prefix: Path): Option[Int] =
if (startsWith(prefix)) Some(prefix.segments.size)
else None
def findSplitOfString(path: String): Option[Int] = findSplit(Path.unsafeFromString(path))
def splitAt(idx: Int): (Path, Path) =
if (idx <= 0) {
(Path.empty, this)
} else if (idx < segments.size) {
val (start, end) = segments.splitAt(idx)
(
Path(start, absolute = absolute),
Path(end, absolute = true, endsWithSlash = endsWithSlash),
)
} else if (idx == segments.size) {
(Path(segments, absolute = absolute), if (endsWithSlash) Path.Root else Path.empty)
} else {
(this, Path.empty)
}
private def copy(
segments: Vector[Path.Segment] = segments,
absolute: Boolean = absolute,
endsWithSlash: Boolean = endsWithSlash,
): Path = Path(segments, absolute, endsWithSlash)
def dropEndsWithSlash: Path = copy(endsWithSlash = false)
def addEndsWithSlash: Path = copy(endsWithSlash = true)
def toAbsolute: Path = copy(absolute = true)
def toRelative: Path = copy(absolute = false)
}
object Path {
val empty: Path = new Path(Vector.empty, absolute = false, endsWithSlash = false)
val Root: Path = new Path(Vector.empty, absolute = true, endsWithSlash = true)
lazy val Asterisk: Path =
new Path(Vector(Segment("*")), absolute = false, endsWithSlash = false)
private val hashSeed: Int =
MurmurHash3.mix(MurmurHash3.productSeed, "Uri.Path".##)
final class Segment private (val encoded: String) {
def isEmpty = encoded.isEmpty
override def equals(obj: Any): Boolean =
obj match {
case s: Segment => s.encoded == encoded
case _ => false
}
override def hashCode(): Int = encoded.hashCode
def decoded(
charset: JCharset = StandardCharsets.UTF_8,
plusIsSpace: Boolean = false,
toSkip: Char => Boolean = Function.const(false),
): String =
Uri.decode(encoded, charset, plusIsSpace, toSkip)
override val toString: String = encoded
}
object Segment extends (String => Segment) {
def apply(value: String): Segment = new Segment(pathEncode(value))
def encoded(value: String): Segment = new Segment(value)
val empty: Segment = Segment("")
implicit val http4sInstancesForSegment: Order[Segment] =
new Order[Segment] {
def compare(x: Segment, y: Segment): Int =
x.encoded.compare(y.encoded)
}
}
trait SegmentEncoder[A] extends Serializable {
def toSegment(a: A): Segment
final def contramap[B](f: B => A): SegmentEncoder[B] =
b => this.toSegment(f(b))
}
object SegmentEncoder {
def apply[A](implicit segmentEncoder: SegmentEncoder[A]): SegmentEncoder[A] =
segmentEncoder
def instance[A](f: A => Segment): SegmentEncoder[A] = f.apply _
def fromToString[A]: SegmentEncoder[A] = v => Segment(v.toString())
def fromShow[A](implicit show: Show[A]): SegmentEncoder[A] =
v => Segment(show.show(v))
implicit val segmentSegmentEncoder: SegmentEncoder[Segment] = identity[Segment] _
implicit val charSegmentEncoder: SegmentEncoder[Char] = fromToString
implicit val stringSegmentEncoder: SegmentEncoder[String] = Segment.apply _
implicit val booleanSegmentEncoder: SegmentEncoder[Boolean] = fromToString
implicit val byteSegmentEncoder: SegmentEncoder[Byte] = fromToString
implicit val shortSegmentEncoder: SegmentEncoder[Short] = fromToString
implicit val intSegmentEncoder: SegmentEncoder[Int] = fromToString
implicit val longSegmentEncoder: SegmentEncoder[Long] = fromToString
implicit val bigIntSegmentEncoder: SegmentEncoder[BigInt] = fromToString
implicit val floatSegmentEncoder: SegmentEncoder[Float] = fromToString
implicit val doubleSegmentEncoder: SegmentEncoder[Double] = fromToString
implicit val bigDecimalSegmentEncoder: SegmentEncoder[BigDecimal] = fromToString
implicit val uuidSegmentEncoder: SegmentEncoder[java.util.UUID] = fromToString
implicit val contravariantInstance: Contravariant[SegmentEncoder] =
new Contravariant[SegmentEncoder] {
override def contramap[A, B](fa: SegmentEncoder[A])(f: B => A): SegmentEncoder[B] =
fa.contramap(f)
}
}
/** This constructor allows you to construct the path directly.
* Each path segment needs to be encoded for it to be used here.
*
* @param segments the segments that this path consists of. MUST be Urlencoded.
* @param absolute if the path is absolute. I.E starts with a "/"
* @param endsWithSlash if the path is a "directory", ends with a "/"
* @return a Uri.Path that can be used in Uri, or by itself.
*/
def apply(
segments: Vector[Segment],
absolute: Boolean = false,
endsWithSlash: Boolean = false,
): Path =
// make sure that we never end up with Path(Vector(), true, true) or Path(Vector(), false, true)
if (segments.isEmpty && (absolute || endsWithSlash)) Root
else new Path(segments, absolute, endsWithSlash)
// def unapply(path: Path): Some[(Vector[Segment], Boolean, Boolean)] =
// Some((path.segments, path.absolute, path.endsWithSlash))
@deprecated(message = "Use unsafeFromString instead", since = "0.22.0-M6")
def fromString(fromPath: String): Path =
unsafeFromString(fromPath)
def unsafeFromString(fromPath: String): Path =
fromPath match {
case "" => empty
case "/" => Root
case pth =>
val absolute = pth.startsWith("/")
val relative = if (absolute) pth.substring(1) else pth
Path(
segments = relative
.split("/")
.foldLeft(Vector.empty[Segment])((path, segment) => path :+ Segment.encoded(segment)),
absolute = absolute,
endsWithSlash = relative.endsWith("/"),
)
}
def http4sInstancesForPath: Order[Path] with Semigroup[Path] = http4sInstancesForPathBinCompat
implicit val http4sInstancesForPathBinCompat: Order[Path] with Semigroup[Path] with Hash[Path] =
new Order[Path] with Semigroup[Path] with Hash[Path] {
def compare(x: Path, y: Path): Int = {
def comparePaths[A: Order](focus: Path => A): Int =
compareField(x, y, focus)
reduceComparisons(
comparePaths(_.absolute),
Eval.later(comparePaths(_.segments)),
Eval.later(comparePaths(_.endsWithSlash)),
)
}
def combine(x: Path, y: Path): Path = x.concat(y)
def hash(x: Path): Int = x.##
}
}
/** The userinfo subcomponent may consist of a user name and,
* optionally, scheme-specific information about how to gain
* authorization to access the resource. The user information, if
* present, is followed by a commercial at-sign ("@") that delimits
* it from the host.
*
* @param username The username component, decoded.
*
* @param password The password, decoded. Passing a password in
* clear text in a URI is a security risk and deprecated by RFC
* 3986, but preserved in this model for losslessness.
*
* @see [[https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1 RFC 3986, Section 3.2.1, User Information]]
*/
final case class UserInfo private ( // scalafix:ok Http4sGeneralLinters.nonValidatingCopyConstructor; bincompat until 1.0
username: String,
password: Option[String],
) extends Ordered[UserInfo] {
override def compare(that: UserInfo): Int =
username.compareTo(that.username) match {
case 0 => Ordering.Option[String].compare(password, that.password)
case cmp => cmp
}
}
object UserInfo {
/** Parses a userInfo from a percent-encoded string. */
def fromString(s: String): ParseResult[UserInfo] =
fromStringWithCharset(s, StandardCharsets.UTF_8)
/** Parses a userInfo from a string percent-encoded in a specific charset. */
def fromStringWithCharset(s: String, cs: JCharset): ParseResult[UserInfo] =
ParseResult.fromParser(Parser.userinfo(cs), "Invalid userinfo")(s)
implicit val http4sInstancesForUserInfo
: HttpCodec[UserInfo] with Order[UserInfo] with Hash[UserInfo] with Show[UserInfo] =
new HttpCodec[UserInfo] with Order[UserInfo] with Hash[UserInfo] with Show[UserInfo] {
def parse(s: String): ParseResult[UserInfo] =
UserInfo.fromString(s)
def render(writer: Writer, userInfo: UserInfo): writer.type = {
writer << encodeUsername(userInfo.username)
userInfo.password.foreach(writer << ":" << encodePassword(_))
writer
}
private val SkipEncodeInUsername =
Unreserved ++ "!$&'()*+,;="
private def encodeUsername(s: String, charset: JCharset = StandardCharsets.UTF_8): String =
encode(s, charset, false, SkipEncodeInUsername)
private val SkipEncodeInPassword =
SkipEncodeInUsername ++ ":"
private def encodePassword(s: String, charset: JCharset = StandardCharsets.UTF_8): String =
encode(s, charset, false, SkipEncodeInPassword)
def compare(x: UserInfo, y: UserInfo): Int = x.compareTo(y)
def hash(x: UserInfo): Int = x.hashCode
def show(x: UserInfo): String = x.toString
}
}
sealed trait Host extends Renderable {
def value: String
override def render(writer: Writer): writer.type =
this match {
case RegName(n) => writer << encode(n.toString)
case a: Ipv4Address => writer << a.value
case a: Ipv6Address => writer << '[' << a << ']'
}
def toIpAddress: Option[ip4s.IpAddress] = this match {
case Ipv4Address(a) => Some(a)
case Ipv6Address(a) => Some(a)
case RegName(_) => None
}
}
object Host {
def fromString(s: String): ParseResult[Host] =
ParseResult.fromParser(Parser.host, "Invalid host")(s)
def unsafeFromString(s: String): Host =
fromString(s).fold(throw _, identity)
/** Create a [[Host]] value from an [[com.comcast.ip4s.IpAddress]].
*
* This is a convenience method for creating the correct host based on
* the underlying IP protocol version of the given address, either IPv4
* or IPv6.
*/
def fromIpAddress(value: ip4s.IpAddress): Host =
value match {
case value: ip4s.Ipv4Address =>
Ipv4Address(value)
case value: ip4s.Ipv6Address =>
Ipv6Address(value)
}
/** Create a [[Host]] value from a [[com.comcast.ip4s.Host]].
*/
def fromIp4sHost(value: ip4s.Host): Host = value match {
case address: ip4s.IpAddress =>
fromIpAddress(address)
case hostname: ip4s.Hostname =>
RegName.fromHostname(hostname)
case idn: ip4s.IDN =>
RegName.fromHostname(idn.hostname)
}
implicit val catsInstancesForHttp4sUriHost: Hash[Host] with Order[Host] with Show[Host] =
new Hash[Host] with Order[Host] with Show[Host] {
override def hash(x: Host): Int =
x match {
case x: Ipv4Address =>
x.hash
case x: Ipv6Address =>
x.hash
case x: RegName =>
x.hash
}
override def compare(x: Host, y: Host): Int =
(x, y) match {
case (x: Ipv4Address, y: Ipv4Address) =>
x.compare(y)
case (x: Ipv6Address, y: Ipv6Address) =>
x.compare(y)
case (x: RegName, y: RegName) =>
x.compare(y)
// Differing ADT constructors
// Ipv4Address is arbitrarily considered > all Ipv6Address and RegName
case (_: Ipv4Address, _) =>
1
case (_, _: Ipv4Address) =>
-1
// Ipv6Address is arbitrarily considered > all RegName
case (_: Ipv6Address, _) =>
1
case (_, _: Ipv6Address) =>
-1
}
override def show(a: Host): String =
a.renderString
}
}
final case class Ipv4Address(address: ip4s.Ipv4Address)
extends Host
with Ordered[Ipv4Address]
with Serializable {
override def toString: String = s"Ipv4Address($value)"
override def compare(that: Ipv4Address): Int =
this.address.compare(that.address)
def toByteArray: Array[Byte] =
address.toBytes
@deprecated("Use address.toInetAddress", "0.23.5")
def toInet4Address: Inet4Address =
address.toInetAddress
def value: String =
address.toString
}
object Ipv4Address {
def fromString(s: String): ParseResult[Ipv4Address] =
ParseResult.fromParser(Parser.ipv4Address, "Invalid IPv4 Address")(s)
/** Like `fromString`, but throws on invalid input */
def unsafeFromString(s: String): Ipv4Address =
fromString(s).fold(throw _, identity)
def fromByteArray(bytes: Array[Byte]): ParseResult[Ipv4Address] =
bytes match {
case Array(a, b, c, d) =>
Right(fromBytes(a, b, c, d))
case _ =>
Left(ParseFailure("Invalid Ipv4Address", s"Byte array not exactly four bytes: ${bytes}"))
}
def fromBytes(a: Byte, b: Byte, c: Byte, d: Byte): Ipv4Address =
apply(ip4s.Ipv4Address.fromBytes(a.toInt, b.toInt, c.toInt, d.toInt))
@deprecated("Use apply(ip4s.Ipv4Address.fromInet4Address(address))", "0.23.5")
def fromInet4Address(address: Inet4Address): Ipv4Address =
apply(ip4s.Ipv4Address.fromInet4Address(address))
implicit val http4sInstancesForIpv4Address: HttpCodec[Ipv4Address]
with Order[Ipv4Address]
with Hash[Ipv4Address]
with Show[Ipv4Address] =
new HttpCodec[Ipv4Address]
with Order[Ipv4Address]
with Hash[Ipv4Address]
with Show[Ipv4Address] {
def parse(s: String): ParseResult[Ipv4Address] =
Ipv4Address.fromString(s)
def render(writer: Writer, ipv4: Ipv4Address): writer.type =
writer << ipv4.value
def compare(x: Ipv4Address, y: Ipv4Address): Int = x.compareTo(y)
def hash(x: Ipv4Address): Int = x.hashCode
def show(x: Ipv4Address): String = x.toString
}
}
final case class Ipv6Address(address: ip4s.Ipv6Address)
extends Host
with Ordered[Ipv6Address]
with Serializable {
override def compare(that: Ipv6Address): Int =
this.address.compare(that.address)
def toByteArray: Array[Byte] =
address.toBytes
@deprecated("Use address.toInetAddress", "0.23.5")
def toInetAddress: InetAddress =
address.toInetAddress
def value: String =
address.toString
}
object Ipv6Address {
def fromString(s: String): ParseResult[Ipv6Address] =
ParseResult.fromParser(Parser.ipv6Address, "Invalid IPv6 address")(s)
/** Like `fromString`, but throws on invalid input */
def unsafeFromString(s: String): Ipv6Address =
fromString(s).fold(throw _, identity)
def fromByteArray(bytes: Array[Byte]): ParseResult[Ipv6Address] =
ip4s.Ipv6Address.fromBytes(bytes) match {
case Some(address) => Right(Ipv6Address(address))
case None =>
Left(
ParseFailure("Invalid Ipv6Address", s"Byte array not exactly 16 bytes: ${bytes.toSeq}")
)
}
@deprecated("Use apply(ip4s.Ipv6Address.fromInet6Address(address))", "0.23.5")
def fromInet6Address(address: Inet6Address): Ipv6Address =
apply(ip4s.Ipv6Address.fromInet6Address(address))
def fromShorts(a: Short, b: Short, c: Short, d: Short, e: Short, f: Short, g: Short, h: Short)
: Ipv6Address = {
val bb = ByteBuffer.allocate(16)
bb.putShort(a)
bb.putShort(b)
bb.putShort(c)
bb.putShort(d)
bb.putShort(e)
bb.putShort(f)
bb.putShort(g)
bb.putShort(h)
fromByteArray(bb.array).valueOr(throw _)
}
implicit val http4sInstancesForIpv6Address: HttpCodec[Ipv6Address]
with Order[Ipv6Address]
with Hash[Ipv6Address]
with Show[Ipv6Address] =
new HttpCodec[Ipv6Address]
with Order[Ipv6Address]
with Hash[Ipv6Address]
with Show[Ipv6Address] {
def parse(s: String): ParseResult[Ipv6Address] =
Ipv6Address.fromString(s)
def render(writer: Writer, ipv6: Ipv6Address): writer.type =
writer << ipv6.value
def compare(x: Ipv6Address, y: Ipv6Address): Int = x.compareTo(y)
def hash(x: Ipv6Address): Int = x.hashCode
def show(x: Ipv6Address): String = x.toString
}
}
final case class RegName(host: CIString) extends Host {
def value: String = host.toString
/** Converts this registered name to a Hostname. In the spec, for
* generic schemes, a registered name need not be a valid host
* name. In HTTP practice, this conversion should succeed.
*/
def toHostname: Option[ip4s.Hostname] =
ip4s.Hostname.fromString(host.toString)
}
object RegName {
def apply(name: String): RegName = new RegName(CIString(name))
def fromHostname(hostname: ip4s.Hostname): RegName =
RegName(CIString(hostname.toString))
implicit val catsInstancesForHttp4sUriRegName
: Hash[RegName] with Order[RegName] with Show[RegName] =
new Hash[RegName] with Order[RegName] with Show[RegName] {
override def hash(x: RegName): Int =
x.hashCode
override def compare(x: RegName, y: RegName): Int =
x.host.compare(y.host)
override def show(a: RegName): String =
a.toString
}
}
/** Resolve a relative Uri reference, per RFC 3986 sec 5.2
*/
def resolve(base: Uri, reference: Uri): Uri = {
val target = (base, reference) match {
case (_, Uri(Some(_), _, _, _, _)) => reference
case (Uri(s, _, _, _, _), Uri(_, a @ Some(_), p, q, f)) => Uri(s, a, p, q, f)
case (Uri(s, a, p, q, _), Uri(_, _, pa, Query.empty, f)) if pa.isEmpty && !pa.absolute =>
Uri(s, a, p, q, f)
case (Uri(s, a, p, _, _), Uri(_, _, pa, q, f)) if pa.isEmpty && !pa.absolute =>
Uri(s, a, p, q, f)
case (Uri(s, a, bp, _, _), Uri(_, _, p, q, f)) =>
if (p.absolute) Uri(s, a, p, q, f)
else Uri(s, a, bp.merge(p), q, f)
}
target.withPath(removeDotSegments(target.path))
}
/** Remove dot sequences from a Path, per RFC 3986 Sec 5.2.4
* Adapted from"
* https://github.com/Norconex/commons-lang/blob/c83fdeac7a60ac99c8602e0b47056ad77b08f570/norconex-commons-lang/src/main/java/com/norconex/commons/lang/url/URLNormalizer.java#L429
*/
def removeDotSegments(path: Uri.Path): Uri.Path = {
// (Bulleted comments are from RFC3986, section-5.2.4)
// 1. The input buffer is initialized with the now-appended path
// components and the output buffer is initialized to the empty
// string.
val in = new StringBuilder(path.renderString)
val out = new StringBuilder
// 2. While the input buffer is not empty, loop as follows:
while (in.nonEmpty)
// A. If the input buffer begins with a prefix of "../" or "./",
// then remove that prefix from the input buffer; otherwise,
if (startsWith(in, "../"))
deleteStart(in, "../")
else if (startsWith(in, "./"))
deleteStart(in, "./")
// B. if the input buffer begins with a prefix of "/./" or "/.",
// where "." is a complete path segment, then replace that
// prefix with "/" in the input buffer; otherwise,
else if (startsWith(in, "/./"))
replaceStart(in, "/./", "/")
else if (equalStrings(in, "/."))
replaceStart(in, "/.", "/")
// C. if the input buffer begins with a prefix of "/../" or "/..",
// where ".." is a complete path segment, then replace that
// prefix with "/" in the input buffer and remove the last
// segment and its preceding "/" (if any) from the output
// buffer; otherwise,
else if (startsWith(in, "/../")) {
replaceStart(in, "/../", "/")
removeLastSegment(out)
} else if (equalStrings(in, "/..")) {
replaceStart(in, "/..", "/")
removeLastSegment(out)
}
// D. if the input buffer consists only of "." or "..", then remove
// that from the input buffer; otherwise,
else if (equalStrings(in, ".."))
deleteStart(in, "..")
else if (equalStrings(in, "."))
deleteStart(in, ".")
// E. move the first path segment in the input buffer to the end of
// the output buffer, including the initial "/" character (if
// any) and any subsequent characters up to, but not including,
// the next "/" character or the end of the input buffer.
else
in.indexOf("/", 1) match {
case nextSlashIndex if nextSlashIndex > -1 =>